|
| 1 | +#include "dummy_nodes.h" |
| 2 | +#include "behaviortree_cpp_v3/bt_factory.h" |
| 3 | + |
| 4 | + |
| 5 | +/** This example show how it is possible to: |
| 6 | + * - load BehaviorTrees from multiple files manually (without the <include> tag) |
| 7 | + * - instantiate a specific tree, instead of the one specified by [main_tree_to_execute] |
| 8 | + */ |
| 9 | + |
| 10 | +// clang-format off |
| 11 | + |
| 12 | +static const char* xml_text_main = R"( |
| 13 | +<root main_tree_to_execute="MainTree"> |
| 14 | + <BehaviorTree ID="MainTree"> |
| 15 | + <Sequence> |
| 16 | + <SaySomething message="starting MainTree" /> |
| 17 | + <SubTree ID="SubA"/> |
| 18 | + <SubTree ID="SubB"/> |
| 19 | + </Sequence> |
| 20 | + </BehaviorTree> |
| 21 | +</root> )"; |
| 22 | + |
| 23 | +static const char* xml_text_subA = R"( |
| 24 | +<root> |
| 25 | + <BehaviorTree ID="SubA"> |
| 26 | + <SaySomething message="Executing SubA" /> |
| 27 | + </BehaviorTree> |
| 28 | +</root> )"; |
| 29 | + |
| 30 | +static const char* xml_text_subB = R"( |
| 31 | +<root> |
| 32 | + <BehaviorTree ID="SubB"> |
| 33 | + <SaySomething message="Executing SubB" /> |
| 34 | + </BehaviorTree> |
| 35 | +</root> )"; |
| 36 | + |
| 37 | +// clang-format on |
| 38 | + |
| 39 | +using namespace BT; |
| 40 | + |
| 41 | +int main() |
| 42 | +{ |
| 43 | + BT::BehaviorTreeFactory factory; |
| 44 | + factory.registerNodeType<DummyNodes::SaySomething>("SaySomething"); |
| 45 | + |
| 46 | + // Register the behavior tree definitions, but do not instantiate them yet. |
| 47 | + // Order is not important. |
| 48 | + factory.registerBehaviorTreeFromText(xml_text_subA); |
| 49 | + factory.registerBehaviorTreeFromText(xml_text_subB); |
| 50 | + factory.registerBehaviorTreeFromText(xml_text_main); |
| 51 | + |
| 52 | + //Check that the BTs have been registered correctly |
| 53 | + std::cout << "Registered BehaviorTrees:" << std::endl; |
| 54 | + for(const std::string& bt_name: factory.registeredBehaviorTrees()) |
| 55 | + { |
| 56 | + std::cout << " - " << bt_name << std::endl; |
| 57 | + } |
| 58 | + |
| 59 | + // You can create the MainTree and the subtrees will be added automatically. |
| 60 | + std::cout << "----- MainTree tick ----" << std::endl; |
| 61 | + auto main_tree = factory.createdTree("MainTree"); |
| 62 | + main_tree.tickRoot(); |
| 63 | + |
| 64 | + // ... or you can create only one of the subtree |
| 65 | + std::cout << "----- SubA tick ----" << std::endl; |
| 66 | + auto subA_tree = factory.createdTree("SubA"); |
| 67 | + subA_tree.tickRoot(); |
| 68 | + |
| 69 | + return 0; |
| 70 | +} |
| 71 | +/* Expected output: |
| 72 | +
|
| 73 | +Registered BehaviorTrees: |
| 74 | + - MainTree |
| 75 | + - SubA |
| 76 | + - SubB |
| 77 | +----- MainTree tick ---- |
| 78 | +Robot says: starting MainTree |
| 79 | +Robot says: Executing SubA |
| 80 | +Robot says: Executing SubB |
| 81 | +----- SubA tick ---- |
| 82 | +Robot says: Executing SubA |
| 83 | +
|
| 84 | +*/ |
0 commit comments