PhysicsBasedAnimationToolkit 0.0.10
Cross-platform C++20 library of algorithms and data structures commonly used in computer graphics research on physically-based simulation.
Loading...
Searching...
No Matches
NAryTreeTraversal.h
Go to the documentation of this file.
1
9
10#ifndef PBAT_COMMON_NARYTREETRAVERSAL_H
11#define PBAT_COMMON_NARYTREETRAVERSAL_H
12
13#include "ConstexprFor.h"
14#include "Stack.h"
15#include "pbat/Aliases.h"
16#include "pbat/HostDevice.h"
17
18namespace pbat::common {
19
37template <class FVisit, class FChild, class TIndex = Index, auto N = 2, auto kStackDepth = 64>
38PBAT_HOST_DEVICE void TraverseNAryTreePseudoPreOrder(FVisit fVisit, FChild fChild, TIndex root = 0);
39
60template <class FVisit, class FChild, class TIndex = Index, auto N = 2, auto kStackDepth = 64>
61PBAT_HOST_DEVICE void
62TraverseNAryTreePseudoPostOrder(FVisit fVisit, FChild fChild, TIndex root = 0);
63
64template <class FVisit, class FChild, class TIndex, auto N, auto kStackDepth>
65PBAT_HOST_DEVICE void TraverseNAryTreePseudoPreOrder(FVisit fVisit, FChild fChild, TIndex root)
66{
68 dfs.Push(root);
69 while (not dfs.IsEmpty())
70 {
71 TIndex const node = dfs.Pop();
72 if (not fVisit(node))
73 continue;
74
75 ForRange<0, N>([&]<auto i> {
76 auto const child = fChild.template operator()<N - i - 1>(node);
77 if (child >= 0)
78 dfs.Push(child);
79 });
80 }
81}
82
83template <class FVisit, class FChild, class TIndex, auto N, auto kStackDepth>
84PBAT_HOST_DEVICE void TraverseNAryTreePseudoPostOrder(FVisit fVisit, FChild fChild, TIndex root)
85{
86 struct Visit
87 {
88 TIndex node;
89 bool bChildrenVisited;
90 };
92 dfs.Push({root, false});
93 while (not dfs.IsEmpty())
94 {
95 auto const visit = dfs.Top();
96 dfs.Pop();
97 if (visit.bChildrenVisited)
98 {
99 fVisit(visit.node);
100 }
101 else
102 {
103 dfs.Push({visit.node, true});
104 ForRange<0, N>([&]<auto i> {
105 auto const child = fChild.template operator()<N - i - 1>(visit.node);
106 if (child >= 0)
107 dfs.Push({child, false});
108 });
109 }
110 }
111}
112
113} // namespace pbat::common
114
115#endif // PBAT_COMMON_NARYTREETRAVERSAL_H
Compile-time for loops.
Fixed-size stack implementation.
Definition Stack.h:26
PBAT_HOST_DEVICE void Push(T value)
Add element to the stack.
Definition Stack.h:37
Fixed-size stack implementation usable in both host and device code.
Common functionality.
Definition ArgSort.h:20
PBAT_HOST_DEVICE void TraverseNAryTreePseudoPreOrder(FVisit fVisit, FChild fChild, TIndex root=0)
Pre-order traversal over an n-ary tree starting from root.
Definition NAryTreeTraversal.h:65
PBAT_HOST_DEVICE void TraverseNAryTreePseudoPostOrder(FVisit fVisit, FChild fChild, TIndex root=0)
Post-order traversal over an n-ary tree starting from root.
Definition NAryTreeTraversal.h:84
constexpr void ForRange(F &&f)
Compile-time for loop over a range of values.
Definition ConstexprFor.h:55