GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
LinearBoundingVolumeHierarchy.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_DATA_LINEAR_BOUNDING_VOLUME_HIERARCHY_HPP
5#define GREM_CORE_DATA_LINEAR_BOUNDING_VOLUME_HIERARCHY_HPP
6
8
18#include <GREM/core/math.hpp>
20
21#include <algorithm> // std::sort
22#include <new> // std::launder
23#include <tuple> // std::forward_as_tuple
24#include <type_traits> // std::conditional_t, std::is_convertible_v
25#include <utility> // std::forward, std::move, std::exchange, std::piecewise_construct, std::declval
26
27namespace grem {
28
37template <size_t N, typename Scalar, typename T>
39public:
40 static_assert(N == 2 || N == 3);
41
47 using size_type = size_t;
48 using difference_type = ptrdiff_t;
49 using iterator = pointer;
51
55 LinearBoundingVolumeHierarchy() noexcept = default;
56
62 void clear() noexcept {
63 dirty = dirty || !elements.empty();
64 elements.clear();
65 }
66
74 [[nodiscard]] iterator begin() noexcept {
75 return std::launder(reinterpret_cast<pointer>(elements.data()));
76 }
77
85 [[nodiscard]] const_iterator begin() const noexcept {
86 return std::launder(reinterpret_cast<const_pointer>(elements.data()));
87 }
88
96 [[nodiscard]] const_iterator cbegin() const noexcept {
97 return begin();
98 }
99
107 [[nodiscard]] iterator end() noexcept {
108 return begin() + elements.size();
109 }
110
118 [[nodiscard]] const_iterator end() const noexcept {
119 return begin() + elements.size();
120 }
121
129 [[nodiscard]] const_iterator cend() const noexcept {
130 return end();
131 }
132
138 [[nodiscard]] size_type size() const noexcept {
139 return elements.size();
140 }
141
147 [[nodiscard]] bool empty() const noexcept {
148 return size() == 0;
149 }
150
169 template <typename... Args>
170 iterator emplace(const Box<N, Scalar>& elementBoundingBox, Args&&... args) {
171 if (elements.size() >= static_cast<size_t>(INVALID_ELEMENT)) {
172 throw std::length_error{"Maximum element count exceeded."};
173 }
174 value_type& element = elements.emplace_back(std::piecewise_construct, std::forward_as_tuple(elementBoundingBox), std::forward_as_tuple(std::forward<Args>(args)...));
175 dirty = true;
176 return std::launder(reinterpret_cast<pointer>(&element));
177 }
178
197 iterator insert(const Box<N, Scalar>& elementBoundingBox, const T& value) {
198 return emplace(elementBoundingBox, value);
199 }
200
219 iterator insert(const Box<N, Scalar>& elementBoundingBox, T&& value) {
220 return emplace(elementBoundingBox, std::move(value));
221 }
222
231 dirty = true;
232 elements.erase(elements.begin() + (pos - cbegin()));
233 }
234
281 template <typename Callback, typename Predicate>
282 auto traverseNodes(Callback&& callback, Predicate&& predicate) const { // NOLINT(cppcoreguidelines-missing-std-forward)
283 return traverseNodesImplementation(
284 [this, callback = std::forward<Callback>(callback)](const Node& node) mutable {
285 const T* const element = (node.elementIndex == INVALID_ELEMENT) ? nullptr : &elements[node.elementIndex].second;
286 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<decltype(callback(node.boundingBox, element)), bool>;
287 if constexpr (CALLBACK_RETURNS_BOOL) {
288 return callback(node.boundingBox, element);
289 } else {
290 callback(node.boundingBox, element);
291 }
292 },
293 std::forward<Predicate>(predicate));
294 }
295
333 template <typename Callback>
334 auto traverseNodes(Callback&& callback) const {
335 return traverseNodes(std::forward<Callback>(callback), [](const Box<N, Scalar>&) -> bool { return true; });
336 }
337
379 template <typename Callback, typename Predicate>
380 auto traverseElements(Callback&& callback, Predicate&& predicate) const { // NOLINT(cppcoreguidelines-missing-std-forward)
381 return traverseNodesImplementation(
382 [this, callback = std::forward<Callback>(callback)](const Node& node) mutable {
383 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<decltype(callback(elements[node.elementIndex].second)), bool>;
384 if (node.elementIndex != INVALID_ELEMENT) {
385 if constexpr (CALLBACK_RETURNS_BOOL) {
386 if (callback(elements[node.elementIndex].second)) {
387 return true; // Callback requested early return.
388 }
389 } else {
390 callback(elements[node.elementIndex].second);
391 }
392 }
393 if constexpr (CALLBACK_RETURNS_BOOL) {
394 return false;
395 }
396 },
397 std::forward<Predicate>(predicate));
398 }
399
432 template <typename Callback>
433 auto traverseElements(Callback&& callback) const {
434 return traverseElements(std::forward<Callback>(callback), [](const Box<N, Scalar>&) -> bool { return true; });
435 }
436
471 template <typename Callback>
472 auto test(Point<N, Scalar> point, Callback&& callback) const {
473 return traverseElements(std::forward<Callback>(callback), [&point](const Box<N, Scalar>& boundingBox) -> bool { return boundingBox.contains(point); });
474 }
475
495 [[nodiscard]] bool test(Point<N, Scalar> point) const noexcept {
496 return traverseElements([](const T&) -> bool { return true; }, [&point](const Box<N, Scalar>& boundingBox) -> bool { return boundingBox.contains(point); });
497 }
498
533 template <typename Callback>
534 auto test(const Box<N, Scalar>& box, Callback&& callback) const {
535 return traverseElements(std::forward<Callback>(callback), [&box](const Box<N, Scalar>& boundingBox) -> bool { return intersects(boundingBox, box); });
536 }
537
558 [[nodiscard]] bool test(const Box<N, Scalar>& box) const noexcept {
559 return traverseElements([](const T&) -> bool { return true; }, [&box](const Box<N, Scalar>& boundingBox) -> bool { return intersects(boundingBox, box); });
560 }
561
562private:
563 using NodeIndex = uint32_t;
564 using ElementIndex = uint32_t;
565
566 static constexpr NodeIndex INVALID_NODE = Limits<NodeIndex>::MAX;
567 static constexpr ElementIndex INVALID_ELEMENT = Limits<ElementIndex>::MAX;
568
569 struct Node {
570 NodeIndex firstChildIndex = INVALID_NODE;
571 NodeIndex secondChildIndex = INVALID_NODE;
572 ElementIndex elementIndex = INVALID_ELEMENT;
573 Box<N, Scalar> boundingBox{};
574 };
575
576 [[nodiscard]] static uint32_t separateMortonCodeBits(uint32_t x) noexcept {
577 if constexpr (N == 2) {
578 x = (x ^ (x << 8)) & 0b00000000111111110000000011111111;
579 x = (x ^ (x << 4)) & 0b00001111000011110000111100001111;
580 x = (x ^ (x << 2)) & 0b00110011001100110011001100110011;
581 x = (x ^ (x << 1)) & 0b01010101010101010101010101010101;
582 } else if constexpr (N == 3) {
583 x = (x ^ (x << 16)) & 0b11111111000000000000000011111111;
584 x = (x ^ (x << 8)) & 0b00001111000000001111000000001111;
585 x = (x ^ (x << 4)) & 0b11000011000011000011000011000011;
586 x = (x ^ (x << 2)) & 0b01001001001001001001001001001001;
587 }
588 return x;
589 }
590
591 [[nodiscard]] static uint32_t getMortonCode(const Point<N, Scalar>& normalizedPosition) noexcept {
592 if constexpr (N == 2) {
593 constexpr Scalar MAX_EXTENT = 0b1111111111111111; // Use 16 bits, which fits in a uint32_t when expanded to 2 dimensions.
594 const uint32_t x = separateMortonCodeBits(static_cast<uint32_t>(clamp(normalizedPosition.x * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
595 const uint32_t y = separateMortonCodeBits(static_cast<uint32_t>(clamp(normalizedPosition.y * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
596 return x | (y << 1);
597 } else if constexpr (N == 3) {
598 constexpr Scalar MAX_EXTENT = 0b1111111111; // Use 10 bits, which fits in a uint32_t when expanded to 3 dimensions.
599 const uint32_t x = separateMortonCodeBits(static_cast<uint32_t>(clamp(normalizedPosition.x * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
600 const uint32_t y = separateMortonCodeBits(static_cast<uint32_t>(clamp(normalizedPosition.y * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
601 const uint32_t z = separateMortonCodeBits(static_cast<uint32_t>(clamp(normalizedPosition.z * MAX_EXTENT, Scalar{0}, MAX_EXTENT)));
602 return x | (y << 1) | (z << 2);
603 }
604 }
605
606 [[nodiscard]] NodeIndex flushSubTree(Span<const Pair<uint32_t, ElementIndex>> elementIndices) const {
607 if (elementIndices.empty()) {
608 return INVALID_NODE;
609 }
610
611 if (tree.size() >= static_cast<size_t>(INVALID_NODE)) {
612 throw std::length_error{"Maximum node count exceeded."};
613 }
614 const NodeIndex nodeIndex = static_cast<NodeIndex>(tree.size());
615 tree.emplace_back();
616 if (elementIndices.size() == 1) {
617 Node& node = tree[nodeIndex];
618 node.firstChildIndex = INVALID_NODE;
619 node.secondChildIndex = INVALID_NODE;
620 node.elementIndex = elementIndices.front().second;
621 node.boundingBox = elements[elementIndices.front().second].first;
622 } else {
623 const size_t halfSize = elementIndices.size() / 2;
624 const NodeIndex firstChildIndex = flushSubTree(elementIndices.first(halfSize));
625 const NodeIndex secondChildIndex = flushSubTree(elementIndices.subspan(halfSize));
626 GREM_ASSERT(firstChildIndex != INVALID_NODE);
627 GREM_ASSERT(secondChildIndex != INVALID_NODE);
628 Node& node = tree[nodeIndex];
629 const Node& firstChild = tree[firstChildIndex];
630 const Node& secondChild = tree[secondChildIndex];
631 node.firstChildIndex = firstChildIndex;
632 node.secondChildIndex = secondChildIndex;
633 node.elementIndex = INVALID_ELEMENT;
634 node.boundingBox = {
635 .min = min(firstChild.boundingBox.min, secondChild.boundingBox.min),
636 .max = max(firstChild.boundingBox.max, secondChild.boundingBox.max),
637 };
638 }
639 return nodeIndex;
640 }
641
642 void flush() const {
643 if (!dirty) {
644 return;
645 }
646
647 Box<N, Scalar> worldBoundingBox{.min{Limits<Scalar>::MAX}, .max{Limits<Scalar>::MIN}};
648 for (const value_type& element : elements) {
649 worldBoundingBox.min = min(worldBoundingBox.min, element.first.min);
650 worldBoundingBox.max = max(worldBoundingBox.max, element.first.max);
651 }
652
653 const Point<N, Scalar> worldCenter = (worldBoundingBox.min + worldBoundingBox.max) * Scalar{0.5};
654 const Length<N, Scalar> worldExtents = worldBoundingBox.max - worldBoundingBox.min;
655 const vec<N, Scalar> inverseWorldExtents = Scalar{1} / worldExtents;
656
657 elementIndicesOrderedByMortonCode.clear();
658 for (size_t elementIndex = 0; elementIndex < elements.size(); ++elementIndex) {
659 const Box<N, Scalar>& boundingBox = elements[elementIndex].first;
660 const Point<N, Scalar> center = (boundingBox.min + boundingBox.max) * Scalar{0.5};
661 elementIndicesOrderedByMortonCode.push_back({getMortonCode((center + worldCenter) * inverseWorldExtents), static_cast<ElementIndex>(elementIndex)});
662 }
663
664 std::sort(elementIndicesOrderedByMortonCode.begin(), elementIndicesOrderedByMortonCode.end(),
665 [](const Pair<uint32_t, ElementIndex>& a, const Pair<uint32_t, ElementIndex>& b) -> bool { return a.first < b.first; });
666
667 tree.clear();
668 [[maybe_unused]] const NodeIndex nodeIndex = flushSubTree(elementIndicesOrderedByMortonCode);
669 GREM_ASSERT((nodeIndex == 0 && !tree.empty()) || (nodeIndex == INVALID_NODE && tree.empty()));
670
671 dirty = false;
672 }
673
674 template <typename Callback, typename Predicate>
675 auto traverseNodesImplementation(Callback&& callback, Predicate&& predicate) const { // NOLINT(cppcoreguidelines-missing-std-forward)
676 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<decltype(callback(std::declval<const Node&>())), bool>;
677 using CallbackResult = std::conditional_t<CALLBACK_RETURNS_BOOL, bool, void>;
678
679 flush();
680
681 const auto traverseSubTree = [&](const auto& self, NodeIndex nodeIndex) -> CallbackResult {
682 const Node& node = tree[nodeIndex];
683 if (predicate(node.boundingBox)) {
684 if constexpr (CALLBACK_RETURNS_BOOL) {
685 if (callback(node)) {
686 return true; // Callback requested early return.
687 }
688 } else {
689 callback(node);
690 }
691
692 if (node.firstChildIndex != INVALID_NODE) {
693 if constexpr (CALLBACK_RETURNS_BOOL) {
694 if (self(self, node.firstChildIndex)) {
695 return true;
696 }
697 } else {
698 self(self, node.firstChildIndex);
699 }
700 }
701 if (node.secondChildIndex != INVALID_NODE) {
702 if constexpr (CALLBACK_RETURNS_BOOL) {
703 if (self(self, node.secondChildIndex)) {
704 return true;
705 }
706 } else {
707 self(self, node.secondChildIndex);
708 }
709 }
710 }
711 if constexpr (CALLBACK_RETURNS_BOOL) {
712 return false;
713 }
714 };
715
716 if (!tree.empty()) {
717 return traverseSubTree(traverseSubTree, 0);
718 }
719 if constexpr (CALLBACK_RETURNS_BOOL) {
720 return false;
721 }
722 }
723
724 ArrayList<value_type> elements{};
725 mutable ArrayList<Node> tree{};
726 mutable Buffer<Pair<uint32_t, ElementIndex>> elementIndicesOrderedByMortonCode{};
727 mutable bool dirty = false;
728};
729
737template <typename Scalar, typename T>
739
747template <typename Scalar, typename T>
749
750} // namespace grem
751
752#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Binary tree-based space subdivision container, Z-ordered using morton codes, optimized for intersecti...
Definition LinearBoundingVolumeHierarchy.hpp:38
iterator emplace(const Box< N, Scalar > &elementBoundingBox, Args &&... args)
Construct a new element in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:170
void clear() noexcept
Definition LinearBoundingVolumeHierarchy.hpp:62
const_pointer const_iterator
Const iterator type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:50
LinearBoundingVolumeHierarchy() noexcept=default
Construct an empty tree.
auto traverseElements(Callback &&callback) const
Execute a callback function for each element in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:433
pointer iterator
Iterator type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:49
const Pair< const Box< N, Scalar >, T > & const_reference
Const reference type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:44
const_iterator end() const noexcept
Get the end iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:118
auto traverseElements(Callback &&callback, Predicate &&predicate) const
Execute a callback function for each element in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:380
const_iterator cbegin() const noexcept
Get the begin iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:96
iterator begin() noexcept
Get the begin iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:74
size_type size() const noexcept
Get the number of elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:138
auto traverseNodes(Callback &&callback, Predicate &&predicate) const
Execute a callback function for each active node of the tree, including empty internal nodes without ...
Definition LinearBoundingVolumeHierarchy.hpp:282
const_iterator cend() const noexcept
Get the end iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:129
size_t size_type
Size type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:47
Pair< Box< N, Scalar >, T > value_type
Value type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:42
iterator insert(const Box< N, Scalar > &elementBoundingBox, T &&value)
Move an element into the tree.
Definition LinearBoundingVolumeHierarchy.hpp:219
bool test(Point< N, Scalar > point) const noexcept
Check if it is possible that some element in the tree contains a given point.
Definition LinearBoundingVolumeHierarchy.hpp:495
iterator end() noexcept
Get the end iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:107
bool empty() const noexcept
Check whether the tree is empty or not.
Definition LinearBoundingVolumeHierarchy.hpp:147
const_iterator begin() const noexcept
Get the begin iterator of the elements in the tree.
Definition LinearBoundingVolumeHierarchy.hpp:85
ptrdiff_t difference_type
Difference type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:48
void erase(const_iterator pos)
Remove an element from the tree.
Definition LinearBoundingVolumeHierarchy.hpp:230
auto test(Point< N, Scalar > point, Callback &&callback) const
Execute a callback function for each element in the tree that might contain a given point.
Definition LinearBoundingVolumeHierarchy.hpp:472
auto traverseNodes(Callback &&callback) const
Execute a callback function for each active node of the tree, including empty internal nodes without ...
Definition LinearBoundingVolumeHierarchy.hpp:334
auto test(const Box< N, Scalar > &box, Callback &&callback) const
Execute a callback function for each element in the tree that might be intersecting with a given axis...
Definition LinearBoundingVolumeHierarchy.hpp:534
const Pair< const Box< N, Scalar >, T > * const_pointer
Const pointer type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:46
iterator insert(const Box< N, Scalar > &elementBoundingBox, const T &value)
Copy an element into the tree.
Definition LinearBoundingVolumeHierarchy.hpp:197
bool test(const Box< N, Scalar > &box) const noexcept
Check if it is possible that some element in the tree is intersecting with a given axis-aligned box.
Definition LinearBoundingVolumeHierarchy.hpp:558
Pair< const Box< N, Scalar >, T > & reference
Reference type of the container.
Definition LinearBoundingVolumeHierarchy.hpp:43
Definition concepts.hpp:106
@ N
'n'
Definition keyboard.hpp:84
float Scalar
Underlying scalar type of physics quantity components.
Definition quantities.hpp:1480
Definition aliases.hpp:9
GREM_ALWAYS_INLINE constexpr decltype(auto) clamp(T &&value, Low &&minValue, High &&maxValue)
Clamp a value to a specific interval.
Definition fundamentals.hpp:630
vec< N, T > Length
Generic length in N-dimensional space.
Definition geometry.hpp:38
constexpr bool intersects(const spherical_shape auto &a, const spherical_shape auto &b) noexcept
Check if two spherical shapes intersect.
Definition geometry.hpp:1662
LinearBoundingVolumeHierarchy< 3, Scalar, T > BoundingVolumeHierarchy3D
Binary tree-based space subdivision container, optimized for intersection queries between 3D axis-ali...
Definition LinearBoundingVolumeHierarchy.hpp:748
Span(R &&range) -> Span< std::remove_reference_t< decltype(*std::data(range))> >
vec< N, T > Point
Generic point in N-dimensional space.
Definition geometry.hpp:29
GREM_ALWAYS_INLINE constexpr decltype(auto) max(A &&a, B &&b)
Get the greater of two values, or the first value if they are equivalent.
Definition fundamentals.hpp:598
LinearBoundingVolumeHierarchy< 2, Scalar, T > BoundingVolumeHierarchy2D
Binary tree-based space subdivision container, optimized for intersection queries between 2D axis-ali...
Definition LinearBoundingVolumeHierarchy.hpp:738
GREM_ALWAYS_INLINE constexpr decltype(auto) min(A &&a, B &&b)
Get the smaller of two values, or the first value if they are equivalent.
Definition fundamentals.hpp:585
Generic axis-aligned box shape with minimum and maximum extents in N-dimensional space.
Definition geometry.hpp:149
constexpr bool contains(const Point< N, T > &point) const noexcept
Check if a given point is contained within the extents of this box.
Definition geometry.hpp:182
Point< N, T > max
Position with the maximum coordinates of the box extents on each coordinate axis.
Definition geometry.hpp:154
static constexpr T MAX
Definition fundamentals.hpp:29
static constexpr T MIN
Definition fundamentals.hpp:28
Definition Pair.hpp:53