-
Notifications
You must be signed in to change notification settings - Fork 834
Expand file tree
/
Copy patht10_observer.cpp
More file actions
81 lines (62 loc) · 2.27 KB
/
t10_observer.cpp
File metadata and controls
81 lines (62 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "behaviortree_cpp/bt_factory.h"
#include "behaviortree_cpp/loggers/bt_observer.h"
/** Show the use of the TreeObserver.
*/
// clang-format off
static const char* xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree ID="MainTree">
<Sequence>
<Fallback>
<AlwaysFailure name="failing_action"/>
<SubTree ID="SubTreeA" name="mysub"/>
</Fallback>
<AlwaysSuccess name="last_action"/>
</Sequence>
</BehaviorTree>
<BehaviorTree ID="SubTreeA">
<Sequence>
<AlwaysSuccess name="action_subA"/>
<SubTree ID="SubTreeB" name="sub_nested"/>
<SubTree ID="SubTreeB" />
</Sequence>
</BehaviorTree>
<BehaviorTree ID="SubTreeB">
<AlwaysSuccess name="action_subB"/>
</BehaviorTree>
</root>
)";
// clang-format on
int main()
{
BT::BehaviorTreeFactory factory;
factory.registerBehaviorTreeFromText(xml_text);
auto tree = factory.createTree("MainTree");
// Helper function to print the tree.
BT::printTreeRecursively(tree.rootNode());
// The purpose of the observer is to save some statistics about the number of times
// a certain node returns SUCCESS or FAILURE.
// This is particularly useful to create unit tests and to check if
// a certain set of transitions happened as expected
BT::TreeObserver observer(tree);
std::map<int, std::string> UID_to_path;
// Print the unique ID and the corresponding human readable path
// Path is also expected to be unique.
tree.applyVisitor([&UID_to_path](BT::TreeNode* node) {
UID_to_path[node->UID()] = node->fullPath();
std::cout << node->UID() << " -> " << node->fullPath() << std::endl;
});
tree.tickWhileRunning();
// You can access a specific statistic, using is full path or the UID
const auto& last_action_stats = observer.getStatistics("last_action");
assert(last_action_stats.transitions_count > 0);
std::cout << "----------------" << std::endl;
// print all the statistics
for(const auto& [uid, name] : UID_to_path)
{
const auto& stats = observer.getStatistics(uid);
std::cout << "[" << name << "] \tT/S/F: " << stats.transitions_count << "/"
<< stats.success_count << "/" << stats.failure_count << std::endl;
}
return 0;
}