diff --git a/.gitattributes b/.gitattributes index 52d3dd69f..c702320ff 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ tests/** linguist-vendored +*.sh text eol=lf diff --git a/bindings/python/src/geometry/CMakeLists.txt b/bindings/python/src/geometry/CMakeLists.txt index 628459dae..65b706467 100644 --- a/bindings/python/src/geometry/CMakeLists.txt +++ b/bindings/python/src/geometry/CMakeLists.txt @@ -33,6 +33,7 @@ add_geode_python_binding( "intersection_detection.cpp" "mensuration.cpp" "nn_search.cpp" + "octree.cpp" "perpendicular.cpp" "point.cpp" "points_sort.cpp" diff --git a/bindings/python/src/geometry/geometry.cpp b/bindings/python/src/geometry/geometry.cpp index 3d8bed14b..7fc3e37c1 100644 --- a/bindings/python/src/geometry/geometry.cpp +++ b/bindings/python/src/geometry/geometry.cpp @@ -37,6 +37,7 @@ namespace geode void define_intersection_detection( pybind11::module& ); void define_mensuration( pybind11::module& ); void define_nn_search( pybind11::module& ); + void define_octree( pybind11::module& ); void define_perpendicular( pybind11::module& ); void define_point( pybind11::module& ); void define_points_sort( pybind11::module& ); @@ -52,12 +53,15 @@ namespace geode PYBIND11_MODULE( opengeode_py_geometry, module ) { + // Octree returns the AttributeManager of opengeode_py_basic + geode::import_binding_dependency( module, "opengeode_py_basic" ); pybind11::add_ostream_redirect( module ); module.doc() = "Geometry of OpenGeode: Point, Vector, Frame, CoordinateSystem, Angle, " "BoundingBox, basic objects (Segment, Triangle, Tetrahedron, Plane, " "Sphere, Circle, Cylinder, InfiniteLine, Ray), nearest neighbor " - "search (NNSearch) and the geometric predicates and computations " + "search (NNSearch), adaptive octree (Octree) and the geometric " + "predicates and computations " "on them (distance, projection, intersection, position, sign, " "mensuration, quality, barycentric coordinates). Functions and " "classes depending on the dimension end with 2D or 3D"; @@ -77,6 +81,7 @@ PYBIND11_MODULE( opengeode_py_geometry, module ) geode::define_intersection_detection( module ); geode::define_mensuration( module ); geode::define_nn_search( module ); + geode::define_octree( module ); geode::define_perpendicular( module ); geode::define_points_sort( module ); geode::define_position( module ); diff --git a/bindings/python/src/geometry/octree.cpp b/bindings/python/src/geometry/octree.cpp new file mode 100644 index 000000000..37d32291f --- /dev/null +++ b/bindings/python/src/geometry/octree.cpp @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include "../common.hpp" + +#include + +#include + +namespace +{ + template < geode::index_t dimension > + void check_cell( std::string_view context, + const geode::Octree< dimension >& octree, + geode::index_t cell ) + { + geode::check_index( context, "cell", cell, octree.nb_cells() ); + } + + template < geode::index_t dimension > + void define_octree( pybind11::module& module ) + { + using Octree = geode::Octree< dimension >; + const auto name = absl::StrCat( "Octree", dimension, "D" ); + pybind11::class_< Octree > octree( module, name.c_str(), + "Adaptive octree (quadtree in 2D) covering an axis-aligned box. " + "The box is split into a grid of root cells (along each axis, " + "round( side / smallest side ) cells, at least 1), then each leaf " + "can be refined into NB_CHILDREN children. Cells have stable " + "indices: roots first (axis 0 varying fastest), then children " + "appended by blocks of NB_CHILDREN each time a leaf is refined; " + "there is no coarsening. Each cell has an integer anchor (its " + "minimal corner) on the finest lattice: a cell at level L spans " + "2^(max_depth() - L) lattice units along each axis" ); + octree.attr( "NB_CHILDREN" ) = Octree::NB_CHILDREN; + octree.attr( "NB_FACE_CHILDREN" ) = Octree::NB_FACE_CHILDREN; + pybind11::native_enum< typename Octree::FACE_SIDE >( octree, "FaceSide", + "enum.Enum", + "With an axis, one of the 2 * dimension faces of a cell: the face " + "of minimal (lower) or maximal (upper) coordinate along the axis" ) + .value( "lower", Octree::FACE_SIDE::lower ) + .value( "upper", Octree::FACE_SIDE::upper ) + .finalize(); + pybind11::native_enum< typename Octree::BALANCE_TYPE >( octree, + "BalanceType", "enum.Enum", + "Adjacency enforced by balance(): faces (leaves sharing a face, " + "an edge in 2D) or full (leaves sharing a face, an edge or a " + "vertex)" ) + .value( "faces", Octree::BALANCE_TYPE::faces ) + .value( "full", Octree::BALANCE_TYPE::full ) + .finalize(); + octree.def( pybind11::init<>(), "Create an empty octree (no cell)" ) + .def( pybind11::init< const geode::BoundingBox< dimension >& >(), + pybind11::arg( "bbox" ), + "Create an octree covering the box with only root cells. " + "Raise an OpenGeodeDataError if a box side is not larger " + "than GLOBAL_EPSILON or if the box is too elongated (more " + "root cells than the lattice can hold)" ) + .def( "max_depth", &Octree::max_depth, + "Return the maximal level a cell can have (roots are at " + "level 0)" ) + .def( "nb_cells", &Octree::nb_cells, + "Return the number of cells, roots and refined cells " + "included" ) + .def( "nb_root_cells", &Octree::nb_root_cells, + "Return the number of root cells along each axis" ) + .def( + "is_leaf", + []( const Octree& self, geode::index_t cell ) { + check_cell( "is_leaf", self, cell ); + return self.is_leaf( cell ); + }, + pybind11::arg( "cell" ), "Return True if the cell is a leaf" ) + .def( + "level", + []( const Octree& self, geode::index_t cell ) { + check_cell( "level", self, cell ); + return self.level( cell ); + }, + pybind11::arg( "cell" ), + "Return the level of the cell (roots are at level 0)" ) + .def( + "parent", + []( const Octree& self, geode::index_t cell ) { + check_cell( "parent", self, cell ); + return self.parent( cell ); + }, + pybind11::arg( "cell" ), + "Return the parent cell, None for a root cell" ) + .def( + "children", + []( const Octree& self, geode::index_t cell ) { + check_cell( "children", self, cell ); + return self.children( cell ); + }, + pybind11::arg( "cell" ), + "Return the index of the first child, None for a leaf. The " + "NB_CHILDREN children are contiguous; bit d of (child - " + "first child) is set when the child is in the upper half of " + "the cell along axis d" ) + .def( + "cell_bounding_box", + []( const Octree& self, geode::index_t cell ) { + check_cell( "cell_bounding_box", self, cell ); + return self.cell_bounding_box( cell ); + }, + pybind11::arg( "cell" ), + "Return the bounding box of the cell, computed from lattice " + "values only: cells sharing a face have exactly the same face " + "coordinates" ) + .def( + "cell_center", + []( const Octree& self, geode::index_t cell ) { + check_cell( "cell_center", self, cell ); + return self.cell_center( cell ); + }, + pybind11::arg( "cell" ), "Return the center of the cell" ) + .def( + "cell_lengths", + []( const Octree& self, geode::index_t cell ) { + check_cell( "cell_lengths", self, cell ); + return self.cell_lengths( cell ); + }, + pybind11::arg( "cell" ), + "Return the cell length along each axis: root cell length / " + "2^level" ) + .def( + "cell_anchor", + []( const Octree& self, geode::index_t cell ) { + check_cell( "cell_anchor", self, cell ); + return self.cell_anchor( cell ); + }, + pybind11::arg( "cell" ), + "Return the minimal corner of the cell on the finest lattice " + "(a copy)" ) + .def( "cell", &Octree::cell, pybind11::arg( "level" ), + pybind11::arg( "anchor" ), + "Return the cell with the given level and anchor, None if it " + "does not exist (not created, level above max_depth(), " + "anchor outside the domain or not aligned on the cell size " + "of this level)" ) + .def( "leaves", + pybind11::overload_cast<>( &Octree::leaves, pybind11::const_ ), + "Return all the leaf cells, sorted by cell index" ) + .def( + "leaves", + []( const Octree& self, geode::index_t cell ) { + check_cell( "leaves", self, cell ); + return self.leaves( cell ); + }, + pybind11::arg( "cell" ), + "Return the leaf cells of the subtree of the cell (the cell " + "itself if it is a leaf), in depth-first order, children in " + "index order" ) + .def( "domain_bounding_box", &Octree::domain_bounding_box, + "Return the domain covered by the root cells: exactly the " + "bounding box given at construction" ) + .def( "leaf_containing", &Octree::leaf_containing, + pybind11::arg( "point" ), + "Return the leaf containing the point, None if the point is " + "outside domain_bounding_box() (no tolerance). Cells are " + "closed: on a face shared by several leaves, the leaf on the " + "upper side is returned, except on the domain upper border" ) + .def( + "traverse", + []( const Octree& self, const pybind11::function& filter, + const pybind11::function& action ) { + self.traverse( + [&filter]( geode::index_t cell, + const geode::BoundingBox< dimension >& box ) { + return filter( cell, box ).template cast< bool >(); + }, + [&action]( geode::index_t leaf ) { + action( leaf ); + } ); + }, + pybind11::arg( "filter" ), pybind11::arg( "action" ), + "Depth-first traversal from the roots, in index order. " + "filter(cell, box) is called on each visited cell with its " + "bounding box: if it returns False, the cell and its subtree " + "are skipped. action(leaf) is called on each leaf accepted by " + "the filter" ) + .def( + "refine", + []( Octree& self, geode::index_t leaf ) { + check_cell( "refine", self, leaf ); + return self.refine( leaf ); + }, + pybind11::arg( "leaf" ), + "Split a leaf into NB_CHILDREN children appended at the end " + "of the cells, copying all its cell attribute values to them, " + "and return the index of the first child. Raise an " + "OpenGeodeDataError if the cell is not a leaf or is at " + "max_depth()" ) + .def( + "face_neighbor_leaves", + []( const Octree& self, geode::index_t cell, + geode::local_index_t axis, + typename Octree::FACE_SIDE side ) { + check_cell( "face_neighbor_leaves", self, cell ); + geode::check_direction( + "face_neighbor_leaves", axis, dimension ); + const auto neighbors = + self.face_neighbor_leaves( cell, axis, side ); + return std::vector< geode::index_t >( + neighbors.begin(), neighbors.end() ); + }, + pybind11::arg( "cell" ), pybind11::arg( "axis" ), + pybind11::arg( "side" ), + "Return the leaves outside the cell (a leaf or not) sharing a " + "part of its face given by axis and side: the same-size leaf " + "on the other side, else the coarser leaf containing it, else " + "all the finer leaves touching the face (depth-first). Empty " + "on the domain border" ) + .def( "balance", &Octree::balance, + pybind11::call_guard< pybind11::gil_scoped_release >(), + pybind11::arg( "type" ), + "Refine leaves until any two adjacent leaves (see " + "BalanceType) differ by at most one level. Existing indices " + "are unchanged, new cells inherit attribute values as in " + "refine(); the result is deterministic" ) + .def( "cell_attribute_manager", &Octree::cell_attribute_manager, + pybind11::return_value_policy::reference_internal, + "Return the manager of the attributes on all the cells " + "(refined cells included); refine() copies the values of a " + "leaf to its children" ); + } +} // namespace + +namespace geode +{ + void define_octree( pybind11::module& module ) + { + ::define_octree< 2 >( module ); + ::define_octree< 3 >( module ); + } +} // namespace geode diff --git a/bindings/python/src/mesh/helpers/convert_solid_mesh.cpp b/bindings/python/src/mesh/helpers/convert_solid_mesh.cpp index e9f4f8256..19651d0f2 100644 --- a/bindings/python/src/mesh/helpers/convert_solid_mesh.cpp +++ b/bindings/python/src/mesh/helpers/convert_solid_mesh.cpp @@ -23,6 +23,9 @@ #include "../../common.hpp" +#include + +#include #include #include #include @@ -43,6 +46,16 @@ namespace geode &convert_grid_into_tetrahedral_solid, pybind11::arg( "grid" ), pybind11::call_guard< pybind11::gil_scoped_release >(), "Return a tetrahedral solid obtained by splitting every cell " - "of the 3D grid into tetrahedra" ); + "of the 3D grid into tetrahedra" ) + .def( "convert_octree_into_hybrid_solid", + &convert_octree_into_hybrid_solid, pybind11::arg( "octree" ), + pybind11::call_guard< pybind11::gil_scoped_release >(), + "Return a hybrid solid with one hexahedron per leaf of the 3D " + "octree (in the order of Octree3D.leaves()), vertices shared " + "between leaves at the same lattice position, and the cell " + "attributes of the leaves transferred to the polyhedra. The " + "mesh is non-conforming at level jumps (no hanging vertex in " + "the coarser cells, missing adjacencies): it is meant for " + "visualization and export" ); } } // namespace geode diff --git a/bindings/python/src/mesh/helpers/convert_surface_mesh.cpp b/bindings/python/src/mesh/helpers/convert_surface_mesh.cpp index 6b2ce4947..475836900 100644 --- a/bindings/python/src/mesh/helpers/convert_surface_mesh.cpp +++ b/bindings/python/src/mesh/helpers/convert_surface_mesh.cpp @@ -23,6 +23,8 @@ #include "../../common.hpp" +#include + #include #include #include @@ -52,6 +54,17 @@ namespace geode pybind11::call_guard< pybind11::gil_scoped_release >(), "Return a triangulated surface obtained by splitting every " "cell of the 2D grid into triangles" ) + .def( "convert_octree_into_polygonal_surface", + &convert_octree_into_polygonal_surface, + pybind11::arg( "octree" ), + pybind11::call_guard< pybind11::gil_scoped_release >(), + "Return a polygonal surface with one quadrangle per leaf of " + "the 2D octree (in the order of Octree2D.leaves()), vertices " + "shared between leaves at the same lattice position, and the " + "cell attributes of the leaves transferred to the polygons. " + "The mesh is non-conforming at level jumps (no hanging vertex " + "in the coarser cells, missing adjacencies): it is meant for " + "visualization and export" ) .def( "triangulate_surface_mesh2D", static_cast< void ( * )( SurfaceMesh< 2 >& ) >( &triangulate_surface_mesh< 2 > ), diff --git a/bindings/python/tests/geometry/CMakeLists.txt b/bindings/python/tests/geometry/CMakeLists.txt index 505a809fa..e4c84f91a 100644 --- a/bindings/python/tests/geometry/CMakeLists.txt +++ b/bindings/python/tests/geometry/CMakeLists.txt @@ -64,6 +64,12 @@ add_geode_python_test( DEPENDENCIES ${PROJECT_NAME}::py_geometry ) +add_geode_python_test( + SOURCE "test-py-octree.py" + DEPENDENCIES + ${PROJECT_NAME}::py_geometry + ${PROJECT_NAME}::py_mesh +) add_geode_python_test( SOURCE "test-py-perpendicular.py" DEPENDENCIES diff --git a/bindings/python/tests/geometry/test-py-octree.py b/bindings/python/tests/geometry/test-py-octree.py new file mode 100644 index 000000000..7eac906a0 --- /dev/null +++ b/bindings/python/tests/geometry/test-py-octree.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019 - 2026 Geode-solutions +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import geode_test_env +import opengeode_py_basic as basic +import opengeode_py_geometry as geom +import opengeode_py_mesh as mesh + + +def check(condition, message): + if not condition: + raise ValueError(f"[Test] {message}") + + +def check_raises(function, error, message): + try: + function() + except error: + return + raise ValueError(f"[Test] {message}") + + +def point(dimension, value): + return geom.Point2D([value] * 2) if dimension == 2 else geom.Point3D([value] * 3) + + +def box(dimension, low, high): + bbox = geom.BoundingBox2D() if dimension == 2 else geom.BoundingBox3D() + bbox.add_point(point(dimension, low)) + bbox.add_point(point(dimension, high)) + return bbox + + +def octree_class(dimension): + return geom.Octree2D if dimension == 2 else geom.Octree3D + + +def test_construction(dimension): + cls = octree_class(dimension) + check(cls.NB_CHILDREN == 2**dimension, "NB_CHILDREN") + check(cls.NB_FACE_CHILDREN == 2 ** (dimension - 1), "NB_FACE_CHILDREN") + empty = cls() + check(empty.nb_cells() == 0 and empty.leaves() == [], "empty octree") + check(empty.leaf_containing(point(dimension, 0)) is None, "empty leaf_containing") + check_raises(lambda: empty.is_leaf(0), IndexError, "empty is_leaf index") + + octree = cls(box(dimension, 1, 3)) + check(octree.nb_cells() == 1, "one root cell") + check(octree.nb_root_cells() == [1] * dimension, "nb_root_cells") + check(octree.max_depth() == (31 if dimension == 2 else 21), "max_depth") + check(octree.is_leaf(0) and octree.level(0) == 0, "root leaf") + check(octree.parent(0) is None and octree.children(0) is None, "root links") + check(octree.domain_bounding_box().min() == point(dimension, 1), "domain min") + check(octree.domain_bounding_box().max() == point(dimension, 3), "domain max") + check(octree.cell_anchor(0) == [0] * dimension, "root anchor") + check(octree.cell_lengths(0) == [2.0] * dimension, "root lengths") + check(octree.cell_center(0) == point(dimension, 2), "root center") + + degenerate_max = point(dimension, 1) + degenerate_max.set_value(0, 0) + flat = geom.BoundingBox2D() if dimension == 2 else geom.BoundingBox3D() + flat.add_point(point(dimension, 0)) + flat.add_point(degenerate_max) + check_raises(lambda: cls(flat), basic.OpenGeodeDataError, "degenerate box") + + +def test_refine(dimension): + cls = octree_class(dimension) + nb_children = cls.NB_CHILDREN + octree = cls(box(dimension, 0, 2)) + first = octree.refine(0) + check(first == 1 and octree.nb_cells() == 1 + nb_children, "first refine") + check(octree.children(0) == 1 and not octree.is_leaf(0), "refined root") + for child in range(first, first + nb_children): + check(octree.parent(child) == 0 and octree.level(child) == 1, "child links") + last = first + nb_children - 1 + check(octree.cell_bounding_box(last).min() == point(dimension, 1), "last child min") + check(octree.cell_bounding_box(last).max() == point(dimension, 2), "last child max") + half = 1 << (octree.max_depth() - 1) + check(octree.cell_anchor(last) == [half] * dimension, "last child anchor") + check(octree.cell(1, [half] * dimension) == last, "cell lookup") + check(octree.cell(1, [1] * dimension) is None, "unaligned anchor") + check(octree.cell(octree.max_depth() + 1, [0] * dimension) is None, "level too deep") + + second = octree.refine(last) + check(octree.leaves(0) == list(range(1, last)) + list(range(second, second + nb_children)), "subtree leaves") + check(octree.leaves(1) == [1], "leaves of a leaf") + check(octree.leaves() == sorted(octree.leaves(0)), "all leaves") + check(octree.leaf_containing(point(dimension, 1.9)) == second + nb_children - 1, "leaf_containing") + check(octree.leaf_containing(point(dimension, 3)) is None, "outside point") + + check_raises(lambda: octree.refine(0), basic.OpenGeodeDataError, "refine non-leaf") + for method in ("is_leaf", "level", "parent", "children", "cell_bounding_box", "cell_center", "cell_lengths", "cell_anchor", "leaves", "refine"): + check_raises(lambda: getattr(octree, method)(octree.nb_cells()), IndexError, f"{method} index") + check_raises(lambda: octree.refine(-1), TypeError, "negative index") + + +def test_traverse(dimension): + octree = octree_class(dimension)(box(dimension, 0, 2)) + first = octree.refine(0) + query = box(dimension, 0.1, 0.5) + visited = [] + octree.traverse(lambda cell, bbox: bbox.intersects_bounding_box(query), visited.append) + check(visited == [first], "filtered traversal") + everything = [] + octree.traverse(lambda cell, bbox: True, everything.append) + check(everything == octree.leaves(0), "full traversal") + + def failing_filter(cell, bbox): + raise KeyError("filter") + + check_raises(lambda: octree.traverse(failing_filter, everything.append), KeyError, "filter exception propagates") + + +def test_face_neighbors(dimension): + cls = octree_class(dimension) + octree = cls(box(dimension, 0, 2)) + first = octree.refine(0) + upper = first + 1 + finer = octree.refine(upper) + lower, side_upper = cls.FaceSide.lower, cls.FaceSide.upper + check(octree.face_neighbor_leaves(first, 0, lower) == [], "domain border") + # The lower children of upper along axis 0 touch the face of first + expected = [finer + c for c in range(cls.NB_CHILDREN) if not c & 1] + check(octree.face_neighbor_leaves(first, 0, side_upper) == expected, "finer neighbors") + check(len(expected) == cls.NB_FACE_CHILDREN, "finer neighbor count") + check(octree.face_neighbor_leaves(finer, 0, lower) == [first], "coarser neighbor") + check_raises(lambda: octree.face_neighbor_leaves(first, dimension, lower), IndexError, "axis out of range") + check_raises(lambda: octree.face_neighbor_leaves(octree.nb_cells(), 0, lower), IndexError, "cell out of range") + + deep = octree.refine(finer) + nb_cells = octree.nb_cells() + octree.balance(cls.BalanceType.faces) + check(octree.nb_cells() > nb_cells, "balance refined the coarse leaf") + check(not octree.is_leaf(first), "balance refined the coarse face neighbor") + check(octree.level(deep) == 3, "balance kept the existing cells") + nb_cells = octree.nb_cells() + octree.balance(cls.BalanceType.faces) + check(octree.nb_cells() == nb_cells, "balance is idempotent") + octree.balance(cls.BalanceType.full) + check(octree.nb_cells() >= nb_cells, "full balance") + + +def test_attributes(dimension): + octree = octree_class(dimension)(box(dimension, 0, 2)) + manager = octree.cell_attribute_manager() + attribute_id = manager.create_attribute_variable_double("metric", -1.0) + attribute = manager.find_attribute_variable_double(attribute_id) + attribute.set_value(0, 4.0) + first = octree.refine(0) + check(manager.nb_elements() == octree.nb_cells(), "attribute size follows refine") + for child in range(first, first + octree.NB_CHILDREN): + check(attribute.value(child) == 4.0, "children inherit the value") + attribute.set_value(first, 2.0) + del octree + check(manager.nb_elements() == 1 + 2**dimension, "manager keeps the octree alive") + + +def leaf_metric(octree): + manager = octree.cell_attribute_manager() + attribute_id = manager.create_attribute_variable_double("metric", -1.0) + attribute = manager.find_attribute_variable_double(attribute_id) + for leaf in octree.leaves(): + attribute.set_value(leaf, 0.5 + leaf) + + +def check_converted(octree, converted, nb_elements, element_manager, nb_vertices): + leaves = octree.leaves() + check(nb_elements == len(leaves), "one element per leaf") + check(converted.nb_vertices() == nb_vertices, "shared corners") + manager = element_manager + attribute_id = manager.attribute_ids_matching_name("metric")[0] + attribute = manager.find_read_only_attribute_double(attribute_id) + for element, leaf in enumerate(leaves): + check(attribute.value(element) == 0.5 + leaf, "leaf attribute transferred") + + +def test_conversions(): + quadtree = geom.Octree2D(box(2, 0, 2)) + quadtree.refine(quadtree.refine(0)) + leaf_metric(quadtree) + surface = mesh.convert_octree_into_polygonal_surface(octree=quadtree) + check(isinstance(surface, mesh.PolygonalSurface2D), "surface type") + # 3x3 corners of the first level, 3x3 - 1 more in the refined child + check_converted(quadtree, surface, surface.nb_polygons(), surface.polygon_attribute_manager(), 9 + 5) + for polygon in range(surface.nb_polygons()): + check(surface.nb_polygon_vertices(polygon) == 4, "quadrangles") + + octree = geom.Octree3D(box(3, 0, 2)) + octree.refine(octree.refine(0)) + leaf_metric(octree) + solid = mesh.convert_octree_into_hybrid_solid(octree=octree) + check(isinstance(solid, mesh.HybridSolid3D), "solid type") + check_converted(octree, solid, solid.nb_polyhedra(), solid.polyhedron_attribute_manager(), 27 + 19) + for polyhedron in range(solid.nb_polyhedra()): + check(solid.nb_polyhedron_vertices(polyhedron) == 8, "hexahedra") + + check_raises(lambda: mesh.convert_octree_into_hybrid_solid(quadtree), TypeError, "2D octree into a solid") + empty = mesh.convert_octree_into_polygonal_surface(geom.Octree2D()) + check(empty.nb_polygons() == 0 and empty.nb_vertices() == 0, "empty octree conversion") + + +if __name__ == "__main__": + basic.OpenGeodeBasicLibrary.initialize() + geom.OpenGeodeGeometryLibrary.initialize() + mesh.OpenGeodeMeshLibrary.initialize() + for dimension in (2, 3): + test_construction(dimension) + test_refine(dimension) + test_traverse(dimension) + test_face_neighbors(dimension) + test_attributes(dimension) + test_conversions() diff --git a/include/geode/geometry/octree.hpp b/include/geode/geometry/octree.hpp new file mode 100644 index 000000000..53795f076 --- /dev/null +++ b/include/geode/geometry/octree.hpp @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#pragma once + +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include + +namespace geode +{ + class AttributeManager; +} // namespace geode + +namespace geode +{ + /*! + * Adaptive octree (quadtree in 2D) covering an axis-aligned domain. + * + * The domain is first split into a grid of root cells, built from a + * BoundingBox: along each axis, the number of root cells is + * max( 1, round( side / smallest_side ) ) and the root cell length is + * side / nb, so that the root cells fit the box exactly and have an + * aspect ratio in [1, 2). + * Each leaf cell can then be refined into 2^dimension children. + * + * Cells are identified by stable indices: all cells (roots, internal + * cells and leaves) are stored in a single vector. Root cells come first + * (indices 0 to nb_roots - 1, row-major with axis 0 varying fastest), + * then children are appended by blocks of 2^dimension contiguous cells + * each time a leaf is refined. Indices never change (no coarsening). + * Within a block of children, bit d of the local child index (0 to + * 2^dimension - 1) is set when the child is in the upper half of its + * parent along axis d. + * + * Each cell has an integer anchor (its minimal corner) in the finest + * lattice. The lattice uses B bits per axis: B = 21 in 3D and B = 31 in + * 2D (32 bits would overflow the 64-bit locational code: 1 sentinel bit + + * 2 * 32 bits). The root grid uses root_bits = ceil( log2( max number of + * root cells along an axis ) ) of these bits, so max_depth() = B - + * root_bits. A cell at level L (roots are at level 0) spans 2^( + * max_depth() - L ) lattice units along each axis. + * + * @note The finest cell size is about the largest domain side times + * 2^-B. Refining a cell at max_depth() throws. This structure bounds the + * resolution, not the memory: refining everywhere down to max_depth() is + * not possible in practice. + */ + template < index_t dimension > + class Octree + { + OPENGEODE_DISABLE_COPY( Octree ); + + public: + static constexpr index_t NB_CHILDREN{ 1u << dimension }; + /*! + * Number of children of a cell touching one of its faces. + */ + static constexpr index_t NB_FACE_CHILDREN{ 1u << ( dimension - 1 ) }; + + /*! + * Identifies, with an axis, one of the 2 * dimension faces of a cell: + * the face of minimal coordinate along the axis (lower) or of maximal + * coordinate (upper). face_neighbor_leaves( cell, axis, side ) uses + * it to select the face whose neighbors are returned: lower gives the + * leaves on the side of decreasing coordinates, upper on the side of + * increasing coordinates. Looping over every axis and both sides + * visits all the face neighbors of a cell, e.g. to propagate values + * between adjacent leaves. + */ + enum struct FACE_SIDE + { + lower, + upper + }; + + /*! + * Adjacency enforced by balance(), which refines leaves until any + * two adjacent leaves differ by at most one level: + * - faces: leaves sharing a face (an edge in 2D). It bounds the + * level jump across faces only, which is enough for algorithms + * walking from leaf to leaf through faces: face_neighbor_leaves() of + * a leaf then returns at most NB_FACE_CHILDREN finer leaves. + * - full: leaves sharing a face, an edge or a vertex (in 2D: an + * edge or a vertex). It also bounds the level jump along edges and + * at vertices, for algorithms using these neighbors too. + */ + enum struct BALANCE_TYPE + { + faces, + full + }; + + /*! + * Leaves returned by face_neighbor_leaves(), inline up to the + * NB_FACE_CHILDREN finer leaves of a one-level-finer neighbor. + */ + using FaceNeighbors = absl::InlinedVector< index_t, NB_FACE_CHILDREN >; + + /*! + * Creates an empty octree (no cell). + */ + Octree(); + + /*! + * Creates an octree covering the given box with only root cells. + * @exception OpenGeodeException if a box side is smaller than or + * equal to GLOBAL_EPSILON, or if the box is too elongated for the + * lattice (max_depth() would be lower than 1). + */ + explicit Octree( const BoundingBox< dimension >& bbox ); + Octree( Octree&& other ) noexcept; + ~Octree(); + + Octree& operator=( Octree&& other ) noexcept; + + /*! + * Maximal level a cell can have (roots are at level 0). + */ + [[nodiscard]] local_index_t max_depth() const; + + /*! + * Number of cells, including roots and internal (refined) cells. + */ + [[nodiscard]] index_t nb_cells() const; + + [[nodiscard]] const std::array< index_t, dimension >& + nb_root_cells() const; + + [[nodiscard]] bool is_leaf( index_t cell ) const; + + [[nodiscard]] local_index_t level( index_t cell ) const; + + /*! + * Parent cell, std::nullopt for a root cell. + */ + [[nodiscard]] std::optional< index_t > parent( index_t cell ) const; + + /*! + * Index of the first child, std::nullopt for a leaf. + * The NB_CHILDREN children are contiguous: their indices are + * [first_child, first_child + NB_CHILDREN). Bit d of + * ( child - first_child ) is set when the child is in the upper half + * of the cell along axis d. + */ + [[nodiscard]] std::optional< index_t > children( index_t cell ) const; + + /*! + * Bounding box of the cell. Coordinates are computed from lattice + * values only, hence cells sharing a face have exactly the same face + * coordinates. Faces on the domain upper border are exactly at the + * input bounding box max. + */ + [[nodiscard]] BoundingBox< dimension > cell_bounding_box( + index_t cell ) const; + + [[nodiscard]] Point< dimension > cell_center( index_t cell ) const; + + /*! + * Cell length along each axis: root cell length / 2^level. + */ + [[nodiscard]] std::array< double, dimension > cell_lengths( + index_t cell ) const; + + /*! + * Minimal corner of the cell in the finest lattice. + */ + [[nodiscard]] const std::array< index_t, dimension >& cell_anchor( + index_t cell ) const; + + /*! + * Finds the cell with the given level and anchor. + * @return std::nullopt if such a cell does not exist (not created, + * level above max_depth(), anchor outside the domain or not aligned + * on the cell size of this level). + */ + [[nodiscard]] std::optional< index_t > cell( local_index_t level, + const std::array< index_t, dimension >& anchor ) const; + + /*! + * All the leaf cells, sorted by cell index. + */ + [[nodiscard]] std::vector< index_t > leaves() const; + + /*! + * Leaf cells of the subtree of the given cell (the cell itself if + * it is a leaf), in depth-first order, children in index order. + */ + [[nodiscard]] std::vector< index_t > leaves( index_t cell ) const; + + /*! + * Domain covered by the root cells: exactly the bounding box given at + * construction. + */ + [[nodiscard]] BoundingBox< dimension > domain_bounding_box() const; + + /*! + * Finds the leaf containing the point. + * Cells are considered as closed boxes. When a point lies on a face + * (or edge/corner) shared by several leaves, the leaf on the upper + * side along each such axis is returned, unless the point is on the + * upper border of the domain, in which case the last leaf along this + * axis is returned. + * @return std::nullopt if the point is outside domain_bounding_box() + * (BoundingBox::contains semantics, no tolerance). + */ + [[nodiscard]] std::optional< index_t > leaf_containing( + const Point< dimension >& point ) const; + + /*! + * Depth-first traversal of the tree, starting from the roots in index + * order, children in index order. + * @param[in] filter Functor called on each visited cell as + * bool filter( index_t cell, const BoundingBox< dimension >& box ); + * if it returns false, the cell and its subtree are skipped. + * @param[in] action Functor called on each leaf accepted by the + * filter as void action( index_t leaf ). + */ + template < typename Filter, typename Action > + void traverse( Filter&& filter, Action&& action ) const; + + /*! + * Splits a leaf into NB_CHILDREN children, appended at the end of + * the cell vector. All cell attribute values of the leaf are copied + * to its children. + * @return Index of the first child. + * @exception OpenGeodeException if the cell is not a leaf or is + * already at max_depth(). + */ + index_t refine( index_t leaf ); + + /*! + * Leaves sharing a part (with positive measure) of the given face of + * the cell, found by lattice lookups only (no geometry). + * The cell may be a leaf or an internal cell: in both cases, the + * returned leaves are outside the cell and touch the given face: + * - the same-size leaf on the other side of the face if it exists, + * - else the coarser leaf containing the neighboring region if this + * region is not refined down to the cell level, + * - else all the finer leaves (at any depth) touching the face, in + * depth-first order, children in index order. + * @return Empty on the domain border. + */ + [[nodiscard]] FaceNeighbors face_neighbor_leaves( + index_t cell, local_index_t axis, FACE_SIDE side ) const; + + /*! + * Refines leaves until any two adjacent leaves (see BALANCE_TYPE) + * differ by at most one level (2:1 balance). Only coarser leaves are + * refined, never coarsened: existing indices are unchanged and new + * cells are appended and inherit attribute values as in refine(). + * Leaves are processed in a FIFO queue seeded in index order, hence + * the result is deterministic. + */ + void balance( BALANCE_TYPE type ); + + /*! + * Attributes on all cells (internal cells included). + */ + [[nodiscard]] AttributeManager& cell_attribute_manager() const; + + private: + friend class bitsery::Access; + template < typename Archive > + void serialize( Archive& serializer ); + + private: + IMPLEMENTATION_MEMBER( impl_ ); + }; + ALIAS_2D_AND_3D( Octree ); +} // namespace geode + +namespace geode +{ + template < index_t dimension > + template < typename Filter, typename Action > + void Octree< dimension >::traverse( Filter&& filter, Action&& action ) const + { + if( nb_cells() == 0 ) + { + return; + } + index_t nb_roots{ 1 }; + for( const auto nb : nb_root_cells() ) + { + nb_roots *= nb; + } + std::vector< index_t > to_visit; + to_visit.reserve( nb_roots ); + for( const auto root : Range{ nb_roots } ) + { + to_visit.push_back( nb_roots - 1 - root ); + } + while( !to_visit.empty() ) + { + const auto cell = to_visit.back(); + to_visit.pop_back(); + if( !filter( cell, cell_bounding_box( cell ) ) ) + { + continue; + } + const auto first_child = children( cell ); + if( !first_child ) + { + action( cell ); + continue; + } + for( const auto child : Range{ NB_CHILDREN } ) + { + to_visit.push_back( + first_child.value() + NB_CHILDREN - 1 - child ); + } + } + } +} // namespace geode diff --git a/include/geode/mesh/helpers/convert_solid_mesh.hpp b/include/geode/mesh/helpers/convert_solid_mesh.hpp index d888bacc4..2800165c3 100644 --- a/include/geode/mesh/helpers/convert_solid_mesh.hpp +++ b/include/geode/mesh/helpers/convert_solid_mesh.hpp @@ -33,10 +33,12 @@ namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( SolidMesh ); FORWARD_DECLARATION_DIMENSION_CLASS( Grid ); + FORWARD_DECLARATION_DIMENSION_CLASS( Octree ); FORWARD_DECLARATION_DIMENSION_CLASS( TetrahedralSolid ); FORWARD_DECLARATION_DIMENSION_CLASS( HybridSolid ); ALIAS_3D( SolidMesh ); ALIAS_3D( Grid ); + ALIAS_3D( Octree ); ALIAS_3D( TetrahedralSolid ); ALIAS_3D( HybridSolid ); } // namespace geode @@ -53,6 +55,19 @@ namespace geode [[nodiscard]] std::unique_ptr< HybridSolid3D > opengeode_mesh_api convert_grid_into_hybrid_solid( const Grid3D& grid ); + /*! + * Convert an Octree into a HybridSolid with one hexahedron per leaf cell + * (in the order given by Octree::leaves()). Vertices are the leaf corners, + * shared between leaves when they have the same position on the octree + * lattice. The octree attributes of the leaves are transferred to the + * polyhedra attributes. + * @warning The mesh is non-conforming at level jumps: hanging vertices are + * not inserted in the coarser cells, so adjacencies across level jumps + * are missing. It is meant for visualization and export. + */ + [[nodiscard]] std::unique_ptr< HybridSolid3D > opengeode_mesh_api + convert_octree_into_hybrid_solid( const Octree3D& octree ); + [[nodiscard]] std::unique_ptr< TetrahedralSolid3D > opengeode_mesh_api convert_grid_into_densified_tetrahedral_solid( const Grid3D& grid, absl::Span< const geode::index_t > cells_to_densify ); diff --git a/include/geode/mesh/helpers/convert_surface_mesh.hpp b/include/geode/mesh/helpers/convert_surface_mesh.hpp index ba13341dc..c5297b0d9 100644 --- a/include/geode/mesh/helpers/convert_surface_mesh.hpp +++ b/include/geode/mesh/helpers/convert_surface_mesh.hpp @@ -32,11 +32,13 @@ namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Grid ); + FORWARD_DECLARATION_DIMENSION_CLASS( Octree ); FORWARD_DECLARATION_DIMENSION_CLASS( PolygonalSurface ); FORWARD_DECLARATION_DIMENSION_CLASS( SurfaceMesh ); FORWARD_DECLARATION_DIMENSION_CLASS( SurfaceMeshBuilder ); FORWARD_DECLARATION_DIMENSION_CLASS( TriangulatedSurface ); ALIAS_2D_AND_3D( Grid ); + ALIAS_2D_AND_3D( Octree ); ALIAS_2D_AND_3D( PolygonalSurface ); ALIAS_2D_AND_3D( SurfaceMesh ); ALIAS_2D_AND_3D( TriangulatedSurface ); @@ -61,6 +63,19 @@ namespace geode [[nodiscard]] std::unique_ptr< PolygonalSurface2D > opengeode_mesh_api convert_grid_into_polygonal_surface( const Grid2D& grid ); + /*! + * Convert an Octree into a PolygonalSurface with one quadrangle per leaf + * cell (in the order given by Octree::leaves()). Vertices are the leaf + * corners, shared between leaves when they have the same position on the + * octree lattice. The octree attributes of the leaves are transferred to + * the polygon attributes. + * @warning The mesh is non-conforming at level jumps: hanging vertices are + * not inserted in the coarser cells, so adjacencies across level jumps + * are missing. It is meant for visualization and export. + */ + [[nodiscard]] std::unique_ptr< PolygonalSurface2D > opengeode_mesh_api + convert_octree_into_polygonal_surface( const Octree2D& octree ); + [[nodiscard]] std::unique_ptr< TriangulatedSurface2D > opengeode_mesh_api convert_grid_into_densified_triangulated_surface( const Grid2D& grid, absl::Span< const geode::index_t > cells_to_densify ); diff --git a/src/geode/geometry/CMakeLists.txt b/src/geode/geometry/CMakeLists.txt index bb4af524d..50d537447 100644 --- a/src/geode/geometry/CMakeLists.txt +++ b/src/geode/geometry/CMakeLists.txt @@ -51,6 +51,7 @@ add_geode_library( "mensuration.cpp" "nn_search.cpp" "normal_frame_transform.cpp" + "octree.cpp" "perpendicular.cpp" "points_sort.cpp" "position.cpp" @@ -91,6 +92,7 @@ add_geode_library( "mensuration.hpp" "nn_search.hpp" "normal_frame_transform.hpp" + "octree.hpp" "perpendicular.hpp" "point.hpp" "points_sort.hpp" diff --git a/src/geode/geometry/octree.cpp b/src/geode/geometry/octree.cpp new file mode 100644 index 000000000..4719d56de --- /dev/null +++ b/src/geode/geometry/octree.cpp @@ -0,0 +1,828 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include + +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace +{ + template < geode::index_t dimension > + constexpr geode::local_index_t lattice_bits() + { + // 64-bit locational code = 1 sentinel bit + dimension * bits: + // 21 bits in 3D (64 bits), 31 bits in 2D (63 bits, 32 would need 65). + return dimension == 3 ? 21 : 31; + } +} // namespace + +namespace geode +{ + template < index_t dimension > + class Octree< dimension >::Impl + { + // Nested (not in the anonymous namespace): a member of Impl, which + // has external linkage, cannot have a type with internal linkage + struct Node + { + local_index_t level{ 0 }; + std::array< index_t, dimension > anchor{}; + index_t parent{ NO_ID }; + index_t first_child{ NO_ID }; + }; + + public: + Impl() = default; + + explicit Impl( const BoundingBox< dimension >& bbox ) + : origin_{ bbox.min() } + { + for( const auto d : LRange{ dimension } ) + { + domain_max_[d] = bbox.max().value( d ); + } + std::array< double, dimension > sides; + for( const auto d : LRange{ dimension } ) + { + sides[d] = bbox.max().value( d ) - bbox.min().value( d ); + OpenGeodeGeometryException::check_exception( + sides[d] > GLOBAL_EPSILON, nullptr, + OpenGeodeException::TYPE::data, + "[Octree] Cannot build an octree on a degenerate " + "bounding box (side ", + d, " length is ", sides[d], ")" ); + } + const auto smallest_side = + *std::min_element( sides.begin(), sides.end() ); + index_t nb_roots{ 1 }; + for( const auto d : LRange{ dimension } ) + { + const auto nb = + std::max( 1., std::round( sides[d] / smallest_side ) ); + // Checked before the product: nb_roots * nb < NO_ID + OpenGeodeGeometryException::check_exception( + nb < static_cast< double >( NO_ID / nb_roots ), nullptr, + OpenGeodeException::TYPE::data, + "[Octree] Bounding box is too elongated" ); + nb_root_cells_[d] = static_cast< index_t >( nb ); + root_cell_length_[d] = sides[d] / nb; + nb_roots *= nb_root_cells_[d]; + } + initialize_depth(); + create_roots( nb_roots ); + } + + local_index_t max_depth() const + { + return max_depth_; + } + + index_t nb_cells() const + { + return static_cast< index_t >( nodes_.size() ); + } + + const std::array< index_t, dimension >& nb_root_cells() const + { + return nb_root_cells_; + } + + const Node& node( index_t cell ) const + { + OpenGeodeGeometryException::check_assertion( cell < nb_cells(), + "[Octree] Invalid cell index ", cell, " (nb cells is ", + nb_cells(), ")" ); + return nodes_[cell]; + } + + index_t cell_size( local_index_t level ) const + { + return index_t{ 1 } << ( max_depth_ - level ); + } + + /*! + * The domain upper border is snapped to the input bounding box max: + * origin + nb * ( side / nb ) may differ from it by rounding. + */ + double coordinate( local_index_t axis, index_t lattice_value ) const + { + if( lattice_value == lattice_extent( axis ) ) + { + return domain_max_[axis]; + } + return origin_.value( axis ) + + std::ldexp( static_cast< double >( lattice_value ), + -static_cast< int >( max_depth_ ) ) + * root_cell_length_[axis]; + } + + index_t lattice_extent( local_index_t axis ) const + { + return nb_root_cells_[axis] << max_depth_; + } + + BoundingBox< dimension > cell_bounding_box( index_t cell ) const + { + const auto& cell_node = node( cell ); + const auto size = cell_size( cell_node.level ); + Point< dimension > min; + Point< dimension > max; + for( const auto d : LRange{ dimension } ) + { + min.set_value( d, coordinate( d, cell_node.anchor[d] ) ); + max.set_value( d, coordinate( d, cell_node.anchor[d] + size ) ); + } + return { std::move( min ), std::move( max ) }; + } + + std::array< double, dimension > cell_lengths( index_t cell ) const + { + const auto cell_level = node( cell ).level; + std::array< double, dimension > lengths; + for( const auto d : LRange{ dimension } ) + { + lengths[d] = std::ldexp( + root_cell_length_[d], -static_cast< int >( cell_level ) ); + } + return lengths; + } + + std::optional< index_t > cell( local_index_t level, + const std::array< index_t, dimension >& anchor ) const + { + if( nodes_.empty() || level > max_depth_ ) + { + return std::nullopt; + } + const auto size = cell_size( level ); + for( const auto d : LRange{ dimension } ) + { + if( anchor[d] % size != 0 || anchor[d] >= lattice_extent( d ) ) + { + return std::nullopt; + } + } + const auto it = lookup_.find( key( level, anchor ) ); + if( it == lookup_.end() ) + { + return std::nullopt; + } + return it->second; + } + + std::vector< index_t > leaves() const + { + std::vector< index_t > result; + for( const auto cell : Range{ nb_cells() } ) + { + if( nodes_[cell].first_child == NO_ID ) + { + result.push_back( cell ); + } + } + return result; + } + + std::vector< index_t > leaves( index_t cell ) const + { + std::vector< index_t > result; + std::vector< index_t > to_visit{ cell }; + while( !to_visit.empty() ) + { + const auto current = to_visit.back(); + to_visit.pop_back(); + const auto first_child = node( current ).first_child; + if( first_child == NO_ID ) + { + result.push_back( current ); + continue; + } + for( auto c = NB_CHILDREN; c-- > 0; ) + { + to_visit.push_back( first_child + c ); + } + } + return result; + } + + BoundingBox< dimension > domain_bounding_box() const + { + if( nodes_.empty() ) + { + return {}; + } + Point< dimension > max; + for( const auto d : LRange{ dimension } ) + { + max.set_value( d, coordinate( d, lattice_extent( d ) ) ); + } + return { origin_, std::move( max ) }; + } + + std::optional< index_t > leaf_containing( + const Point< dimension >& point ) const + { + if( nodes_.empty() || !domain_bounding_box().contains( point ) ) + { + return std::nullopt; + } + index_t cell{ 0 }; + index_t stride{ 1 }; + for( const auto d : LRange{ dimension } ) + { + cell += root_index( d, point.value( d ) ) * stride; + stride *= nb_root_cells_[d]; + } + while( nodes_[cell].first_child != NO_ID ) + { + const auto& cell_node = nodes_[cell]; + const auto half_size = cell_size( cell_node.level ) / 2; + index_t local_child{ 0 }; + for( const auto d : LRange{ dimension } ) + { + if( point.value( d ) + >= coordinate( d, cell_node.anchor[d] + half_size ) ) + { + local_child |= index_t{ 1 } << d; + } + } + cell = cell_node.first_child + local_child; + } + return cell; + } + + index_t refine( index_t leaf ) + { + const auto parent_node = node( leaf ); + OpenGeodeGeometryException::check_exception( + parent_node.first_child == NO_ID, nullptr, + OpenGeodeException::TYPE::data, "[Octree::refine] Cell ", leaf, + " is not a leaf" ); + OpenGeodeGeometryException::check_exception( + parent_node.level < max_depth_, nullptr, + OpenGeodeException::TYPE::data, "[Octree::refine] Cell ", leaf, + " is already at max depth (", max_depth_, ")" ); + OpenGeodeGeometryException::check_exception( + nodes_.size() + NB_CHILDREN < NO_ID, nullptr, + OpenGeodeException::TYPE::data, + "[Octree::refine] Too many cells" ); + const auto first_child = nb_cells(); + const auto child_level = + static_cast< local_index_t >( parent_node.level + 1 ); + const auto half_size = cell_size( child_level ); + for( const auto c : Range{ NB_CHILDREN } ) + { + Node child; + child.level = child_level; + child.parent = leaf; + for( const auto d : LRange{ dimension } ) + { + child.anchor[d] = parent_node.anchor[d]; + if( ( ( c >> d ) & 1 ) != 0 ) + { + child.anchor[d] += half_size; + } + } + lookup_.emplace( + key( child.level, child.anchor ), first_child + c ); + nodes_.push_back( std::move( child ) ); + } + nodes_[leaf].first_child = first_child; + cell_attribute_manager_.resize( nb_cells() ); + for( const auto c : Range{ NB_CHILDREN } ) + { + cell_attribute_manager_.copy_attribute_value( + leaf, first_child + c ); + } + return first_child; + } + + AttributeManager& cell_attribute_manager() const + { + return cell_attribute_manager_; + } + + FaceNeighbors face_neighbor_leaves( + index_t cell, local_index_t axis, FACE_SIDE side ) const + { + OpenGeodeGeometryException::check_assertion( axis < dimension, + "[Octree::face_neighbor_leaves] Invalid axis ", axis ); + const auto& cell_node = node( cell ); + Offset offset{}; + offset[axis] = side == FACE_SIDE::lower ? -1 : 1; + FaceNeighbors result; + const auto anchor = shifted_anchor( cell_node, offset ); + if( !anchor ) + { + return result; + } + const auto neighbor = + enclosing_cell( cell_node.level, anchor.value() ); + // Children of the neighbor touching the face are on the opposite + // side along the axis. + const index_t face_bit = side == FACE_SIDE::lower ? 1 : 0; + absl::InlinedVector< index_t, 16 > stack{ neighbor }; + while( !stack.empty() ) + { + const auto current = stack.back(); + stack.pop_back(); + const auto first_child = nodes_[current].first_child; + if( first_child == NO_ID ) + { + result.push_back( current ); + continue; + } + for( auto c = NB_CHILDREN; c-- > 0; ) + { + if( ( ( c >> axis ) & 1 ) == face_bit ) + { + stack.push_back( first_child + c ); + } + } + } + return result; + } + + void balance( BALANCE_TYPE type ) + { + const auto offsets = neighbor_offsets( type ); + auto queue = leaves(); + for( index_t head = 0; head < queue.size(); head++ ) + { + // Copy: refine() may reallocate the nodes. + const auto leaf_node = nodes_[queue[head]]; + if( leaf_node.first_child != NO_ID || leaf_node.level < 2 ) + { + continue; + } + for( const auto& offset : offsets ) + { + const auto anchor = shifted_anchor( leaf_node, offset ); + if( !anchor ) + { + continue; + } + // Probe the level just coarser than the leaf first: if + // it exists, the neighbor is fine enough. + const auto probe_level = + static_cast< local_index_t >( leaf_node.level - 1 ); + while( true ) + { + const auto neighbor = + enclosing_cell( probe_level, anchor.value() ); + if( nodes_[neighbor].level + 1 >= leaf_node.level ) + { + break; + } + const auto first_child = refine( neighbor ); + for( const auto c : Range{ NB_CHILDREN } ) + { + queue.push_back( first_child + c ); + } + } + } + } + } + + private: + friend class bitsery::Access; + template < typename Archive > + void serialize( Archive& serializer ) + { + serializer.ext( *this, + Growable< Archive, Impl >{ + { []( Archive& archive, Impl& impl ) { + archive.object( impl.origin_ ); + archive.container8b( impl.domain_max_ ); + archive.container8b( impl.root_cell_length_ ); + archive.container4b( impl.nb_root_cells_ ); + archive.container( impl.nodes_, impl.nodes_.max_size(), + []( Archive& archive2, Node& cell_node ) { + archive2.value1b( cell_node.level ); + archive2.container4b( cell_node.anchor ); + archive2.value4b( cell_node.parent ); + archive2.value4b( cell_node.first_child ); + } ); + archive.object( impl.cell_attribute_manager_ ); + if constexpr( std::is_same_v< Archive, Deserializer > ) + { + impl.initialize_depth(); + impl.build_lookup(); + } + OpenGeodeGeometryException::check_exception( + impl.cell_attribute_manager_.nb_elements() + == impl.nb_cells(), + nullptr, OpenGeodeException::TYPE::data, + "[Octree] Wrong attribute manager size after " + "deserialization: file may be corrupted" ); + } } } ); + } + + void initialize_depth() + { + const auto max_nb_roots = *std::max_element( + nb_root_cells_.begin(), nb_root_cells_.end() ); + constexpr auto bits = lattice_bits< dimension >(); + local_index_t root_bits{ 0 }; + while( root_bits < bits + && ( index_t{ 1 } << root_bits ) < max_nb_roots ) + { + root_bits++; + } + OpenGeodeGeometryException::check_exception( root_bits < bits, + nullptr, OpenGeodeException::TYPE::data, + "[Octree] Bounding box is too elongated: ", max_nb_roots, + " root cells along an axis leave no refinement level" ); + root_bits_ = root_bits; + max_depth_ = static_cast< local_index_t >( bits - root_bits ); + } + + void create_roots( index_t nb_roots ) + { + nodes_.reserve( nb_roots ); + for( const auto root : Range{ nb_roots } ) + { + Node root_node; + auto remainder = root; + for( const auto d : LRange{ dimension } ) + { + root_node.anchor[d] = ( remainder % nb_root_cells_[d] ) + << max_depth_; + remainder /= nb_root_cells_[d]; + } + nodes_.push_back( std::move( root_node ) ); + } + build_lookup(); + cell_attribute_manager_.resize( nb_cells() ); + } + + void build_lookup() + { + lookup_.clear(); + lookup_.reserve( nodes_.size() ); + for( const auto cell : Range{ nb_cells() } ) + { + const auto& cell_node = nodes_[cell]; + OpenGeodeGeometryException::check_exception( + cell_node.level <= max_depth_, nullptr, + OpenGeodeException::TYPE::data, "[Octree] Cell ", cell, + " has an invalid level: file may be corrupted" ); + lookup_.emplace( + key( cell_node.level, cell_node.anchor ), cell ); + } + } + + /*! + * Locational code: a sentinel bit followed by the bit-interleaved + * cell coordinates at its level (root_bits + level bits per axis). + */ + uint64_t key( local_index_t level, + const std::array< index_t, dimension >& anchor ) const + { + const auto shift = max_depth_ - level; + const auto nb_bits = root_bits_ + level; + uint64_t code{ 1 }; + for( auto bit = nb_bits; bit-- > 0; ) + { + for( const auto d : LRange{ dimension } ) + { + code = ( code << 1 ) + | ( ( anchor[d] >> ( shift + bit ) ) & 1u ); + } + } + return code; + } + + using Offset = std::array< int, dimension >; + + /*! + * Offsets (-1, 0 or 1 along each axis) toward the neighbors to + * balance: faces only, or faces, edges and vertices. + */ + static std::vector< Offset > neighbor_offsets( BALANCE_TYPE type ) + { + // 3^dimension combinations of -1, 0 and 1. + constexpr index_t nb_combinations{ dimension == 3 ? 27u : 9u }; + std::vector< Offset > offsets; + for( const auto combination : Range{ nb_combinations } ) + { + Offset offset; + index_t nb_non_zeros{ 0 }; + auto remainder = combination; + for( const auto d : LRange{ dimension } ) + { + offset[d] = static_cast< int >( remainder % 3 ) - 1; + remainder /= 3; + if( offset[d] != 0 ) + { + nb_non_zeros++; + } + } + if( nb_non_zeros == 0 + || ( type == BALANCE_TYPE::faces && nb_non_zeros != 1 ) ) + { + continue; + } + offsets.push_back( offset ); + } + return offsets; + } + + /*! + * Anchor of the cell of the same level shifted by the offset (in + * number of cells), std::nullopt if outside the domain. + */ + std::optional< std::array< index_t, dimension > > shifted_anchor( + const Node& cell_node, const Offset& offset ) const + { + const auto size = cell_size( cell_node.level ); + auto anchor = cell_node.anchor; + for( const auto d : LRange{ dimension } ) + { + if( offset[d] < 0 ) + { + if( anchor[d] == 0 ) + { + return std::nullopt; + } + anchor[d] -= size; + } + else if( offset[d] > 0 ) + { + if( anchor[d] + size >= lattice_extent( d ) ) + { + return std::nullopt; + } + anchor[d] += size; + } + } + return anchor; + } + + /*! + * Finest existing cell, at the given level or coarser, containing the + * cell of the given level and anchor (inside the domain). If it is + * coarser than the given level, it is a leaf. + */ + index_t enclosing_cell( + local_index_t level, std::array< index_t, dimension > anchor ) const + { + for( auto current_level = level + 1; current_level-- > 0; ) + { + const auto mask = ~( + cell_size( static_cast< local_index_t >( current_level ) ) + - 1 ); + for( const auto d : LRange{ dimension } ) + { + anchor[d] &= mask; + } + const auto it = lookup_.find( key( + static_cast< local_index_t >( current_level ), anchor ) ); + if( it != lookup_.end() ) + { + return it->second; + } + } + throw OpenGeodeGeometryException{ nullptr, + OpenGeodeException::TYPE::data, + "[Octree] No root cell contains the given anchor" }; + } + + index_t root_index( local_index_t axis, double value ) const + { + const auto nb = nb_root_cells_[axis]; + const auto guess = std::floor( + ( value - origin_.value( axis ) ) / root_cell_length_[axis] ); + auto index = static_cast< index_t >( + std::clamp( guess, 0., static_cast< double >( nb - 1 ) ) ); + while( + index > 0 && value < coordinate( axis, index << max_depth_ ) ) + { + index--; + } + while( index + 1 < nb + && value >= coordinate( axis, ( index + 1 ) << max_depth_ ) ) + { + index++; + } + return index; + } + + private: + Point< dimension > origin_; + std::array< double, dimension > domain_max_{}; + std::array< double, dimension > root_cell_length_{}; + std::array< index_t, dimension > nb_root_cells_{}; + local_index_t root_bits_{ 0 }; + local_index_t max_depth_{ 0 }; + std::vector< Node > nodes_; + absl::flat_hash_map< uint64_t, index_t > lookup_; + mutable AttributeManager cell_attribute_manager_; + }; + + template < index_t dimension > + Octree< dimension >::Octree() = default; + + template < index_t dimension > + Octree< dimension >::Octree( const BoundingBox< dimension >& bbox ) + : impl_{ bbox } + { + } + + template < index_t dimension > + Octree< dimension >::Octree( Octree&& ) noexcept = default; + + template < index_t dimension > + Octree< dimension >::~Octree() = default; + + template < index_t dimension > + Octree< dimension >& Octree< dimension >::operator=( + Octree&& ) noexcept = default; + + template < index_t dimension > + local_index_t Octree< dimension >::max_depth() const + { + return impl_->max_depth(); + } + + template < index_t dimension > + index_t Octree< dimension >::nb_cells() const + { + return impl_->nb_cells(); + } + + template < index_t dimension > + const std::array< index_t, dimension >& + Octree< dimension >::nb_root_cells() const + { + return impl_->nb_root_cells(); + } + + template < index_t dimension > + bool Octree< dimension >::is_leaf( index_t cell ) const + { + return impl_->node( cell ).first_child == NO_ID; + } + + template < index_t dimension > + local_index_t Octree< dimension >::level( index_t cell ) const + { + return impl_->node( cell ).level; + } + + template < index_t dimension > + std::optional< index_t > Octree< dimension >::parent( index_t cell ) const + { + const auto parent_cell = impl_->node( cell ).parent; + if( parent_cell == NO_ID ) + { + return std::nullopt; + } + return parent_cell; + } + + template < index_t dimension > + std::optional< index_t > Octree< dimension >::children( index_t cell ) const + { + const auto first_child = impl_->node( cell ).first_child; + if( first_child == NO_ID ) + { + return std::nullopt; + } + return first_child; + } + + template < index_t dimension > + BoundingBox< dimension > Octree< dimension >::cell_bounding_box( + index_t cell ) const + { + return impl_->cell_bounding_box( cell ); + } + + template < index_t dimension > + Point< dimension > Octree< dimension >::cell_center( index_t cell ) const + { + return cell_bounding_box( cell ).center(); + } + + template < index_t dimension > + std::array< double, dimension > Octree< dimension >::cell_lengths( + index_t cell ) const + { + return impl_->cell_lengths( cell ); + } + + template < index_t dimension > + const std::array< index_t, dimension >& Octree< dimension >::cell_anchor( + index_t cell ) const + { + return impl_->node( cell ).anchor; + } + + template < index_t dimension > + std::optional< index_t > Octree< dimension >::cell( local_index_t level, + const std::array< index_t, dimension >& anchor ) const + { + return impl_->cell( level, anchor ); + } + + template < index_t dimension > + std::vector< index_t > Octree< dimension >::leaves() const + { + return impl_->leaves(); + } + + template < index_t dimension > + std::vector< index_t > Octree< dimension >::leaves( index_t cell ) const + { + return impl_->leaves( cell ); + } + + template < index_t dimension > + BoundingBox< dimension > Octree< dimension >::domain_bounding_box() const + { + return impl_->domain_bounding_box(); + } + + template < index_t dimension > + std::optional< index_t > Octree< dimension >::leaf_containing( + const Point< dimension >& point ) const + { + return impl_->leaf_containing( point ); + } + + template < index_t dimension > + index_t Octree< dimension >::refine( index_t leaf ) + { + return impl_->refine( leaf ); + } + + template < index_t dimension > + auto Octree< dimension >::face_neighbor_leaves( + index_t cell, local_index_t axis, FACE_SIDE side ) const + -> FaceNeighbors + { + return impl_->face_neighbor_leaves( cell, axis, side ); + } + + template < index_t dimension > + void Octree< dimension >::balance( BALANCE_TYPE type ) + { + impl_->balance( type ); + } + + template < index_t dimension > + AttributeManager& Octree< dimension >::cell_attribute_manager() const + { + return impl_->cell_attribute_manager(); + } + + template < index_t dimension > + template < typename Archive > + void Octree< dimension >::serialize( Archive& serializer ) + { + serializer.ext( *this, Growable< Archive, Octree >{ + { []( Archive& archive, Octree& octree ) { + archive.object( octree.impl_ ); + } } } ); + } + + template class opengeode_geometry_api Octree< 2 >; + template class opengeode_geometry_api Octree< 3 >; + + SERIALIZE_BITSERY_ARCHIVE( opengeode_geometry_api, Octree< 2 > ); + SERIALIZE_BITSERY_ARCHIVE( opengeode_geometry_api, Octree< 3 > ); +} // namespace geode diff --git a/src/geode/mesh/helpers/convert_solid_mesh.cpp b/src/geode/mesh/helpers/convert_solid_mesh.cpp index e2bb316f0..e6f3821a4 100644 --- a/src/geode/mesh/helpers/convert_solid_mesh.cpp +++ b/src/geode/mesh/helpers/convert_solid_mesh.cpp @@ -23,8 +23,12 @@ #include +#include + +#include #include +#include #include #include @@ -624,6 +628,54 @@ namespace return solid; } + std::unique_ptr< geode::HybridSolid3D > create_hybrid_solid_from_octree( + const geode::Octree3D& octree ) + { + auto mesh = geode::HybridSolid3D::create(); + auto builder = geode::HybridSolidBuilder3D::create( *mesh ); + const auto leaves = octree.leaves(); + absl::flat_hash_map< std::array< geode::index_t, 3 >, geode::index_t > + corner_ids; + corner_ids.reserve( leaves.size() * 2 ); + geode::GenericMapping< geode::index_t > old2new_mapping; + for( const auto leaf : leaves ) + { + const auto box = octree.cell_bounding_box( leaf ); + const auto& anchor = octree.cell_anchor( leaf ); + const geode::index_t size{ geode::index_t{ 1 } + << ( octree.max_depth() + - octree.level( leaf ) ) }; + std::array< geode::index_t, 8 > corners; + for( const auto c : geode::LRange{ 8 } ) + { + std::array< geode::index_t, 3 > key; + geode::Point3D point; + for( const auto d : geode::LRange{ 3 } ) + { + const auto upper = ( ( c >> d ) & 1u ) != 0; + key[d] = anchor[d] + ( upper ? size : geode::index_t{ 0 } ); + point.set_value( d, + upper ? box.max().value( d ) : box.min().value( d ) ); + } + const auto it = + corner_ids.try_emplace( key, mesh->nb_vertices() ); + if( it.second ) + { + builder->create_point( point ); + } + corners[c] = it.first->second; + } + const auto element_id = builder->create_hexahedron( + { corners[0], corners[1], corners[3], corners[2], corners[4], + corners[5], corners[7], corners[6] } ); + old2new_mapping.map( leaf, element_id ); + } + builder->compute_polyhedron_adjacencies(); + mesh->polyhedron_attribute_manager().import( + octree.cell_attribute_manager(), old2new_mapping ); + return mesh; + } + /*! * Copy polyhedron adjacencies from a solid to a converted one having the * same polyhedra but possibly with reordered vertices and facets. @@ -921,6 +973,12 @@ namespace geode return create_hybrid_solid_from_grid( grid ); } + std::unique_ptr< HybridSolid3D > convert_octree_into_hybrid_solid( + const Octree3D& octree ) + { + return create_hybrid_solid_from_octree( octree ); + } + std::unique_ptr< TetrahedralSolid3D > convert_grid_into_densified_tetrahedral_solid( const Grid3D& grid, absl::Span< const geode::index_t > cells_to_densify ) diff --git a/src/geode/mesh/helpers/convert_surface_mesh.cpp b/src/geode/mesh/helpers/convert_surface_mesh.cpp index fc40d99ff..bdec9bab3 100644 --- a/src/geode/mesh/helpers/convert_surface_mesh.cpp +++ b/src/geode/mesh/helpers/convert_surface_mesh.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include @@ -310,6 +311,53 @@ namespace return surface; } + std::unique_ptr< geode::PolygonalSurface2D > + create_polygonal_surface_from_octree( const geode::Octree2D& octree ) + { + auto mesh = geode::PolygonalSurface2D::create(); + auto builder = geode::PolygonalSurfaceBuilder2D::create( *mesh ); + const auto leaves = octree.leaves(); + absl::flat_hash_map< std::array< geode::index_t, 2 >, geode::index_t > + corner_ids; + corner_ids.reserve( leaves.size() * 2 ); + geode::GenericMapping< geode::index_t > old2new_mapping; + for( const auto leaf : leaves ) + { + const auto box = octree.cell_bounding_box( leaf ); + const auto& anchor = octree.cell_anchor( leaf ); + const geode::index_t size{ geode::index_t{ 1 } + << ( octree.max_depth() + - octree.level( leaf ) ) }; + std::array< geode::index_t, 4 > corners; + for( const auto c : geode::LRange{ 4 } ) + { + std::array< geode::index_t, 2 > key; + geode::Point2D point; + for( const auto d : geode::LRange{ 2 } ) + { + const auto upper = ( ( c >> d ) & 1u ) != 0; + key[d] = anchor[d] + ( upper ? size : geode::index_t{ 0 } ); + point.set_value( d, + upper ? box.max().value( d ) : box.min().value( d ) ); + } + const auto it = + corner_ids.try_emplace( key, mesh->nb_vertices() ); + if( it.second ) + { + builder->create_point( point ); + } + corners[c] = it.first->second; + } + const auto element_id = builder->create_polygon( + { corners[0], corners[1], corners[3], corners[2] } ); + old2new_mapping.map( leaf, element_id ); + } + builder->compute_polygon_adjacencies(); + mesh->polygon_attribute_manager().import( + octree.cell_attribute_manager(), old2new_mapping ); + return mesh; + } + std::vector< geode::index_t > checked_cells_to_densify( const geode::Grid2D& grid, absl::Span< const geode::index_t > cells_to_densify ) @@ -396,6 +444,12 @@ namespace geode return create_polygonal_surface_from_grid( grid ); } + std::unique_ptr< PolygonalSurface2D > convert_octree_into_polygonal_surface( + const Octree2D& octree ) + { + return create_polygonal_surface_from_octree( octree ); + } + std::unique_ptr< TriangulatedSurface2D > convert_grid_into_densified_triangulated_surface( const Grid2D& grid, absl::Span< const geode::index_t > cells_to_densify ) diff --git a/tests/geometry/CMakeLists.txt b/tests/geometry/CMakeLists.txt index d39b9281b..ac47a5a3f 100644 --- a/tests/geometry/CMakeLists.txt +++ b/tests/geometry/CMakeLists.txt @@ -30,6 +30,12 @@ add_geode_test( ${PROJECT_NAME}::basic ${PROJECT_NAME}::geometry ) +add_geode_test( + SOURCE "test-octree.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::geometry +) add_geode_test( SOURCE "test-angle.cpp" DEPENDENCIES diff --git a/tests/geometry/test-octree.cpp b/tests/geometry/test-octree.cpp new file mode 100644 index 000000000..33fb0cc77 --- /dev/null +++ b/tests/geometry/test-octree.cpp @@ -0,0 +1,1194 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace +{ + template < geode::index_t dimension > + geode::Point< dimension > uniform_point( double value ) + { + geode::Point< dimension > point; + for( const auto d : geode::LRange{ dimension } ) + { + point.set_value( d, value ); + } + return point; + } + + template < geode::index_t dimension > + geode::BoundingBox< dimension > uniform_box( double min, double max ) + { + return { uniform_point< dimension >( min ), + uniform_point< dimension >( max ) }; + } + + template < geode::index_t dimension > + constexpr geode::local_index_t expected_bits() + { + return dimension == 3 ? 21 : 31; + } + + template < geode::index_t dimension > + void check_cell_consistency( const geode::Octree< dimension >& octree ) + { + for( const auto cell : geode::Range{ octree.nb_cells() } ) + { + const auto level = octree.level( cell ); + const auto& anchor = octree.cell_anchor( cell ); + const auto found = octree.cell( level, anchor ); + geode::OpenGeodeGeometryException::test( + found && found.value() == cell, + "[Test] Wrong cell lookup for cell ", cell ); + const auto box = octree.cell_bounding_box( cell ); + const auto lengths = octree.cell_lengths( cell ); + const auto center = octree.cell_center( cell ); + for( const auto d : geode::LRange{ dimension } ) + { + const auto side = box.max().value( d ) - box.min().value( d ); + geode::OpenGeodeGeometryException::test( + std::fabs( side - lengths[d] ) <= geode::GLOBAL_EPSILON, + "[Test] Wrong cell lengths for cell ", cell ); + geode::OpenGeodeGeometryException::test( + std::fabs( center.value( d ) + - ( box.min().value( d ) + side / 2. ) ) + <= geode::GLOBAL_EPSILON, + "[Test] Wrong cell center for cell ", cell ); + } + if( const auto parent = octree.parent( cell ) ) + { + geode::OpenGeodeGeometryException::test( + octree.level( parent.value() ) + 1 == level, + "[Test] Wrong parent level for cell ", cell ); + const auto first_child = octree.children( parent.value() ); + geode::OpenGeodeGeometryException::test( + first_child && cell >= first_child.value() + && cell < first_child.value() + + geode::Octree< dimension >::NB_CHILDREN, + "[Test] Cell ", cell, " not in its parent children" ); + const auto local = cell - first_child.value(); + const auto parent_box = + octree.cell_bounding_box( parent.value() ); + const auto parent_center = octree.cell_center( parent.value() ); + geode::OpenGeodeGeometryException::test( + parent_box.contains( box ), "[Test] Cell ", cell, + " not inside its parent" ); + for( const auto d : geode::LRange{ dimension } ) + { + const auto upper = ( ( local >> d ) & 1 ) != 0; + geode::OpenGeodeGeometryException::test( + upper + == ( center.value( d ) > parent_center.value( d ) ), + "[Test] Wrong child ordering for cell ", cell ); + } + } + else + { + geode::OpenGeodeGeometryException::test( + level == 0, "[Test] Cell without parent is not a root" ); + } + if( const auto first_child = octree.children( cell ) ) + { + geode::OpenGeodeGeometryException::test( + !octree.is_leaf( cell ), "[Test] Wrong is_leaf" ); + for( const auto c : + geode::Range{ geode::Octree< dimension >::NB_CHILDREN } ) + { + geode::OpenGeodeGeometryException::test( + octree.parent( first_child.value() + c ) == cell, + "[Test] Wrong child parent" ); + } + } + else + { + geode::OpenGeodeGeometryException::test( + octree.is_leaf( cell ), "[Test] Wrong is_leaf" ); + } + } + } + + template < geode::index_t dimension > + void test_construction() + { + geode::Logger::info( "Test construction ", dimension, "D" ); + const geode::Octree< dimension > octree{ uniform_box< dimension >( + 1., 3. ) }; + geode::OpenGeodeGeometryException::test( + octree.nb_cells() == 1, "[Test] Wrong number of cells" ); + geode::OpenGeodeGeometryException::test( + octree.max_depth() == expected_bits< dimension >(), + "[Test] Wrong max depth" ); + geode::OpenGeodeGeometryException::test( + octree.is_leaf( 0 ) && octree.level( 0 ) == 0 && !octree.parent( 0 ) + && !octree.children( 0 ), + "[Test] Wrong root cell" ); + geode::OpenGeodeGeometryException::test( + octree.domain_bounding_box().min() + == uniform_point< dimension >( 1 ) + && octree.domain_bounding_box().max() + == uniform_point< dimension >( 3 ), + "[Test] Wrong domain bounding box" ); + check_cell_consistency( octree ); + + try + { + geode::Point< dimension > max = uniform_point< dimension >( 1. ); + max.set_value( 0, 0. ); + const geode::Octree< dimension > degenerate{ + { uniform_point< dimension >( 0. ), max } + }; + geode::OpenGeodeGeometryException::test( + false, "[Test] Degenerate box should throw" ); + } + catch( const geode::OpenGeodeGeometryException& ) + { + } + + geode::Octree< dimension > empty; + geode::OpenGeodeGeometryException::test( + empty.nb_cells() == 0 && empty.leaves().empty() + && !empty.leaf_containing( uniform_point< dimension >( 0. ) ), + "[Test] Wrong empty octree" ); + empty = geode::Octree< dimension >{ uniform_box< dimension >( 0, 1 ) }; + geode::OpenGeodeGeometryException::test( + empty.nb_cells() == 1, "[Test] Wrong move assigned octree" ); + } + + void test_non_cubic_3d() + { + geode::Logger::info( "Test non cubic 3D" ); + const geode::Octree3D octree{ { geode::Point3D{ { 0., 0., 0. } }, + geode::Point3D{ { 10., 3., 1. } } } }; + geode::OpenGeodeGeometryException::test( + octree.nb_root_cells() + == std::array< geode::index_t, 3 >{ 10, 3, 1 }, + "[Test] Wrong 3D root cells" ); + geode::OpenGeodeGeometryException::test( + octree.nb_cells() == 30, "[Test] Wrong number of 3D root cells" ); + // 10 roots -> 4 root bits + geode::OpenGeodeGeometryException::test( + octree.max_depth() == 17, "[Test] Wrong 3D max depth" ); + geode::OpenGeodeGeometryException::test( + octree.cell_lengths( 0 ) == std::array< double, 3 >{ 1., 1., 1. }, + "[Test] Wrong 3D root lengths" ); + // Row-major, axis 0 fastest + const auto box = octree.cell_bounding_box( 13 ); + geode::OpenGeodeGeometryException::test( + box.min() == geode::Point3D{ { 3., 1., 0. } } + && box.max() == geode::Point3D{ { 4., 2., 1. } }, + "[Test] Wrong 3D root ordering" ); + geode::OpenGeodeGeometryException::test( + octree.cell_anchor( 13 ) + == std::array< geode::index_t, 3 >{ 3u << 17, 1u << 17, 0 }, + "[Test] Wrong 3D root anchor" ); + // Shared face between roots goes to the upper root, domain border to + // the last root + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( geode::Point3D{ { 1., 0.5, 0.5 } } ) == 1, + "[Test] Wrong leaf on root shared face" ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( geode::Point3D{ { 10., 3., 1. } } ) == 29, + "[Test] Wrong leaf on domain upper corner" ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( geode::Point3D{ { 4., 2., 0. } } ) == 24, + "[Test] Wrong leaf on root shared edge" ); + geode::OpenGeodeGeometryException::test( + !octree.leaf_containing( geode::Point3D{ { 10.1, 1., 0.5 } } ), + "[Test] Point outside domain should have no leaf" ); + check_cell_consistency( octree ); + } + + void test_non_cubic_2d() + { + geode::Logger::info( "Test non cubic 2D" ); + const geode::Octree2D octree{ { geode::Point2D{ { -1., 0. } }, + geode::Point2D{ { 6., 2. } } } }; + // round( 7 / 2 ) = 4 roots of length 1.75 along x + geode::OpenGeodeGeometryException::test( + octree.nb_root_cells() == std::array< geode::index_t, 2 >{ 4, 1 }, + "[Test] Wrong 2D root cells" ); + geode::OpenGeodeGeometryException::test( + octree.max_depth() == 29, "[Test] Wrong 2D max depth" ); + geode::OpenGeodeGeometryException::test( + octree.cell_lengths( 0 ) == std::array< double, 2 >{ 1.75, 2. }, + "[Test] Wrong 2D root lengths" ); + geode::OpenGeodeGeometryException::test( + octree.domain_bounding_box().max() == geode::Point2D{ { 6., 2. } }, + "[Test] Wrong 2D domain" ); + check_cell_consistency( octree ); + } + + template < geode::index_t dimension > + void check_too_elongated( const geode::Point< dimension >& max ) + { + try + { + const geode::Octree< dimension > octree{ + { geode::Point< dimension >{}, max } + }; + geode::OpenGeodeGeometryException::test( + false, "[Test] Too elongated box should throw" ); + } + catch( const geode::OpenGeodeGeometryException& ) + { + } + } + + void test_elongated() + { + geode::Logger::info( "Test elongated boxes" ); + // 1000 roots -> 10 root bits + const geode::Octree2D octree{ { geode::Point2D{ { 0., 0. } }, + geode::Point2D{ { 1000., 1. } } } }; + geode::OpenGeodeGeometryException::test( + octree.nb_root_cells() == std::array< geode::index_t, 2 >{ 1000, 1 } + && octree.max_depth() == 21, + "[Test] Wrong elongated 2D octree" ); + // More roots along an axis than index_t can count + check_too_elongated( geode::Point2D{ { 1e10, 1. } } ); + // 2^30 + 1 roots need 31 root bits: no refinement level left + check_too_elongated( geode::Point2D{ + { static_cast< double >( ( 1u << 30 ) + 1 ), 1. } } ); + // 7e4 roots per axis fit the lattice but not their product + check_too_elongated( geode::Point3D{ { 1., 7e4, 7e4 } } ); + } + + template < geode::index_t dimension > + void test_refine() + { + geode::Logger::info( "Test refine ", dimension, "D" ); + constexpr auto nb_children = geode::Octree< dimension >::NB_CHILDREN; + geode::Octree< dimension > octree{ uniform_box< dimension >( 0., 2. ) }; + const auto first = octree.refine( 0 ); + geode::OpenGeodeGeometryException::test( + first == 1 && octree.nb_cells() == 1 + nb_children + && octree.children( 0 ) == 1 && !octree.is_leaf( 0 ), + "[Test] Wrong first refine" ); + const auto half = geode::index_t{ 1 } << ( octree.max_depth() - 1 ); + for( const auto c : geode::Range{ nb_children } ) + { + const auto child = first + c; + geode::OpenGeodeGeometryException::test( + octree.level( child ) == 1 && octree.parent( child ) == 0 + && octree.is_leaf( child ), + "[Test] Wrong child ", child ); + std::array< geode::index_t, dimension > anchor; + for( const auto d : geode::LRange{ dimension } ) + { + anchor[d] = ( ( c >> d ) & 1 ) != 0 ? half : 0; + } + geode::OpenGeodeGeometryException::test( + octree.cell_anchor( child ) == anchor, + "[Test] Wrong child anchor ", child ); + geode::OpenGeodeGeometryException::test( + octree.cell_lengths( child )[0] == 1., + "[Test] Wrong child length ", child ); + } + const auto last_child = first + nb_children - 1; + geode::OpenGeodeGeometryException::test( + octree.cell_bounding_box( last_child ).min() + == uniform_point< dimension >( 1. ) + && octree.cell_bounding_box( last_child ).max() + == uniform_point< dimension >( 2. ) + && octree.cell_center( last_child ) + == uniform_point< dimension >( 1.5 ), + "[Test] Wrong last child geometry" ); + + std::vector< std::array< geode::index_t, dimension > > anchors; + std::vector< geode::local_index_t > levels; + for( const auto cell : geode::Range{ octree.nb_cells() } ) + { + anchors.push_back( octree.cell_anchor( cell ) ); + levels.push_back( octree.level( cell ) ); + } + const auto second = octree.refine( last_child ); + geode::OpenGeodeGeometryException::test( + second == 1 + nb_children, "[Test] Wrong second refine" ); + const auto third = octree.refine( first ); + geode::OpenGeodeGeometryException::test( + third == 1 + 2 * nb_children, "[Test] Wrong third refine" ); + octree.refine( second ); + for( const auto cell : geode::Range{ anchors.size() } ) + { + geode::OpenGeodeGeometryException::test( + octree.cell_anchor( cell ) == anchors[cell] + && octree.level( cell ) == levels[cell], + "[Test] Cell ", cell, " changed after refine" ); + } + geode::OpenGeodeGeometryException::test( + octree.nb_cells() == 1 + 4 * nb_children, + "[Test] Wrong number of cells" ); + geode::OpenGeodeGeometryException::test( + octree.leaves().size() == 1 + 4 * ( nb_children - 1 ), + "[Test] Wrong number of leaves" ); + geode::OpenGeodeGeometryException::test( + absl::c_is_sorted( octree.leaves() ), "[Test] Unsorted leaves" ); + auto subtree_leaves = octree.leaves( 0 ); + absl::c_sort( subtree_leaves ); + geode::OpenGeodeGeometryException::test( + subtree_leaves == octree.leaves(), "[Test] Wrong root leaves" ); + geode::OpenGeodeGeometryException::test( + octree.leaves( first + 1 ) + == std::vector< geode::index_t >{ first + 1 }, + "[Test] Wrong leaves of a leaf" ); + std::vector< geode::index_t > expected_leaves; + const auto fourth = 1 + 3 * nb_children; + for( const auto c : geode::Range{ nb_children } ) + { + expected_leaves.push_back( fourth + c ); + } + for( const auto c : geode::Range{ 1, nb_children } ) + { + expected_leaves.push_back( second + c ); + } + geode::OpenGeodeGeometryException::test( + octree.leaves( last_child ) == expected_leaves, + "[Test] Wrong depth-first leaves of an internal cell" ); + check_cell_consistency( octree ); + + try + { + octree.refine( 0 ); + geode::OpenGeodeGeometryException::test( + false, "[Test] Refining a non-leaf should throw" ); + } + catch( const geode::OpenGeodeGeometryException& ) + { + } + + // Lookup of missing cells + std::array< geode::index_t, dimension > zero{}; + geode::OpenGeodeGeometryException::test( + octree.cell( 0, zero ) == 0 && octree.cell( 1, zero ) == first + && octree.cell( 2, zero ) == third, + "[Test] Wrong lookup of existing cells" ); + geode::OpenGeodeGeometryException::test( + !octree.cell( 3, zero ), "[Test] Missing cell should not exist" ); + auto misaligned = zero; + misaligned[0] = 1; + geode::OpenGeodeGeometryException::test( + !octree.cell( 1, misaligned ), "[Test] Misaligned anchor found" ); + auto outside = zero; + outside[0] = 2 * half; + geode::OpenGeodeGeometryException::test( + !octree.cell( 1, outside ), "[Test] Outside anchor found" ); + geode::OpenGeodeGeometryException::test( + !octree.cell( + static_cast< geode::local_index_t >( octree.max_depth() + 1 ), + zero ), + "[Test] Too deep cell found" ); + } + + template < geode::index_t dimension > + void test_attributes() + { + geode::Logger::info( "Test attributes ", dimension, "D" ); + constexpr auto nb_children = geode::Octree< dimension >::NB_CHILDREN; + geode::Octree< dimension > octree{ uniform_box< dimension >( 0., 1. ) }; + geode::AttributeProperties properties; + properties.assignable = false; + properties.interpolable = false; + geode::AttributeValues< double > values; + values.default_value = -1; + values.no_value = -1; + const auto attribute_id = + octree.cell_attribute_manager() + .template create_attribute< geode::VariableAttribute, double >( + "value", values, properties ); + auto attribute = + octree.cell_attribute_manager() + .template find_attribute< geode::VariableAttribute, double >( + attribute_id ); + attribute->set_value( 0, 5 ); + const auto first = octree.refine( 0 ); + geode::OpenGeodeGeometryException::test( + octree.cell_attribute_manager().nb_elements() == octree.nb_cells(), + "[Test] Wrong attribute manager size" ); + for( const auto c : geode::Range{ nb_children } ) + { + geode::OpenGeodeGeometryException::test( + attribute->value( first + c ) == 5, + "[Test] Child did not inherit its parent value" ); + } + attribute->set_value( first + 1, 7 ); + const auto second = octree.refine( first + 1 ); + for( const auto c : geode::Range{ nb_children } ) + { + geode::OpenGeodeGeometryException::test( + attribute->value( second + c ) == 7, + "[Test] Grandchild did not inherit its parent value" ); + } + geode::OpenGeodeGeometryException::test( + attribute->value( 0 ) == 5 && attribute->value( first ) == 5, + "[Test] Internal cell values changed" ); + } + + template < geode::index_t dimension > + void test_leaf_containing() + { + geode::Logger::info( "Test leaf containing ", dimension, "D" ); + constexpr auto nb_children = geode::Octree< dimension >::NB_CHILDREN; + geode::Octree< dimension > octree{ uniform_box< dimension >( 0., 2. ) }; + const auto first = octree.refine( 0 ); + const auto second = octree.refine( first ); + // Interior points + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( uniform_point< dimension >( 0.2 ) ) + == second, + "[Test] Wrong leaf for interior point" ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( uniform_point< dimension >( 1.5 ) ) + == first + nb_children - 1, + "[Test] Wrong leaf for interior point" ); + // Shared faces go to the upper side + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( uniform_point< dimension >( 0.5 ) ) + == second + nb_children - 1, + "[Test] Wrong leaf on shared corner" ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( uniform_point< dimension >( 1. ) ) + == first + nb_children - 1, + "[Test] Wrong leaf on shared corner" ); + auto on_face = uniform_point< dimension >( 0.2 ); + on_face.set_value( 0, 1. ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( on_face ) == first + 1, + "[Test] Wrong leaf on shared face" ); + // Domain borders + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( uniform_point< dimension >( 0. ) ) + == second, + "[Test] Wrong leaf on domain lower corner" ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( uniform_point< dimension >( 2. ) ) + == first + nb_children - 1, + "[Test] Wrong leaf on domain upper corner" ); + auto on_border = uniform_point< dimension >( 0.2 ); + on_border.set_value( 0, 2. ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( on_border ) == first + 1, + "[Test] Wrong leaf on domain upper border" ); + // Outside + geode::OpenGeodeGeometryException::test( + !octree.leaf_containing( uniform_point< dimension >( 2.001 ) ) + && !octree.leaf_containing( + uniform_point< dimension >( -0.001 ) ), + "[Test] Outside point should have no leaf" ); + // Every leaf center is in its own leaf + for( const auto leaf : octree.leaves() ) + { + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( octree.cell_center( leaf ) ) == leaf, + "[Test] Wrong leaf for leaf center ", leaf ); + } + } + + template < geode::index_t dimension > + void test_traverse() + { + geode::Logger::info( "Test traverse ", dimension, "D" ); + geode::Point< dimension > max = uniform_point< dimension >( 4. ); + max.set_value( 0, 8. ); + geode::Octree< dimension > octree{ { uniform_point< dimension >( 0. ), + max } }; + geode::OpenGeodeGeometryException::test( + octree.nb_root_cells()[0] == 2, "[Test] Wrong traverse roots" ); + const auto first = octree.refine( 0 ); + const auto second = octree.refine( first + 1 ); + octree.refine( second + 1 ); + const auto query = uniform_box< dimension >( 3.5, 5. ); + std::vector< geode::index_t > visited; + octree.traverse( + [&query]( geode::index_t /*cell*/, + const geode::BoundingBox< dimension >& box ) { + return box.intersects( query ); + }, + [&visited]( geode::index_t leaf ) { + visited.push_back( leaf ); + } ); + std::vector< geode::index_t > expected; + for( const auto leaf : octree.leaves() ) + { + if( octree.cell_bounding_box( leaf ).intersects( query ) ) + { + expected.push_back( leaf ); + } + } + auto sorted_visited = visited; + absl::c_sort( sorted_visited ); + geode::OpenGeodeGeometryException::test( + !expected.empty() && sorted_visited == expected, + "[Test] Wrong traversed leaves" ); + + std::vector< geode::index_t > all; + octree.traverse( + []( geode::index_t /*cell*/, + const geode::BoundingBox< dimension >& /*box*/ ) { + return true; + }, + [&all]( geode::index_t leaf ) { + all.push_back( leaf ); + } ); + // Depth-first, roots and children in index order + std::vector< geode::index_t > expected_order; + const std::function< void( geode::index_t ) > collect = + [&]( geode::index_t cell ) { + if( const auto first_child = octree.children( cell ) ) + { + for( const auto c : geode::Range{ + geode::Octree< dimension >::NB_CHILDREN } ) + { + collect( first_child.value() + c ); + } + return; + } + expected_order.push_back( cell ); + }; + collect( 0 ); + collect( 1 ); + geode::OpenGeodeGeometryException::test( + all == expected_order && all.back() == 1, + "[Test] Wrong full traversal order" ); + auto root_leaves = octree.leaves( 0 ); + root_leaves.push_back( 1 ); + geode::OpenGeodeGeometryException::test( root_leaves == expected_order, + "[Test] Wrong subtree leaves order" ); + auto sorted_all = all; + absl::c_sort( sorted_all ); + geode::OpenGeodeGeometryException::test( + sorted_all == octree.leaves(), "[Test] Wrong full traversal" ); + + std::vector< geode::index_t > none; + octree.traverse( + []( geode::index_t /*cell*/, + const geode::BoundingBox< dimension >& /*box*/ ) { + return false; + }, + [&none]( geode::index_t leaf ) { + none.push_back( leaf ); + } ); + geode::OpenGeodeGeometryException::test( + none.empty(), "[Test] Rejected roots should not be traversed" ); + } + + template < geode::index_t dimension > + void test_max_depth() + { + geode::Logger::info( "Test max depth ", dimension, "D" ); + geode::Octree< dimension > octree{ uniform_box< dimension >( 0., 1. ) }; + geode::index_t cell{ 0 }; + while( octree.level( cell ) < octree.max_depth() ) + { + cell = octree.refine( cell ) + + geode::Octree< dimension >::NB_CHILDREN - 1; + } + geode::OpenGeodeGeometryException::test( + octree.level( cell ) == expected_bits< dimension >(), + "[Test] Wrong deepest level" ); + try + { + octree.refine( cell ); + geode::OpenGeodeGeometryException::test( + false, "[Test] Refining at max depth should throw" ); + } + catch( const geode::OpenGeodeGeometryException& ) + { + } + const auto box = octree.cell_bounding_box( cell ); + geode::OpenGeodeGeometryException::test( + box.max() == uniform_point< dimension >( 1. ) + && box.min().value( 0 ) < 1. + && octree.cell_lengths( cell )[0] + == std::ldexp( 1., -octree.max_depth() ), + "[Test] Wrong deepest cell geometry" ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( uniform_point< dimension >( 1. ) ) == cell, + "[Test] Wrong deepest leaf containing" ); + check_cell_consistency( octree ); + } + + template < geode::index_t dimension > + void test_serialization() + { + geode::Logger::info( "Test serialization ", dimension, "D" ); + // Box whose max is not exactly origin + nb * ( side / nb ) + geode::Point< dimension > max = uniform_point< dimension >( 1.2 ); + max.set_value( 0, 0.1 + 1.1 * 3.1 ); + geode::Octree< dimension > octree{ { uniform_point< dimension >( 0.1 ), + max } }; + geode::AttributeValues< double > values; + values.default_value = 0; + values.no_value = 0; + const auto attribute_id = + octree.cell_attribute_manager() + .template create_attribute< geode::VariableAttribute, double >( + "value", values, geode::AttributeProperties{} ); + auto attribute = + octree.cell_attribute_manager() + .template find_attribute< geode::VariableAttribute, double >( + attribute_id ); + attribute->set_value( 1, 3 ); + const auto first = octree.refine( 1 ); + octree.refine( first + 2 ); + attribute->set_value( first, 9 ); + + const auto filename = + absl::StrCat( "octree", dimension, "d.og_octree" ); + { + std::ofstream file{ filename, std::ofstream::binary }; + geode::TContext context{}; + geode::register_basic_serialize_pcontext( + std::get< 0 >( context ) ); + geode::register_geometry_serialize_pcontext( + std::get< 0 >( context ) ); + geode::Serializer archive{ context, file }; + archive.object( octree ); + archive.adapter().flush(); + geode::OpenGeodeGeometryException::test( + std::get< 1 >( context ).isValid(), + "[Test] Error while writing file" ); + } + geode::Octree< dimension > reloaded; + { + std::ifstream file{ filename, std::ifstream::binary }; + geode::TContext context{}; + geode::register_basic_deserialize_pcontext( + std::get< 0 >( context ) ); + geode::register_geometry_deserialize_pcontext( + std::get< 0 >( context ) ); + geode::Deserializer archive{ context, file }; + archive.object( reloaded ); + const auto& adapter = archive.adapter(); + geode::OpenGeodeGeometryException::test( + adapter.error() == bitsery::ReaderError::NoError + && adapter.isCompletedSuccessfully() + && std::get< 1 >( context ).isValid(), + "[Test] Error while reading file" ); + } + std::remove( filename.c_str() ); + geode::OpenGeodeGeometryException::test( + reloaded.nb_cells() == octree.nb_cells() + && reloaded.max_depth() == octree.max_depth() + && reloaded.nb_root_cells() == octree.nb_root_cells() + && reloaded.leaves() == octree.leaves(), + "[Test] Wrong reloaded octree" ); + geode::OpenGeodeGeometryException::test( + reloaded.domain_bounding_box().min() + == octree.domain_bounding_box().min() + && reloaded.domain_bounding_box().max() + == octree.domain_bounding_box().max(), + "[Test] Wrong reloaded domain" ); + geode::OpenGeodeGeometryException::test( + reloaded.domain_bounding_box().max() == max + && reloaded.leaf_containing( max ).has_value(), + "[Test] Reloaded domain not snapped to bbox max" ); + for( const auto cell : geode::Range{ octree.nb_cells() } ) + { + geode::OpenGeodeGeometryException::test( + reloaded.level( cell ) == octree.level( cell ) + && reloaded.cell_anchor( cell ) + == octree.cell_anchor( cell ) + && reloaded.parent( cell ) == octree.parent( cell ) + && reloaded.children( cell ) == octree.children( cell ) + && reloaded.cell_bounding_box( cell ).min() + == octree.cell_bounding_box( cell ).min(), + "[Test] Wrong reloaded cell ", cell ); + } + check_cell_consistency( reloaded ); + const auto reloaded_attribute = + reloaded.cell_attribute_manager() + .template find_attribute< geode::VariableAttribute, double >( + attribute_id ); + for( const auto cell : geode::Range{ octree.nb_cells() } ) + { + geode::OpenGeodeGeometryException::test( + reloaded_attribute->value( cell ) == attribute->value( cell ), + "[Test] Wrong reloaded attribute value ", cell ); + } + for( const auto leaf : octree.leaves() ) + { + geode::OpenGeodeGeometryException::test( + reloaded.leaf_containing( octree.cell_center( leaf ) ) == leaf, + "[Test] Wrong reloaded leaf containing" ); + } + reloaded.refine( reloaded.leaves().front() ); + geode::OpenGeodeGeometryException::test( + reloaded.nb_cells() + == octree.nb_cells() + geode::Octree< dimension >::NB_CHILDREN, + "[Test] Cannot refine reloaded octree" ); + check_cell_consistency( reloaded ); + } + + template < geode::index_t dimension > + void test_domain_snapping() + { + geode::Logger::info( "Test domain snapping ", dimension, "D" ); + const std::array< double, 4 > origins{ 0.1, -3.7, 1234.567, 1e-3 }; + const std::array< double, 5 > sides{ 0.3, 0.7, 1.1, 10.3, 3.33 }; + for( const auto origin : origins ) + { + for( const auto side : sides ) + { + for( const auto ratio : { 1., 3.1, 7.2, 10. } ) + { + const auto min = uniform_point< dimension >( origin ); + auto max = uniform_point< dimension >( origin + side ); + max.set_value( 0, origin + side * ratio ); + const geode::Octree< dimension > octree{ { min, max } }; + const auto domain = octree.domain_bounding_box(); + geode::OpenGeodeGeometryException::test( + domain.min() == min && domain.max() == max, + "[Test] Domain not snapped to bbox (origin ", origin, + ", side ", side, ", ratio ", ratio, ")" ); + geode::OpenGeodeGeometryException::test( + octree.leaf_containing( max ).has_value() + && octree.leaf_containing( min ).has_value(), + "[Test] bbox corner outside octree (origin ", origin, + ", side ", side, ", ratio ", ratio, ")" ); + const auto last = octree.nb_cells() - 1; + geode::OpenGeodeGeometryException::test( + octree.cell_bounding_box( last ).max() == max + && octree.leaf_containing( max ) == last, + "[Test] Last root not snapped to bbox max" ); + } + } + } + } + + template < geode::index_t dimension > + geode::BoundingBox< dimension > non_cubic_box() + { + // 3x2x1 root cells in 3D, 2x1 in 2D. + auto max = uniform_point< dimension >( 1. ); + max.set_value( 0, 3. ); + max.set_value( 1, 1.5 ); + return { uniform_point< dimension >( 0. ), max }; + } + + /*! + * Deterministic pseudo-random refinement (fixed LCG, platform + * independent). + */ + template < geode::index_t dimension > + void refine_randomly( geode::Octree< dimension >& octree, + geode::index_t nb_refinements, + geode::local_index_t max_level ) + { + uint64_t state{ 42 }; + for( const auto step : geode::Range{ nb_refinements } ) + { + geode_unused( step ); + state = state * 6364136223846793005ULL + 1442695040888963407ULL; + const auto leaves = octree.leaves(); + const auto leaf = leaves[( state >> 33 ) % leaves.size()]; + if( octree.level( leaf ) < max_level ) + { + octree.refine( leaf ); + } + } + } + + /*! + * True if the box b is on the given side of the box a along the axis and + * shares a part of the corresponding face of a with positive measure. + */ + template < geode::index_t dimension > + bool shares_face( const geode::BoundingBox< dimension >& a, + const geode::BoundingBox< dimension >& b, + geode::local_index_t axis, + typename geode::Octree< dimension >::FACE_SIDE side ) + { + using FACE_SIDE = typename geode::Octree< dimension >::FACE_SIDE; + if( side == FACE_SIDE::upper + ? b.min().value( axis ) != a.max().value( axis ) + : b.max().value( axis ) != a.min().value( axis ) ) + { + return false; + } + for( const auto d : geode::LRange{ dimension } ) + { + if( d == axis ) + { + continue; + } + if( std::min( a.max().value( d ), b.max().value( d ) ) + <= std::max( a.min().value( d ), b.min().value( d ) ) ) + { + return false; + } + } + return true; + } + + /*! + * Brute-force face neighbors: leaves sharing a part of the face, in + * depth-first traversal order. + */ + template < geode::index_t dimension > + std::vector< geode::index_t > brute_force_face_neighbors( + const geode::Octree< dimension >& octree, + geode::index_t cell, + geode::local_index_t axis, + typename geode::Octree< dimension >::FACE_SIDE side ) + { + using FACE_SIDE = typename geode::Octree< dimension >::FACE_SIDE; + const auto cell_box = octree.cell_bounding_box( cell ); + const auto face = side == FACE_SIDE::upper + ? cell_box.max().value( axis ) + : cell_box.min().value( axis ); + std::vector< geode::index_t > result; + octree.traverse( + [&]( geode::index_t /*unused*/, + const geode::BoundingBox< dimension >& box ) { + return box.min().value( axis ) <= face + && face <= box.max().value( axis ); + }, + [&]( geode::index_t leaf ) { + if( shares_face( cell_box, octree.cell_bounding_box( leaf ), + axis, side ) ) + { + result.push_back( leaf ); + } + } ); + return result; + } + + template < geode::index_t dimension > + void check_face_neighbors( const geode::Octree< dimension >& octree, + geode::index_t cell, + geode::local_index_t axis, + typename geode::Octree< dimension >::FACE_SIDE side, + const std::vector< geode::index_t >& expected ) + { + const auto neighbors = octree.face_neighbor_leaves( cell, axis, side ); + geode::OpenGeodeGeometryException::test( + neighbors.size() == expected.size() + && std::equal( + neighbors.begin(), neighbors.end(), expected.begin() ), + "[Test] Wrong face neighbors of cell ", cell, " axis ", axis, + " side ", side == geode::Octree< dimension >::FACE_SIDE::upper, + " (found ", neighbors.size(), ", expected ", expected.size(), ")" ); + } + + template < geode::index_t dimension > + void test_face_neighbors() + { + geode::Logger::info( "Test face neighbors ", dimension, "D" ); + using FACE_SIDE = typename geode::Octree< dimension >::FACE_SIDE; + constexpr auto nb_children = geode::Octree< dimension >::NB_CHILDREN; + // Explicit cases on 3 root cells along axis 0. + auto max = uniform_point< dimension >( 1. ); + max.set_value( 0, 3. ); + geode::Octree< dimension > octree{ { uniform_point< dimension >( 0. ), + max } }; + check_face_neighbors( octree, 0, 0, FACE_SIDE::upper, { 1 } ); + check_face_neighbors( octree, 1, 0, FACE_SIDE::lower, { 0 } ); + check_face_neighbors( octree, 0, 0, FACE_SIDE::lower, {} ); + check_face_neighbors( octree, 2, 0, FACE_SIDE::upper, {} ); + for( const auto d : geode::LRange{ 1, dimension } ) + { + for( const auto side : { FACE_SIDE::lower, FACE_SIDE::upper } ) + { + check_face_neighbors( octree, 1, d, side, {} ); + } + } + const auto children = octree.refine( 1 ); + const auto grand_children = octree.refine( children ); + // Finer leaves over 2 levels, depth-first order. + std::vector< geode::index_t > expected; + for( const auto c : geode::Range{ nb_children } ) + { + if( ( c & 1 ) == 0 ) + { + expected.push_back( grand_children + c ); + } + } + for( const auto c : geode::Range{ 1, nb_children } ) + { + if( ( c & 1 ) == 0 ) + { + expected.push_back( children + c ); + } + } + check_face_neighbors( octree, 0, 0, FACE_SIDE::upper, expected ); + // Same level across a root boundary. + check_face_neighbors( + octree, children + 1, 0, FACE_SIDE::upper, { 2 } ); + // Coarser leaves. + check_face_neighbors( + octree, children + 2, 0, FACE_SIDE::lower, { 0 } ); + check_face_neighbors( + octree, grand_children + 1, 0, FACE_SIDE::upper, { children + 1 } ); + check_face_neighbors( + octree, grand_children, 0, FACE_SIDE::lower, { 0 } ); + // Same level inside a root. + check_face_neighbors( octree, grand_children, 1, FACE_SIDE::upper, + { grand_children + 2 } ); + check_face_neighbors( octree, grand_children, 1, FACE_SIDE::lower, {} ); + // Internal cell: its own children are not its neighbors. + check_face_neighbors( + octree, children, 0, FACE_SIDE::upper, { children + 1 } ); + + // Brute force on a randomly refined non-cubic octree. + geode::Octree< dimension > random{ non_cubic_box< dimension >() }; + refine_randomly( random, 150, 6 ); + for( const auto cell : geode::Range{ random.nb_cells() } ) + { + for( const auto axis : geode::LRange{ dimension } ) + { + for( const auto side : { FACE_SIDE::lower, FACE_SIDE::upper } ) + { + check_face_neighbors( random, cell, axis, side, + brute_force_face_neighbors( + random, cell, axis, side ) ); + } + } + } + } + + /*! + * Brute-force 2:1 check over all leaf pairs: boxes touching (closed + * intersection) along all axes; they share a face if they overlap with + * positive measure along all axes but one. + */ + template < geode::index_t dimension > + bool is_balanced( const geode::Octree< dimension >& octree, + typename geode::Octree< dimension >::BALANCE_TYPE type ) + { + using BALANCE_TYPE = typename geode::Octree< dimension >::BALANCE_TYPE; + const auto leaves = octree.leaves(); + std::vector< geode::BoundingBox< dimension > > boxes; + boxes.reserve( leaves.size() ); + for( const auto leaf : leaves ) + { + boxes.push_back( octree.cell_bounding_box( leaf ) ); + } + for( const auto i : geode::Indices{ leaves } ) + { + for( const auto j : geode::Range{ i + 1, leaves.size() } ) + { + const auto level_i = octree.level( leaves[i] ); + const auto level_j = octree.level( leaves[j] ); + if( std::max( level_i, level_j ) - std::min( level_i, level_j ) + <= 1 ) + { + continue; + } + bool touch{ true }; + geode::index_t nb_contacts{ 0 }; + for( const auto d : geode::LRange{ dimension } ) + { + const auto low = std::max( + boxes[i].min().value( d ), boxes[j].min().value( d ) ); + const auto high = std::min( + boxes[i].max().value( d ), boxes[j].max().value( d ) ); + if( low > high ) + { + touch = false; + } + else if( low == high ) + { + nb_contacts++; + } + } + if( touch + && ( type == BALANCE_TYPE::full || nb_contacts == 1 ) ) + { + return false; + } + } + } + return true; + } + + template < geode::index_t dimension > + geode::Octree< dimension > unbalanced_octree() + { + geode::Octree< dimension > octree{ non_cubic_box< dimension >() }; + // Deep refinement of the upper corner of the first root, touching the + // second root (face) and the other roots (edges/vertices). + geode::index_t cell{ 0 }; + for( const auto level : geode::Range{ 5 } ) + { + geode_unused( level ); + cell = octree.refine( cell ) + + geode::Octree< dimension >::NB_CHILDREN - 1; + } + refine_randomly( octree, 30, 7 ); + return octree; + } + + template < geode::index_t dimension > + void test_balance( typename geode::Octree< dimension >::BALANCE_TYPE type ) + { + using BALANCE_TYPE = typename geode::Octree< dimension >::BALANCE_TYPE; + geode::Logger::info( "Test balance ", dimension, "D ", + type == BALANCE_TYPE::full ? "full" : "faces" ); + auto octree = unbalanced_octree< dimension >(); + geode::OpenGeodeGeometryException::test( !is_balanced( octree, type ), + "[Test] Octree should be unbalanced before balance" ); + geode::AttributeProperties properties; + properties.assignable = false; + properties.interpolable = false; + geode::AttributeValues< double > values; + values.default_value = -1; + values.no_value = -1; + const auto attribute_id = + octree.cell_attribute_manager() + .template create_attribute< geode::VariableAttribute, double >( + "value", values, properties ); + auto attribute = + octree.cell_attribute_manager() + .template find_attribute< geode::VariableAttribute, double >( + attribute_id ); + const auto old_nb_cells = octree.nb_cells(); + std::vector< std::array< geode::index_t, dimension > > old_anchors; + std::vector< geode::local_index_t > old_levels; + std::vector< std::optional< geode::index_t > > old_children; + for( const auto cell : geode::Range{ old_nb_cells } ) + { + attribute->set_value( cell, cell ); + old_anchors.push_back( octree.cell_anchor( cell ) ); + old_levels.push_back( octree.level( cell ) ); + old_children.push_back( octree.children( cell ) ); + } + octree.balance( type ); + geode::OpenGeodeGeometryException::test( + octree.nb_cells() > old_nb_cells, + "[Test] BALANCE_TYPE should have refined cells" ); + geode::OpenGeodeGeometryException::test( + is_balanced( octree, type ), "[Test] Octree is not balanced" ); + if( type == BALANCE_TYPE::faces ) + { + geode::OpenGeodeGeometryException::test( + !is_balanced( octree, BALANCE_TYPE::full ), + "[Test] Faces balance should not imply full balance here" ); + } + geode::OpenGeodeGeometryException::test( + octree.cell_attribute_manager().nb_elements() == octree.nb_cells(), + "[Test] Wrong attribute manager size after balance" ); + for( const auto cell : geode::Range{ old_nb_cells } ) + { + geode::OpenGeodeGeometryException::test( + octree.cell_anchor( cell ) == old_anchors[cell] + && octree.level( cell ) == old_levels[cell] + && ( !old_children[cell] + || octree.children( cell ) == old_children[cell] ) + && attribute->value( cell ) == cell, + "[Test] BALANCE_TYPE changed existing cell ", cell ); + } + for( const auto cell : geode::Range{ old_nb_cells, octree.nb_cells() } ) + { + const auto parent = octree.parent( cell ); + geode::OpenGeodeGeometryException::test( + parent + && attribute->value( cell ) + == attribute->value( parent.value() ), + "[Test] BALANCE_TYPE-created cell ", cell, + " did not inherit its parent value" ); + geode::OpenGeodeGeometryException::test( + attribute->value( cell ) < old_nb_cells + && attribute->value( cell ) >= 0, + "[Test] BALANCE_TYPE-created cell ", cell, + " has no inherited value" ); + } + check_cell_consistency( octree ); + const auto balanced_nb_cells = octree.nb_cells(); + octree.balance( type ); + geode::OpenGeodeGeometryException::test( + octree.nb_cells() == balanced_nb_cells, + "[Test] BALANCE_TYPE is not idempotent" ); + // Determinism: same input, same output. + auto other = unbalanced_octree< dimension >(); + other.balance( type ); + geode::OpenGeodeGeometryException::test( + other.nb_cells() == octree.nb_cells(), + "[Test] BALANCE_TYPE is not deterministic" ); + for( const auto cell : geode::Range{ other.nb_cells() } ) + { + geode::OpenGeodeGeometryException::test( + other.cell_anchor( cell ) == octree.cell_anchor( cell ) + && other.level( cell ) == octree.level( cell ), + "[Test] BALANCE_TYPE is not deterministic" ); + } + // An already balanced octree is unchanged. + geode::Octree< dimension > uniform{ non_cubic_box< dimension >() }; + uniform.refine( 0 ); + uniform.balance( type ); + geode::OpenGeodeGeometryException::test( + uniform.nb_cells() + == geode::Octree< dimension >::NB_CHILDREN + + ( dimension == 3 ? 6 : 2 ), + "[Test] BALANCE_TYPE refined a balanced octree" ); + } + + template < geode::index_t dimension > + void do_test() + { + test_construction< dimension >(); + test_refine< dimension >(); + test_attributes< dimension >(); + test_leaf_containing< dimension >(); + test_traverse< dimension >(); + test_max_depth< dimension >(); + test_serialization< dimension >(); + test_domain_snapping< dimension >(); + test_face_neighbors< dimension >(); + test_balance< dimension >( + geode::Octree< dimension >::BALANCE_TYPE::faces ); + test_balance< dimension >( + geode::Octree< dimension >::BALANCE_TYPE::full ); + } +} // namespace + +void test() +{ + geode::OpenGeodeGeometryLibrary::initialize(); + do_test< 2 >(); + do_test< 3 >(); + test_non_cubic_2d(); + test_non_cubic_3d(); + test_elongated(); +} + +OPENGEODE_TEST( "octree" ) diff --git a/tests/mesh/CMakeLists.txt b/tests/mesh/CMakeLists.txt index 02cd681e0..01cb77eb6 100644 --- a/tests/mesh/CMakeLists.txt +++ b/tests/mesh/CMakeLists.txt @@ -60,6 +60,13 @@ add_geode_test( ${PROJECT_NAME}::geometry ${PROJECT_NAME}::mesh ) +add_geode_test( + SOURCE "test-convert-octree.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::geometry + ${PROJECT_NAME}::mesh +) add_geode_test( SOURCE "test-convert-solid.cpp" DEPENDENCIES diff --git a/tests/mesh/test-convert-octree.cpp b/tests/mesh/test-convert-octree.cpp new file mode 100644 index 000000000..e429cdf6a --- /dev/null +++ b/tests/mesh/test-convert-octree.cpp @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace +{ + template < geode::index_t dimension > + geode::BoundingBox< dimension > non_cubic_box(); + + template <> + geode::BoundingBox2D non_cubic_box() + { + return { geode::Point2D{ { 0.3, -1.1 } }, + geode::Point2D{ { 7.7, 1.3 } } }; + } + + template <> + geode::BoundingBox3D non_cubic_box() + { + return { geode::Point3D{ { 0.3, -1.1, 2. } }, + geode::Point3D{ { 7.7, 1.3, 3.1 } } }; + } + + template < geode::index_t dimension > + geode::Octree< dimension > unbalanced_octree() + { + geode::Octree< dimension > octree{ non_cubic_box< dimension >() }; + // refine a root, then repeatedly its first child, and another root + auto leaf = octree.refine( 1 ); + for( [[maybe_unused]] const auto i : geode::Range{ 3 } ) + { + leaf = octree.refine( leaf ); + } + octree.refine( octree.nb_cells() - 1 ); + octree.refine( 0 ); + return octree; + } + + template < geode::index_t dimension > + geode::uuid add_leaf_attribute( const geode::Octree< dimension >& octree ) + { + geode::AttributeValues< double > values; + values.default_value = -1; + values.no_value = -1; + const auto attribute_id = + octree.cell_attribute_manager() + .template create_attribute< geode::VariableAttribute, double >( + "metric", values, geode::AttributeProperties{} ); + auto attribute = + octree.cell_attribute_manager() + .template find_attribute< geode::VariableAttribute, double >( + attribute_id ); + for( const auto leaf : octree.leaves() ) + { + attribute->set_value( leaf, 0.5 + leaf ); + } + return attribute_id; + } + + template < geode::index_t dimension > + absl::flat_hash_set< std::array< geode::index_t, dimension > > + brute_force_corners( const geode::Octree< dimension >& octree ) + { + absl::flat_hash_set< std::array< geode::index_t, dimension > > corners; + for( const auto leaf : octree.leaves() ) + { + const auto& anchor = octree.cell_anchor( leaf ); + const geode::index_t size{ geode::index_t{ 1 } + << ( octree.max_depth() + - octree.level( leaf ) ) }; + for( const auto c : geode::Range{ 1u << dimension } ) + { + std::array< geode::index_t, dimension > key; + for( const auto d : geode::LRange{ dimension } ) + { + key[d] = anchor[d] + ( ( ( c >> d ) & 1u ) ? size : 0 ); + } + corners.insert( key ); + } + } + return corners; + } + + template < geode::index_t dimension > + void check_octree_mesh( const geode::Octree< dimension >& octree, + const geode::BoundingBox< dimension >& domain, + geode::index_t nb_vertices, + geode::index_t nb_elements, + double total_measure ) + { + const auto leaves = octree.leaves(); + geode::OpenGeodeMeshException::test( + nb_elements == leaves.size(), "[Test] Wrong number of elements" ); + geode::OpenGeodeMeshException::test( + nb_vertices == brute_force_corners( octree ).size(), + "[Test] Wrong number of vertices" ); + double domain_measure{ 1 }; + for( const auto d : geode::LRange{ dimension } ) + { + domain_measure *= domain.max().value( d ) - domain.min().value( d ); + } + geode::OpenGeodeMeshException::test( + std::fabs( total_measure - domain_measure ) + <= geode::GLOBAL_EPSILON * domain_measure, + "[Test] Wrong total measure" ); + } + + void test_2d() + { + geode::Logger::info( "Test octree into polygonal surface" ); + const auto octree = unbalanced_octree< 2 >(); + const auto attribute_id = add_leaf_attribute( octree ); + const auto surface = + geode::convert_octree_into_polygonal_surface( octree ); + double area{ 0 }; + for( const auto p : geode::Range{ surface->nb_polygons() } ) + { + geode::OpenGeodeMeshException::test( + surface->nb_polygon_vertices( p ) == 4, + "[Test] Polygon should be a quadrangle" ); + area += surface->polygon_area( p ); + } + check_octree_mesh( octree, non_cubic_box< 2 >(), surface->nb_vertices(), + surface->nb_polygons(), area ); + const auto leaves = octree.leaves(); + auto attribute = + surface->polygon_attribute_manager() + .find_read_only_attribute< double >( attribute_id ); + for( const auto p : geode::Range{ surface->nb_polygons() } ) + { + const auto box = octree.cell_bounding_box( leaves[p] ); + geode::BoundingBox2D polygon_box; + for( const auto v : geode::LRange{ 4 } ) + { + polygon_box.add_point( + surface->point( surface->polygon_vertex( { p, v } ) ) ); + } + geode::OpenGeodeMeshException::test( + polygon_box.min() == box.min() + && polygon_box.max() == box.max(), + "[Test] Polygon box differs from leaf box" ); + geode::OpenGeodeMeshException::test( + attribute->value( p ) == 0.5 + leaves[p], + "[Test] Wrong attribute value" ); + } + const auto domain = surface->bounding_box(); + geode::OpenGeodeMeshException::test( + domain.min() == non_cubic_box< 2 >().min() + && domain.max() == non_cubic_box< 2 >().max(), + "[Test] Mesh bounding box should be the octree domain" ); + // refined leaf 0 has 4 children: conforming interior adjacencies + geode::index_t nb_adjacencies{ 0 }; + for( const auto p : geode::Range{ surface->nb_polygons() } ) + { + for( const auto e : geode::LRange{ 4 } ) + { + nb_adjacencies += surface->polygon_adjacent( { p, e } ) ? 1 : 0; + } + } + geode::OpenGeodeMeshException::test( + nb_adjacencies > 0, "[Test] No adjacency" ); + } + + void test_3d() + { + geode::Logger::info( "Test octree into hybrid solid" ); + const auto octree = unbalanced_octree< 3 >(); + const auto attribute_id = add_leaf_attribute( octree ); + const auto solid = geode::convert_octree_into_hybrid_solid( octree ); + double volume{ 0 }; + for( const auto p : geode::Range{ solid->nb_polyhedra() } ) + { + geode::OpenGeodeMeshException::test( + solid->nb_polyhedron_vertices( p ) == 8, + "[Test] Polyhedron should be a hexahedron" ); + volume += solid->polyhedron_volume( p ); + } + check_octree_mesh( octree, non_cubic_box< 3 >(), solid->nb_vertices(), + solid->nb_polyhedra(), volume ); + const auto leaves = octree.leaves(); + auto attribute = + solid->polyhedron_attribute_manager() + .find_read_only_attribute< double >( attribute_id ); + for( const auto p : geode::Range{ solid->nb_polyhedra() } ) + { + const auto box = octree.cell_bounding_box( leaves[p] ); + geode::BoundingBox3D polyhedron_box; + for( const auto v : geode::LRange{ 8 } ) + { + polyhedron_box.add_point( + solid->point( solid->polyhedron_vertex( { p, v } ) ) ); + } + geode::OpenGeodeMeshException::test( + polyhedron_box.min() == box.min() + && polyhedron_box.max() == box.max(), + "[Test] Polyhedron box differs from leaf box" ); + geode::OpenGeodeMeshException::test( + attribute->value( p ) == 0.5 + leaves[p], + "[Test] Wrong attribute value" ); + } + const auto domain = solid->bounding_box(); + geode::OpenGeodeMeshException::test( + domain.min() == non_cubic_box< 3 >().min() + && domain.max() == non_cubic_box< 3 >().max(), + "[Test] Mesh bounding box should be the octree domain" ); + geode::index_t nb_adjacencies{ 0 }; + for( const auto p : geode::Range{ solid->nb_polyhedra() } ) + { + for( const auto f : geode::LRange{ 6 } ) + { + nb_adjacencies += + solid->polyhedron_adjacent( { p, f } ) ? 1 : 0; + } + } + geode::OpenGeodeMeshException::test( + nb_adjacencies > 0, "[Test] No adjacency" ); + } + +} // namespace + +void test() +{ + geode::OpenGeodeMeshLibrary::initialize(); + geode::Logger::set_level( geode::Logger::LEVEL::debug ); + test_2d(); + test_3d(); +} + +OPENGEODE_TEST( "convert-octree" )