GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
LooseOrthtree.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_LOOSE_ORTHTREE_HPP
5#define GREM_CORE_DATA_LOOSE_ORTHTREE_HPP
6
8
18#include <GREM/core/math.hpp>
20
21#include <type_traits> // std::conditional_t, std::is_convertible_v
22#include <utility> // std::forward, std::move, std::exchange, std::declval
23
24namespace grem {
25
26template <size_t N, typename Scalar, typename T>
27class LooseOrthtree; // Forward declaration.
28
33public:
34 constexpr LooseOrthtreeID() noexcept = default;
35
36 [[nodiscard]] constexpr bool operator==(const LooseOrthtreeID&) const noexcept = default;
37
38 constexpr operator bool() const noexcept {
39 return elementIndex != INVALID_ELEMENT;
40 }
41
42private:
43 using ElementIndex = uint32_t;
44
45 static constexpr ElementIndex INVALID_ELEMENT = Limits<ElementIndex>::MAX;
46
47 template <size_t N, typename Scalar, typename T>
48 friend class LooseOrthtree;
49
50 constexpr explicit LooseOrthtreeID(ElementIndex elementIndex) noexcept
51 : elementIndex(elementIndex) {}
52
53 ElementIndex elementIndex = INVALID_ELEMENT;
54};
55
64template <size_t N, typename Scalar, typename T>
66public:
67 static_assert(N == 2 || N == 3);
68
69 using value_type = T;
70 using reference = T&;
71 using const_reference = const T&;
72 using pointer = T*;
73 using const_pointer = const T*;
74 using size_type = size_t;
75 using difference_type = ptrdiff_t;
76
77private:
78 using NodeIndex = uint32_t;
79 using ElementIndex = LooseOrthtreeID::ElementIndex;
80
81 static constexpr ElementIndex INVALID_ELEMENT = LooseOrthtreeID::INVALID_ELEMENT;
82
83 struct Node {
84 using SubOrthantNodeIndices = Array<NodeIndex, (N == 2) ? 4 : 8>;
85
86 SubOrthantNodeIndices subOrthantNodeIndices{};
87 NodeIndex parentNodeIndex = 0;
88 ElementIndex firstElementIndex = INVALID_ELEMENT;
89 };
90
91 struct Element {
92 ElementIndex previousElementIndex = INVALID_ELEMENT;
93 ElementIndex nextElementIndex = INVALID_ELEMENT;
95 NodeIndex nodeIndex = 0;
96 };
97
98 template <bool Const>
99 class Iterator {
100 public:
101 using reference = std::conditional_t<Const, typename LooseOrthtree::const_reference, typename LooseOrthtree::reference>;
102 using pointer = std::conditional_t<Const, typename LooseOrthtree::const_pointer, typename LooseOrthtree::pointer>;
103 using difference_type = typename LooseOrthtree::difference_type;
104 using value_type = typename LooseOrthtree::value_type;
105
106 constexpr Iterator() noexcept = default;
107
108 constexpr operator Iterator<true>() const noexcept requires(!Const) {
109 return Iterator<true>{container, elementIndex};
110 }
111
112 constexpr operator LooseOrthtreeID() const noexcept {
113 return LooseOrthtreeID{elementIndex};
114 }
115
116 [[nodiscard]] constexpr reference operator*() const {
117 GREM_ASSERT(container);
118 return *container->elements[elementIndex].value;
119 }
120
121 [[nodiscard]] constexpr pointer operator->() const {
122 return &**this;
123 }
124
125 [[nodiscard]] constexpr bool operator==(const Iterator& other) const {
126 GREM_ASSERT(container == other.container);
127 return elementIndex == other.elementIndex;
128 }
129
130 constexpr Iterator& operator++() {
131 GREM_ASSERT(container);
132 GREM_ASSERT(elementIndex < container->elements.size());
133 do {
134 ++elementIndex;
135 } while (elementIndex < container->elements.size() && !container->elements[elementIndex].value);
136 return *this;
137 }
138
139 constexpr Iterator operator++(int) {
140 Iterator old = *this;
141 ++*this;
142 return old;
143 }
144
145 private:
146 friend LooseOrthtree;
147
148 constexpr Iterator(std::conditional_t<Const, const LooseOrthtree, LooseOrthtree>* container, ElementIndex elementIndex) noexcept
149 : container(container)
150 , elementIndex(elementIndex) {}
151
152 std::conditional_t<Const, const LooseOrthtree, LooseOrthtree>* container = nullptr;
153 ElementIndex elementIndex = 0;
154 };
155
156 template <bool Const>
157 class LocalIterator {
158 public:
159 using reference = std::conditional_t<Const, typename LooseOrthtree::const_reference, typename LooseOrthtree::reference>;
160 using pointer = std::conditional_t<Const, typename LooseOrthtree::const_pointer, typename LooseOrthtree::pointer>;
161 using difference_type = typename LooseOrthtree::difference_type;
162 using value_type = typename LooseOrthtree::value_type;
163
164 constexpr LocalIterator() noexcept = default;
165
166 constexpr operator Iterator<true>() const noexcept requires(!Const) {
167 return Iterator<true>{container, elementIndex};
168 }
169
170 constexpr operator LooseOrthtreeID() const noexcept {
171 return LooseOrthtreeID{elementIndex};
172 }
173
174 [[nodiscard]] constexpr reference operator*() const {
175 GREM_ASSERT(container);
176 return *container->elements[elementIndex].value;
177 }
178
179 [[nodiscard]] constexpr pointer operator->() const {
180 return &**this;
181 }
182
183 [[nodiscard]] constexpr bool operator==(const LocalIterator& other) const {
184 GREM_ASSERT(container == other.container);
185 return elementIndex == other.elementIndex;
186 }
187
188 constexpr LocalIterator& operator++() {
189 GREM_ASSERT(container);
190 elementIndex = container->elements[elementIndex].nextElementIndex;
191 return *this;
192 }
193
194 constexpr LocalIterator operator++(int) {
195 Iterator old = *this;
196 ++*this;
197 return old;
198 }
199
200 private:
201 friend LooseOrthtree;
202
203 constexpr LocalIterator(std::conditional_t<Const, const LooseOrthtree, LooseOrthtree>* container, ElementIndex elementIndex) noexcept
204 : container(container)
205 , elementIndex(elementIndex) {}
206
207 std::conditional_t<Const, const LooseOrthtree, LooseOrthtree>* container = nullptr;
208 ElementIndex elementIndex = 0;
209 };
210
211public:
212 using iterator = Iterator<false>;
213 using const_iterator = Iterator<true>;
214 using local_iterator = LocalIterator<false>;
215 using const_local_iterator = LocalIterator<true>;
216
221 LooseOrthtree() noexcept
222 : LooseOrthtree(Box<N, Scalar>{}, Scalar{}) {}
223
234 LooseOrthtree(const Box<N, Scalar>& worldBoundingBox, Scalar minOrthantSize) noexcept {
235 reset(worldBoundingBox, minOrthantSize);
236 }
237
250 void reset(const Box<N, Scalar>& newWorldBoundingBox, Scalar newMinOrthantSize) noexcept {
251 clear();
252 minOrthantSize = newMinOrthantSize;
253 rootCenter = (newWorldBoundingBox.min + newWorldBoundingBox.max) * Scalar{0.5};
254 const Length<N, Scalar> worldMaxExtents = max(newWorldBoundingBox.max - rootCenter, rootCenter - newWorldBoundingBox.min);
255 const Scalar worldMaxExtent = maxComponent(worldMaxExtents);
256 // Double the root size until it fits the entire world.
257 halfRootSize = newMinOrthantSize;
258 while (halfRootSize < worldMaxExtent) {
259 halfRootSize *= Scalar{2};
260 }
261 }
262
269 void clear() noexcept {
270 tree.clear();
271 elements.clear();
272 elementCount = 0;
273 firstFreeNodeIndex = 0;
274 firstFreeElementIndex = INVALID_ELEMENT;
275 }
276
282 [[nodiscard]] Scalar getMinOrthantSize() const noexcept {
283 return minOrthantSize;
284 }
285
291 [[nodiscard]] Box<N, Scalar> getRootBox() const noexcept {
292 const Length<N, Scalar> rootHalfExtents{halfRootSize};
293 return Box<N, Scalar>{.min = rootCenter - rootHalfExtents, .max = rootCenter + rootHalfExtents};
294 }
295
303 [[nodiscard]] iterator begin() noexcept {
304 ElementIndex elementIndex = 0;
305 while (elementIndex < elements.size() && !elements[elementIndex].value) {
306 ++elementIndex;
307 }
308 return iterator{this, elementIndex};
309 }
310
318 [[nodiscard]] const_iterator begin() const noexcept {
319 ElementIndex elementIndex = 0;
320 while (elementIndex < elements.size() && !elements[elementIndex].value) {
321 ++elementIndex;
322 }
323 return const_iterator{this, elementIndex};
324 }
325
333 [[nodiscard]] const_iterator cbegin() const noexcept {
334 return begin();
335 }
336
344 [[nodiscard]] iterator end() noexcept {
345 return iterator{this, static_cast<ElementIndex>(elements.size())};
346 }
347
355 [[nodiscard]] const_iterator end() const noexcept {
356 return const_iterator{this, static_cast<ElementIndex>(elements.size())};
357 }
358
366 [[nodiscard]] const_iterator cend() const noexcept {
367 return end();
368 }
369
375 [[nodiscard]] size_type size() const noexcept {
376 return elementCount;
377 }
378
384 [[nodiscard]] bool empty() const noexcept {
385 return size() == 0;
386 }
387
403 template <typename... Args>
404 iterator emplace(const Box<N, Scalar>& elementBoundingBox, Args&&... args) {
405 // Make sure the tree has a root.
406 if (tree.empty()) {
407 tree.emplace_back();
408 }
409
410 // Find the center of the AABB.
411 const Length<N, Scalar> aabbDiagonal = elementBoundingBox.max - elementBoundingBox.min;
412 const Point<N, Scalar> aabbCenter = elementBoundingBox.min + aabbDiagonal * Scalar{0.5};
413
414 // Find the largest extent of the AABB.
415 const Scalar aabbSize = [&] {
416 if constexpr (N == 2) {
417 return max(aabbDiagonal.x, aabbDiagonal.y);
418 } else {
419 return max(max(aabbDiagonal.x, aabbDiagonal.y), aabbDiagonal.z);
420 }
421 }();
422
423 // Start at the root of the tree and descend to the smallest orthant that contains the entire AABB within its loose bounds.
424 // The loose bounds is a box around the orthant that is twice as big as the orthant in every direction and shares the same center.
425 // Since the loose bounds of adjacent orthants overlap, it could happen that the AABB is contained within multiple orthants' loose bounds at the same time.
426 // In that case, the closest orthant, i.e. the one which contains the center of the AABB, is chosen.
427 // The loop stops going lower in the tree when the AABB can no longer fit in a smaller orthant, or when we reach the minimum orthant size.
428 Scalar orthantSize = halfRootSize;
429 Point<N, Scalar> center = rootCenter;
430 NodeIndex nodeIndex = 0;
431 while (orthantSize >= aabbSize && orthantSize >= minOrthantSize) {
432 orthantSize *= Scalar{0.5};
433
434 // Determine which orthant the AABB belongs to.
435 const Length<N, Scalar> difference = aabbCenter - center;
436 const size_t subOrthantArrayIndex = getSubOrthantArrayIndex(difference);
437
438 // Update the center.
439 center += copysign(Length<N, Scalar>{orthantSize}, difference);
440
441 // Descend to the chosen orthant.
442 const NodeIndex parentNodeIndex = nodeIndex;
443 if (const NodeIndex orthantNodeIndex = tree[parentNodeIndex].subOrthantNodeIndices[subOrthantArrayIndex]) {
444 // The orthant already exists in the tree. Go directly to it.
445 nodeIndex = orthantNodeIndex;
446 } else {
447 // The orthant does not exist in the tree yet. Acquire a slot in the tree for a new node.
448 if (firstFreeNodeIndex != 0) {
449 // Re-use the first free node, update the free index and go to the new node.
450 // Note: The first sub-orthant index in each free node leads to the next free node after it.
451 nodeIndex = std::exchange(firstFreeNodeIndex, std::exchange(tree[firstFreeNodeIndex].subOrthantNodeIndices.front(), NodeIndex{0}));
452 } else {
453 // No free orthants available for re-use. Allocate a new node and go to it.
454 if (tree.size() >= size_t{Limits<NodeIndex>::MAX}) {
455 throw std::length_error{"Maximum node count exceeded."};
456 }
457 nodeIndex = static_cast<NodeIndex>(tree.size());
458 tree.emplace_back();
459 }
460 // Set the new orthant's parent node index.
461 tree[nodeIndex].parentNodeIndex = parentNodeIndex;
462 // Update the parent node to point to the new node.
463 tree[parentNodeIndex].subOrthantNodeIndices[subOrthantArrayIndex] = nodeIndex;
464 }
465 }
466
467 // Acquire a slot for the new element.
468 ElementIndex elementIndex = INVALID_ELEMENT;
469 try {
470 if (firstFreeElementIndex != INVALID_ELEMENT) {
471 // Re-use the first free element and update the free index.
472 // Note: The next element index in each free element leads to the next free element after it.
473 elementIndex = std::exchange(firstFreeElementIndex, std::exchange(elements[firstFreeElementIndex].nextElementIndex, INVALID_ELEMENT));
474 } else {
475 // No free elements available for re-use. Allocate a new element.
476 if (elements.size() >= size_t{Limits<ElementIndex>::MAX}) {
477 throw std::length_error{"Maximum element count exceeded."};
478 }
479 elementIndex = static_cast<ElementIndex>(elements.size());
480 elements.emplace_back();
481 }
482 // Construct the new element value.
483 try {
484 elements[elementIndex].value.emplace(std::forward<Args>(args)...);
485 } catch (...) {
486 cleanupElement(elementIndex);
487 throw;
488 }
489 } catch (...) {
490 cleanupNode(nodeIndex);
491 throw;
492 }
493
494 // Insert the new element into the selected node.
495 elements[elementIndex].nodeIndex = nodeIndex;
496 ElementIndex& firstElementIndex = tree[nodeIndex].firstElementIndex;
497 GREM_ASSERT(firstElementIndex != elementIndex);
498 if (firstElementIndex != INVALID_ELEMENT) {
499 elements[firstElementIndex].previousElementIndex = elementIndex;
500 }
501 GREM_ASSERT(elements[elementIndex].previousElementIndex == INVALID_ELEMENT);
502 elements[elementIndex].nextElementIndex = std::exchange(firstElementIndex, elementIndex);
503 GREM_ASSERT(elements[elementIndex].nextElementIndex != elementIndex);
504
505 ++elementCount;
506 return iterator{this, elementIndex};
507 }
508
524 iterator insert(const Box<N, Scalar>& elementBoundingBox, const T& value) {
525 return emplace(elementBoundingBox, value);
526 }
527
543 iterator insert(const Box<N, Scalar>& elementBoundingBox, T&& value) {
544 return emplace(elementBoundingBox, std::move(value));
545 }
546
557 GREM_ASSERT(pos.container == this);
558 iterator result{this, pos.elementIndex};
559 ++result;
561 return result;
562 }
563
572 eraseAtIndex(id.elementIndex);
573 }
574
584 return *elements[id.elementIndex].value;
585 }
586
596 return *elements[id.elementIndex].value;
597 }
598
643 template <typename Callback, typename Predicate>
644 auto traverseNodes(Callback&& callback, Predicate&& predicate) const { // NOLINT(cppcoreguidelines-missing-std-forward)
645 return traverseNodesImplementation(
646 [this, callback = std::forward<Callback>(callback)](const Box<N, Scalar>& looseBounds, NodeIndex nodeIndex) mutable {
647 const const_local_iterator first{this, tree[nodeIndex].firstElementIndex};
648 const const_local_iterator last{this, INVALID_ELEMENT};
649 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<decltype(callback(looseBounds, first, last)), bool>;
650 if constexpr (CALLBACK_RETURNS_BOOL) {
651 return callback(looseBounds, first, last);
652 } else {
653 callback(looseBounds, first, last);
654 }
655 },
656 std::forward<Predicate>(predicate));
657 }
658
694 template <typename Callback>
695 auto traverseNodes(Callback&& callback) const {
696 return traverseNodes(std::forward<Callback>(callback), [](const Box<N, Scalar>&) -> bool { return true; });
697 }
698
736 template <typename Callback, typename Predicate>
737 auto traverseElements(Callback&& callback, Predicate&& predicate) const { // NOLINT(cppcoreguidelines-missing-std-forward)
738 return traverseNodesImplementation(
739 [this, callback = std::forward<Callback>(callback)](const Box<N, Scalar>&, NodeIndex nodeIndex) mutable {
740 const const_local_iterator first{this, tree[nodeIndex].firstElementIndex};
741 const const_local_iterator last{this, INVALID_ELEMENT};
742 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<decltype(callback(*first)), bool>;
743 for (const_local_iterator it = first; it != last; ++it) {
744 if constexpr (CALLBACK_RETURNS_BOOL) {
745 if (callback(*it)) {
746 return true; // Callback requested early return.
747 }
748 } else {
749 callback(*it);
750 }
751 }
752 if constexpr (CALLBACK_RETURNS_BOOL) {
753 return false;
754 }
755 },
756 std::forward<Predicate>(predicate));
757 }
758
787 template <typename Callback>
788 auto traverseElements(Callback&& callback) const {
789 return traverseElements(std::forward<Callback>(callback), [](const Box<N, Scalar>&) -> bool { return true; });
790 }
791
822 template <typename Callback>
823 auto test(Point<N, Scalar> point, Callback&& callback) const {
824 return traverseElements(std::forward<Callback>(callback), [&point](const Box<N, Scalar>& boundingBox) -> bool { return boundingBox.contains(point); });
825 }
826
842 [[nodiscard]] bool test(Point<N, Scalar> point) const noexcept {
843 return traverseElements([](const T&) -> bool { return true; }, [&point](const Box<N, Scalar>& boundingBox) -> bool { return boundingBox.contains(point); });
844 }
845
876 template <typename Callback>
877 auto test(const Box<N, Scalar>& box, Callback&& callback) const {
878 return traverseElements(std::forward<Callback>(callback), [&box](const Box<N, Scalar>& boundingBox) -> bool { return intersects(boundingBox, box); });
879 }
880
897 [[nodiscard]] bool test(const Box<N, Scalar>& box) const noexcept {
898 return traverseElements([](const T&) -> bool { return true; }, [&box](const Box<N, Scalar>& boundingBox) -> bool { return intersects(boundingBox, box); });
899 }
900
901 template <typename U>
902 friend size_type erase(LooseOrthtree& c, const U& value) {
903 return erase_if(c, [&](const value_type& v) -> bool { return v == value; });
904 }
905
906 template <typename Predicate>
907 friend size_type erase_if(LooseOrthtree& c, Predicate predicate) {
908 size_type result = 0;
909 for (ElementIndex elementIndex = 0; elementIndex < c.elements.size(); ++elementIndex) {
910 if (const Optional<value_type>& value = c.elements[elementIndex].value) {
911 if (predicate(*value)) {
912 c.eraseAtIndex(elementIndex);
913 ++result;
914 }
915 }
916 }
917 return result;
918 }
919
920private:
921 [[nodiscard]] static constexpr size_t getSubOrthantArrayIndex(Length<N, Scalar> difference) {
922 size_t result = 0;
923 for (size_t i = 0; i < N; ++i) {
924 result |= static_cast<size_t>(!signbit(difference[i])) << (N - 1 - i);
925 }
926 return result;
927 }
928
929 template <typename Callback>
930 static constexpr void forEachActiveOrthant(const Node::SubOrthantNodeIndices& subOrthantNodeIndices, Point<N, Scalar> center, Scalar halfOrthantSize,
931 Callback&& callback) { // NOLINT(cppcoreguidelines-missing-std-forward)
932 if constexpr (N == 2) {
933 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b00]) {
934 callback(orthantNodeIndex, Point<2, Scalar>{center.x - halfOrthantSize, center.y - halfOrthantSize});
935 }
936 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b01]) {
937 callback(orthantNodeIndex, Point<2, Scalar>{center.x - halfOrthantSize, center.y + halfOrthantSize});
938 }
939 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b10]) {
940 callback(orthantNodeIndex, Point<2, Scalar>{center.x + halfOrthantSize, center.y - halfOrthantSize});
941 }
942 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b11]) {
943 callback(orthantNodeIndex, Point<2, Scalar>{center.x + halfOrthantSize, center.y + halfOrthantSize});
944 }
945 } else {
946 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b000]) {
947 callback(orthantNodeIndex, Point<3, Scalar>{center.x - halfOrthantSize, center.y - halfOrthantSize, center.z - halfOrthantSize});
948 }
949 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b001]) {
950 callback(orthantNodeIndex, Point<3, Scalar>{center.x - halfOrthantSize, center.y - halfOrthantSize, center.z + halfOrthantSize});
951 }
952 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b010]) {
953 callback(orthantNodeIndex, Point<3, Scalar>{center.x - halfOrthantSize, center.y + halfOrthantSize, center.z - halfOrthantSize});
954 }
955 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b011]) {
956 callback(orthantNodeIndex, Point<3, Scalar>{center.x - halfOrthantSize, center.y + halfOrthantSize, center.z + halfOrthantSize});
957 }
958 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b100]) {
959 callback(orthantNodeIndex, Point<3, Scalar>{center.x + halfOrthantSize, center.y - halfOrthantSize, center.z - halfOrthantSize});
960 }
961 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b101]) {
962 callback(orthantNodeIndex, Point<3, Scalar>{center.x + halfOrthantSize, center.y - halfOrthantSize, center.z + halfOrthantSize});
963 }
964 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b110]) {
965 callback(orthantNodeIndex, Point<3, Scalar>{center.x + halfOrthantSize, center.y + halfOrthantSize, center.z - halfOrthantSize});
966 }
967 if (const NodeIndex orthantNodeIndex = subOrthantNodeIndices[0b111]) {
968 callback(orthantNodeIndex, Point<3, Scalar>{center.x + halfOrthantSize, center.y + halfOrthantSize, center.z + halfOrthantSize});
969 }
970 }
971 }
972
973 template <typename Callback, typename Predicate>
974 auto traverseNodesImplementation(Callback&& callback, Predicate&& predicate) const { // NOLINT(cppcoreguidelines-missing-std-forward)
975 constexpr bool CALLBACK_RETURNS_BOOL = std::is_convertible_v<decltype(callback(std::declval<const Box<N, Scalar>&>(), std::declval<const NodeIndex&>())), bool>;
976
977 if (!tree.empty()) {
978 struct IterationState {
979 Point<N, Scalar> center;
980 Scalar orthantSize;
981 NodeIndex nodeIndex;
982 };
983 SmallBuffer<IterationState, 24> iterationStack{};
984
985 iterationStack.push_back(IterationState{
986 .center = rootCenter,
987 .orthantSize = halfRootSize,
988 .nodeIndex = 0,
989 });
990 do {
991 const IterationState iterationState = iterationStack.back();
992 iterationStack.pop_back();
993
994 const Point<N, Scalar> center = iterationState.center;
995 const Scalar orthantSize = iterationState.orthantSize;
996 const NodeIndex nodeIndex = iterationState.nodeIndex;
997 const Length<N, Scalar> looseBoundsHalfSize{orthantSize * Scalar{2}};
998 const Box<N, Scalar> looseBounds{center - looseBoundsHalfSize, center + looseBoundsHalfSize};
999 if constexpr (CALLBACK_RETURNS_BOOL) {
1000 if (callback(looseBounds, nodeIndex)) {
1001 return true; // Callback requested early return.
1002 }
1003 } else {
1004 callback(looseBounds, nodeIndex);
1005 }
1006
1007 const Scalar halfOrthantSize = orthantSize * Scalar{0.5};
1008 forEachActiveOrthant(tree[nodeIndex].subOrthantNodeIndices, center, halfOrthantSize,
1009 [&iterationStack, &predicate, orthantSize, halfOrthantSize](NodeIndex orthantNodeIndex, Point<N, Scalar> orthantCenter) {
1010 const Box<N, Scalar> looseBounds{orthantCenter - Length<N, Scalar>{orthantSize}, orthantCenter + Length<N, Scalar>{orthantSize}};
1011 if (predicate(looseBounds)) {
1012 iterationStack.push_back(IterationState{
1013 .center = orthantCenter,
1014 .orthantSize = halfOrthantSize,
1015 .nodeIndex = orthantNodeIndex,
1016 });
1017 }
1018 });
1019 } while (!iterationStack.empty());
1020 }
1021
1022 if constexpr (CALLBACK_RETURNS_BOOL) {
1023 return false;
1024 }
1025 }
1026
1027 [[nodiscard]] static bool isNodeEmpty(const Node& node) {
1028 return node.firstElementIndex == INVALID_ELEMENT && allOf(node.subOrthantNodeIndices, [](NodeIndex orthantNodeIndex) -> bool { return orthantNodeIndex == 0; });
1029 }
1030
1031 void cleanupNode(NodeIndex nodeIndex) noexcept {
1032 Node* node = &tree[nodeIndex];
1033 while (isNodeEmpty(*node)) {
1034 if (nodeIndex == 0) {
1035 clear();
1036 break;
1037 }
1038 node->subOrthantNodeIndices.front() = std::exchange(firstFreeNodeIndex, std::exchange(nodeIndex, node->parentNodeIndex));
1039 node = &tree[nodeIndex];
1040 for (NodeIndex& orthantNodeIndex : node->subOrthantNodeIndices) {
1041 if (orthantNodeIndex == firstFreeNodeIndex) {
1042 orthantNodeIndex = 0;
1043 break;
1044 }
1045 }
1046 }
1047 }
1048
1049 void cleanupElement(ElementIndex elementIndex) noexcept {
1050 Element& element = elements[elementIndex];
1051 const ElementIndex previousElementIndex = std::exchange(element.previousElementIndex, INVALID_ELEMENT);
1052 if (element.nextElementIndex != INVALID_ELEMENT) {
1053 elements[element.nextElementIndex].previousElementIndex = previousElementIndex;
1054 }
1055 ElementIndex& previousNextElementIndex =
1056 (previousElementIndex == INVALID_ELEMENT) ? tree[element.nodeIndex].firstElementIndex : elements[previousElementIndex].nextElementIndex;
1057 previousNextElementIndex = std::exchange(element.nextElementIndex, std::exchange(firstFreeElementIndex, elementIndex));
1058 GREM_ASSERT(elements[elementIndex].nextElementIndex != elementIndex);
1059 if (element.nodeIndex != 0) {
1060 cleanupNode(std::exchange(element.nodeIndex, NodeIndex{0}));
1061 }
1062 }
1063
1064 void eraseAtIndex(ElementIndex elementIndex) {
1065 GREM_ASSERT(elementCount > 0);
1066 GREM_ASSERT(elementIndex < elements.size());
1067 GREM_ASSERT(elements[elementIndex].value.has_value());
1068 --elementCount;
1069 elements[elementIndex].value.reset();
1070 cleanupElement(elementIndex);
1071 }
1072
1073 ArrayList<Node> tree{};
1074 ArrayList<Element> elements{};
1075 size_type elementCount = 0;
1076 Scalar minOrthantSize{};
1077 Scalar halfRootSize{};
1078 Point<N, Scalar> rootCenter{};
1079 NodeIndex firstFreeNodeIndex = 0;
1080 ElementIndex firstFreeElementIndex = INVALID_ELEMENT;
1081};
1082
1087
1095template <typename Scalar, typename T>
1097
1102
1110template <typename Scalar, typename T>
1112
1113} // namespace grem
1114
1115#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
constexpr size_type size() const noexcept
Definition ArrayList.hpp:297
Opaque handle to an element in a LooseOrthtree.
Definition LooseOrthtree.hpp:32
constexpr LooseOrthtreeID() noexcept=default
friend class LooseOrthtree
Definition LooseOrthtree.hpp:48
Orthtree-based space subdivision structure, optimized for intersection queries between axis-aligned b...
Definition LooseOrthtree.hpp:65
Box< N, Scalar > getRootBox() const noexcept
Get the current root box of the tree.
Definition LooseOrthtree.hpp:291
iterator begin() noexcept
Get the begin iterator of the elements in the tree.
Definition LooseOrthtree.hpp:303
iterator insert(const Box< N, Scalar > &elementBoundingBox, T &&value)
Move an element into the tree.
Definition LooseOrthtree.hpp:543
iterator erase(const_iterator pos)
Remove an element from the tree.
Definition LooseOrthtree.hpp:556
const T & const_reference
Const reference type of the container.
Definition LooseOrthtree.hpp:71
iterator end() noexcept
Get the end iterator of the elements in the tree.
Definition LooseOrthtree.hpp:344
void reset(const Box< N, Scalar > &newWorldBoundingBox, Scalar newMinOrthantSize) noexcept
Reset the tree to an empty state with new world parameters.
Definition LooseOrthtree.hpp:250
const_iterator begin() const noexcept
Get the begin iterator of the elements in the tree.
Definition LooseOrthtree.hpp:318
size_t size_type
Size type of the container.
Definition LooseOrthtree.hpp:74
Scalar getMinOrthantSize() const noexcept
Get the current minimum orthant size of the tree.
Definition LooseOrthtree.hpp:282
iterator emplace(const Box< N, Scalar > &elementBoundingBox, Args &&... args)
Construct a new element in the tree.
Definition LooseOrthtree.hpp:404
LooseOrthtree() noexcept
Construct an invalid tree that must be reset with valid world parameters before use.
Definition LooseOrthtree.hpp:221
auto traverseElements(Callback &&callback, Predicate &&predicate) const
Execute a callback function for each element in the tree.
Definition LooseOrthtree.hpp:737
T & reference
Reference type of the container.
Definition LooseOrthtree.hpp:70
const_iterator cend() const noexcept
Get the end iterator of the elements in the tree.
Definition LooseOrthtree.hpp:366
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 LooseOrthtree.hpp:897
LocalIterator< true > const_local_iterator
Const local iterator type for the nodes of the container.
Definition LooseOrthtree.hpp:215
void clear() noexcept
Erase all inserted elements from the tree.
Definition LooseOrthtree.hpp:269
auto traverseNodes(Callback &&callback, Predicate &&predicate) const
Execute a callback function for each active node of the tree, including empty internal nodes without ...
Definition LooseOrthtree.hpp:644
T value_type
Value type of the container.
Definition LooseOrthtree.hpp:69
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 LooseOrthtree.hpp:877
Iterator< false > iterator
Iterator type of the container.
Definition LooseOrthtree.hpp:212
LooseOrthtree(const Box< N, Scalar > &worldBoundingBox, Scalar minOrthantSize) noexcept
Construct an empty tree.
Definition LooseOrthtree.hpp:234
void erase(LooseOrthtreeID id)
Remove an element from the tree.
Definition LooseOrthtree.hpp:571
auto traverseNodes(Callback &&callback) const
Execute a callback function for each active node of the tree, including empty internal nodes without ...
Definition LooseOrthtree.hpp:695
iterator insert(const Box< N, Scalar > &elementBoundingBox, const T &value)
Copy an element into the tree.
Definition LooseOrthtree.hpp:524
const T * const_pointer
Const pointer type of the container.
Definition LooseOrthtree.hpp:73
const_iterator cbegin() const noexcept
Get the begin iterator of the elements in the tree.
Definition LooseOrthtree.hpp:333
bool test(Point< N, Scalar > point) const noexcept
Check if it is possible that some element in the tree contains a given point.
Definition LooseOrthtree.hpp:842
const_iterator end() const noexcept
Get the end iterator of the elements in the tree.
Definition LooseOrthtree.hpp:355
reference operator[](LooseOrthtreeID id)
Get the element with a specific handle.
Definition LooseOrthtree.hpp:583
LocalIterator< false > local_iterator
Local iterator type for the nodes of the container.
Definition LooseOrthtree.hpp:214
Iterator< true > const_iterator
Const iterator type of the container.
Definition LooseOrthtree.hpp:213
bool empty() const noexcept
Check whether the tree is empty or not.
Definition LooseOrthtree.hpp:384
friend size_type erase_if(LooseOrthtree &c, Predicate predicate)
Definition LooseOrthtree.hpp:907
size_type size() const noexcept
Get the number of elements in the tree.
Definition LooseOrthtree.hpp:375
friend size_type erase(LooseOrthtree &c, const U &value)
Definition LooseOrthtree.hpp:902
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 LooseOrthtree.hpp:823
auto traverseElements(Callback &&callback) const
Execute a callback function for each element in the tree.
Definition LooseOrthtree.hpp:788
const_reference operator[](LooseOrthtreeID id) const
Get the element with a specific handle.
Definition LooseOrthtree.hpp:595
ptrdiff_t difference_type
Difference type of the container.
Definition LooseOrthtree.hpp:75
Optional value type that holds either a value or no value.
Definition Optional.hpp:58
Definition concepts.hpp:106
@ N
'n'
Definition keyboard.hpp:84
size_t NodeIndex
Index into Asset::nodes.
Definition gltf.hpp:145
float Scalar
Underlying scalar type of physics quantity components.
Definition quantities.hpp:1480
Definition aliases.hpp:9
LooseOrthtreeID LooseQuadtreeID
Opaque handle to an element in a LooseQuadtree.
Definition LooseOrthtree.hpp:1086
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
GREM_ALWAYS_INLINE T copysign(T magnitude, T sign)
Get a value with the sign of a different value.
Definition math.hpp:3601
LooseOrthtree< 2, Scalar, T > LooseQuadtree
Quadtree-based space subdivision container, optimized for intersection queries between 2D axis-aligne...
Definition LooseOrthtree.hpp:1096
vec< N, T > Point
Generic point in N-dimensional space.
Definition geometry.hpp:29
LooseOrthtreeID LooseOctreeID
Opaque handle to an element in a LooseOctree.
Definition LooseOrthtree.hpp:1101
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
GREM_ALWAYS_INLINE vec< N, bool > GREM_VECTORCALL signbit(vec< N, T > values)
Get the sign bits of the components of a vector.
Definition math.hpp:3584
constexpr bool allOf(input_range auto &&range, auto predicate)
Definition algorithms.hpp:226
LooseOrthtree< 3, Scalar, T > LooseOctree
Octree-based space subdivision container, optimized for intersection queries between 3D axis-aligned ...
Definition LooseOrthtree.hpp:1111
GREM_ALWAYS_INLINE constexpr T GREM_VECTORCALL maxComponent(vec< 1, T > a)
Definition math.hpp:1920
Definition Array.hpp:20
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
Point< N, T > min
Position with the minimum coordinates of the box extents on each coordinate axis.
Definition geometry.hpp:153
static constexpr T MAX
Definition fundamentals.hpp:29