forked from BehaviorTree/BehaviorTree.CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxml_parsing.cpp
1512 lines (1342 loc) · 48.4 KB
/
xml_parsing.cpp
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2018-2020 Davide Faconti, Eurecat - All Rights Reserved
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <list>
#include <sstream>
#include <string>
#include <typeindex>
#if defined(__linux) || defined(__linux__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wattributes"
#endif
#include <map>
#include "behaviortree_cpp/xml_parsing.h"
#include "tinyxml2/tinyxml2.h"
#include <filesystem>
#ifdef USING_ROS
#include <ros/package.h>
#endif
#ifdef USING_ROS2
#include <ament_index_cpp/get_package_share_directory.hpp>
#endif
#include "behaviortree_cpp/blackboard.h"
#include "behaviortree_cpp/tree_node.h"
#include "behaviortree_cpp/utils/demangle_util.h"
namespace
{
std::string xsdAttributeType(const BT::PortInfo& port_info)
{
if(port_info.direction() == BT::PortDirection::OUTPUT)
{
return "blackboardType";
}
const auto& type_info = port_info.type();
if((type_info == typeid(int)) or (type_info == typeid(unsigned int)))
{
return "integerOrBlackboardType";
}
else if(type_info == typeid(double))
{
return "decimalOrBlackboardType";
}
else if(type_info == typeid(bool))
{
return "booleanOrBlackboardType";
}
else if(type_info == typeid(std::string))
{
return "stringOrBlackboardType";
}
return std::string();
}
} // namespace
namespace BT
{
using namespace tinyxml2;
auto StrEqual = [](const char* str1, const char* str2) -> bool {
return strcmp(str1, str2) == 0;
};
struct SubtreeModel
{
std::unordered_map<std::string, BT::PortInfo> ports;
};
struct XMLParser::PImpl
{
TreeNode::Ptr createNodeFromXML(const XMLElement* element,
const Blackboard::Ptr& blackboard,
const TreeNode::Ptr& node_parent,
const std::string& prefix_path, Tree& output_tree);
void recursivelyCreateSubtree(const std::string& tree_ID, const std::string& tree_path,
const std::string& prefix_path, Tree& output_tree,
Blackboard::Ptr blackboard,
const TreeNode::Ptr& root_node);
void getPortsRecursively(const XMLElement* element,
std::vector<std::string>& output_ports);
void loadDocImpl(XMLDocument* doc, bool add_includes);
std::list<std::unique_ptr<XMLDocument> > opened_documents;
std::map<std::string, const XMLElement*> tree_roots;
const BehaviorTreeFactory& factory;
std::filesystem::path current_path;
std::map<std::string, SubtreeModel> subtree_models;
int suffix_count;
explicit PImpl(const BehaviorTreeFactory& fact)
: factory(fact), current_path(std::filesystem::current_path()), suffix_count(0)
{}
void clear()
{
suffix_count = 0;
current_path = std::filesystem::current_path();
opened_documents.clear();
tree_roots.clear();
}
private:
void loadSubtreeModel(const XMLElement* xml_root);
};
#if defined(__linux) || defined(__linux__)
#pragma GCC diagnostic pop
#endif
XMLParser::XMLParser(const BehaviorTreeFactory& factory) : _p(new PImpl(factory))
{}
XMLParser::XMLParser(XMLParser&& other) noexcept
{
this->_p = std::move(other._p);
}
XMLParser& XMLParser::operator=(XMLParser&& other) noexcept
{
this->_p = std::move(other._p);
return *this;
}
XMLParser::~XMLParser()
{}
void XMLParser::loadFromFile(const std::filesystem::path& filepath, bool add_includes)
{
_p->opened_documents.emplace_back(new XMLDocument());
XMLDocument* doc = _p->opened_documents.back().get();
doc->LoadFile(filepath.string().c_str());
_p->current_path = std::filesystem::absolute(filepath.parent_path());
_p->loadDocImpl(doc, add_includes);
}
void XMLParser::loadFromText(const std::string& xml_text, bool add_includes)
{
_p->opened_documents.emplace_back(new XMLDocument());
XMLDocument* doc = _p->opened_documents.back().get();
doc->Parse(xml_text.c_str(), xml_text.size());
_p->loadDocImpl(doc, add_includes);
}
std::vector<std::string> XMLParser::registeredBehaviorTrees() const
{
std::vector<std::string> out;
for(const auto& it : _p->tree_roots)
{
out.push_back(it.first);
}
return out;
}
void BT::XMLParser::PImpl::loadSubtreeModel(const XMLElement* xml_root)
{
for(auto models_node = xml_root->FirstChildElement("TreeNodesModel");
models_node != nullptr; models_node = models_node->NextSiblingElement("TreeNodesMo"
"del"))
{
for(auto sub_node = models_node->FirstChildElement("SubTree"); sub_node != nullptr;
sub_node = sub_node->NextSiblingElement("SubTree"))
{
auto subtree_id = sub_node->Attribute("ID");
auto& subtree_model = subtree_models[subtree_id];
std::pair<const char*, BT::PortDirection> port_types[3] = {
{ "input_port", BT::PortDirection::INPUT },
{ "output_port", BT::PortDirection::OUTPUT },
{ "inout_port", BT::PortDirection::INOUT }
};
for(const auto& [name, direction] : port_types)
{
for(auto port_node = sub_node->FirstChildElement(name); port_node != nullptr;
port_node = port_node->NextSiblingElement(name))
{
BT::PortInfo port(direction);
auto name = port_node->Attribute("name");
if(!name)
{
throw RuntimeError("Missing attribute [name] in port (SubTree model)");
}
if(auto default_value = port_node->Attribute("default"))
{
port.setDefaultValue(default_value);
}
if(auto description = port_node->Attribute("description"))
{
port.setDescription(description);
}
subtree_model.ports[name] = std::move(port);
}
}
}
}
}
void XMLParser::PImpl::loadDocImpl(XMLDocument* doc, bool add_includes)
{
if(doc->Error())
{
char buffer[512];
snprintf(buffer, sizeof buffer, "Error parsing the XML: %s", doc->ErrorStr());
throw RuntimeError(buffer);
}
const XMLElement* xml_root = doc->RootElement();
auto format = xml_root->Attribute("BTCPP_format");
if(!format)
{
std::cout << "Warnings: The first tag of the XML (<root>) should contain the "
"attribute [BTCPP_format=\"4\"]\n"
<< "Please check if your XML is compatible with version 4.x of BT.CPP"
<< std::endl;
}
// recursively include other files
for(auto incl_node = xml_root->FirstChildElement("include"); incl_node != nullptr;
incl_node = incl_node->NextSiblingElement("include"))
{
if(!add_includes)
{
break;
}
std::filesystem::path file_path(incl_node->Attribute("path"));
const char* ros_pkg_relative_path = incl_node->Attribute("ros_pkg");
if(ros_pkg_relative_path)
{
if(file_path.is_absolute())
{
std::cout << "WARNING: <include path=\"...\"> contains an absolute path.\n"
<< "Attribute [ros_pkg] will be ignored." << std::endl;
}
else
{
std::string ros_pkg_path;
#ifdef USING_ROS
ros_pkg_path = ros::package::getPath(ros_pkg_relative_path);
#elif defined USING_ROS2
ros_pkg_path =
ament_index_cpp::get_package_share_directory(ros_pkg_relative_path);
#else
throw RuntimeError("Using attribute [ros_pkg] in <include>, but this library was "
"compiled without ROS support. Recompile the BehaviorTree.CPP "
"using catkin");
#endif
file_path = std::filesystem::path(ros_pkg_path) / file_path;
}
}
if(!file_path.is_absolute())
{
file_path = current_path / file_path;
}
opened_documents.emplace_back(new XMLDocument());
XMLDocument* next_doc = opened_documents.back().get();
// change current path to the included file for handling additional relative paths
const auto previous_path = current_path;
current_path = std::filesystem::absolute(file_path.parent_path());
next_doc->LoadFile(file_path.string().c_str());
loadDocImpl(next_doc, add_includes);
// reset current path to the previous value
current_path = previous_path;
}
// Collect the names of all nodes registered with the behavior tree factory
std::unordered_map<std::string, BT::NodeType> registered_nodes;
for(const auto& it : factory.manifests())
{
registered_nodes.insert({ it.first, it.second.type });
}
XMLPrinter printer;
doc->Print(&printer);
auto xml_text = std::string(printer.CStr(), size_t(printer.CStrSize()));
// Verify the validity of the XML before adding any behavior trees to the parser's list of registered trees
VerifyXML(xml_text, registered_nodes);
loadSubtreeModel(xml_root);
// Register each BehaviorTree within the XML
for(auto bt_node = xml_root->FirstChildElement("BehaviorTree"); bt_node != nullptr;
bt_node = bt_node->NextSiblingElement("BehaviorTree"))
{
std::string tree_name;
if(bt_node->Attribute("ID"))
{
tree_name = bt_node->Attribute("ID");
}
else
{
tree_name = "BehaviorTree_" + std::to_string(suffix_count++);
}
tree_roots[tree_name] = bt_node;
}
}
void VerifyXML(const std::string& xml_text,
const std::unordered_map<std::string, BT::NodeType>& registered_nodes)
{
XMLDocument doc;
auto xml_error = doc.Parse(xml_text.c_str(), xml_text.size());
if(xml_error)
{
char buffer[512];
snprintf(buffer, sizeof buffer, "Error parsing the XML: %s", doc.ErrorName());
throw RuntimeError(buffer);
}
//-------- Helper functions (lambdas) -----------------
auto ThrowError = [&](int line_num, const std::string& text) {
char buffer[512];
snprintf(buffer, sizeof buffer, "Error at line %d: -> %s", line_num, text.c_str());
throw RuntimeError(buffer);
};
auto ChildrenCount = [](const XMLElement* parent_node) {
int count = 0;
for(auto node = parent_node->FirstChildElement(); node != nullptr;
node = node->NextSiblingElement())
{
count++;
}
return count;
};
//-----------------------------
const XMLElement* xml_root = doc.RootElement();
if(!xml_root || !StrEqual(xml_root->Name(), "root"))
{
throw RuntimeError("The XML must have a root node called <root>");
}
//-------------------------------------------------
auto models_root = xml_root->FirstChildElement("TreeNodesModel");
auto meta_sibling =
models_root ? models_root->NextSiblingElement("TreeNodesModel") : nullptr;
if(meta_sibling)
{
ThrowError(meta_sibling->GetLineNum(), " Only a single node <TreeNodesModel> is "
"supported");
}
if(models_root)
{
// not having a MetaModel is not an error. But consider that the
// Graphical editor needs it.
for(auto node = xml_root->FirstChildElement(); node != nullptr;
node = node->NextSiblingElement())
{
const std::string name = node->Name();
if(name == "Action" || name == "Decorator" || name == "SubTree" ||
name == "Condition" || name == "Control")
{
const char* ID = node->Attribute("ID");
if(!ID)
{
ThrowError(node->GetLineNum(), "Error at line %d: -> The attribute "
"[ID] is mandatory");
}
}
}
}
//-------------------------------------------------
int behavior_tree_count = 0;
for(auto child = xml_root->FirstChildElement(); child != nullptr;
child = child->NextSiblingElement())
{
behavior_tree_count++;
}
// function to be called recursively
std::function<void(const XMLElement*)> recursiveStep;
recursiveStep = [&](const XMLElement* node) {
const int children_count = ChildrenCount(node);
const std::string name = node->Name();
const std::string ID = node->Attribute("ID") ? node->Attribute("ID") : "";
const int line_number = node->GetLineNum();
if(name == "Decorator")
{
if(children_count != 1)
{
ThrowError(line_number, "The tag <Decorator> must have exactly 1 "
"child");
}
if(ID.empty())
{
ThrowError(line_number, "The tag <Decorator> must have the "
"attribute [ID]");
}
}
else if(name == "Action")
{
if(children_count != 0)
{
ThrowError(line_number, "The tag <Action> must not have any "
"child");
}
if(ID.empty())
{
ThrowError(line_number, "The tag <Action> must have the "
"attribute [ID]");
}
}
else if(name == "Condition")
{
if(children_count != 0)
{
ThrowError(line_number, "The tag <Condition> must not have any "
"child");
}
if(ID.empty())
{
ThrowError(line_number, "The tag <Condition> must have the "
"attribute [ID]");
}
}
else if(name == "Control")
{
if(children_count == 0)
{
ThrowError(line_number, "The tag <Control> must have at least 1 "
"child");
}
if(ID.empty())
{
ThrowError(line_number, "The tag <Control> must have the "
"attribute [ID]");
}
}
else if(name == "SubTree")
{
if(children_count != 0)
{
ThrowError(line_number, "<SubTree> should not have any child");
}
if(ID.empty())
{
ThrowError(line_number, "The tag <SubTree> must have the "
"attribute [ID]");
}
if(registered_nodes.count(ID) != 0)
{
ThrowError(line_number, "The attribute [ID] of tag <SubTree> must "
"not use the name of a registered Node");
}
}
else if(name == "BehaviorTree")
{
if(ID.empty() && behavior_tree_count > 1)
{
ThrowError(line_number, "The tag <BehaviorTree> must have the "
"attribute [ID]");
}
if(children_count != 1)
{
ThrowError(line_number, "The tag <BehaviorTree> must have exactly 1 "
"child");
}
if(registered_nodes.count(ID) != 0)
{
ThrowError(line_number, "The attribute [ID] of tag <BehaviorTree> "
"must not use the name of a registered Node");
}
}
else
{
// search in the factory and the list of subtrees
const auto search = registered_nodes.find(name);
bool found = (search != registered_nodes.end());
if(!found)
{
ThrowError(line_number, std::string("Node not recognized: ") + name);
}
if(search->second == NodeType::DECORATOR)
{
if(children_count != 1)
{
ThrowError(line_number,
std::string("The node <") + name + "> must have exactly 1 child");
}
}
else if(search->second == NodeType::CONTROL)
{
if(children_count == 0)
{
ThrowError(line_number,
std::string("The node <") + name + "> must have 1 or more children");
}
}
}
//recursion
for(auto child = node->FirstChildElement(); child != nullptr;
child = child->NextSiblingElement())
{
recursiveStep(child);
}
};
for(auto bt_root = xml_root->FirstChildElement("BehaviorTree"); bt_root != nullptr;
bt_root = bt_root->NextSiblingElement("BehaviorTree"))
{
recursiveStep(bt_root);
}
}
Tree XMLParser::instantiateTree(const Blackboard::Ptr& root_blackboard,
std::string main_tree_ID)
{
Tree output_tree;
// use the main_tree_to_execute argument if it was provided by the user
// or the one in the FIRST document opened
if(main_tree_ID.empty())
{
XMLElement* first_xml_root = _p->opened_documents.front()->RootElement();
if(auto main_tree_attribute = first_xml_root->Attribute("main_tree_to_execute"))
{
main_tree_ID = main_tree_attribute;
}
else if(_p->tree_roots.size() == 1)
{
// special case: there is only one registered BT.
main_tree_ID = _p->tree_roots.begin()->first;
}
else
{
throw RuntimeError("[main_tree_to_execute] was not specified correctly");
}
}
//--------------------------------------
if(!root_blackboard)
{
throw RuntimeError("XMLParser::instantiateTree needs a non-empty "
"root_blackboard");
}
_p->recursivelyCreateSubtree(main_tree_ID, {}, {}, output_tree, root_blackboard,
TreeNode::Ptr());
output_tree.initialize();
return output_tree;
}
void XMLParser::clearInternalState()
{
_p->clear();
}
TreeNode::Ptr XMLParser::PImpl::createNodeFromXML(const XMLElement* element,
const Blackboard::Ptr& blackboard,
const TreeNode::Ptr& node_parent,
const std::string& prefix_path,
Tree& output_tree)
{
const auto element_name = element->Name();
const auto element_ID = element->Attribute("ID");
auto node_type = convertFromString<NodeType>(element_name);
// name used by the factory
std::string type_ID;
if(node_type == NodeType::UNDEFINED)
{
// This is the case of nodes like <MyCustomAction>
// check if the factory has this name
if(factory.builders().count(element_name) == 0)
{
throw RuntimeError(element_name, " is not a registered node");
}
type_ID = element_name;
if(element_ID)
{
throw RuntimeError("Attribute [ID] is not allowed in <", type_ID, ">");
}
}
else
{
// in this case, it is mandatory to have a field "ID"
if(!element_ID)
{
throw RuntimeError("Attribute [ID] is mandatory in <", type_ID, ">");
}
type_ID = element_ID;
}
// By default, the instance name is equal to ID, unless the
// attribute [name] is present.
const char* attr_name = element->Attribute("name");
const std::string instance_name = (attr_name != nullptr) ? attr_name : type_ID;
const TreeNodeManifest* manifest = nullptr;
auto manifest_it = factory.manifests().find(type_ID);
if(manifest_it != factory.manifests().end())
{
manifest = &manifest_it->second;
}
PortsRemapping port_remap;
for(const XMLAttribute* att = element->FirstAttribute(); att; att = att->Next())
{
if(IsAllowedPortName(att->Name()))
{
const std::string port_name = att->Name();
const std::string port_value = att->Value();
if(manifest)
{
auto port_model_it = manifest->ports.find(port_name);
if(port_model_it == manifest->ports.end())
{
throw RuntimeError(StrCat("a port with name [", port_name,
"] is found in the XML, but not in the "
"providedPorts()"));
}
else
{
const auto& port_model = port_model_it->second;
bool is_blacbkboard = port_value.size() >= 3 && port_value.front() == '{' &&
port_value.back() == '}';
// let's test already if conversion is possible
if(!is_blacbkboard && port_model.converter() && port_model.isStronglyTyped())
{
// This may throw
try
{
port_model.converter()(port_value);
}
catch(std::exception& ex)
{
auto msg = StrCat("The port with name \"", port_name, "\" and value \"",
port_value, "\" can not be converted to ",
port_model.typeName());
throw LogicError(msg);
}
}
}
}
port_remap[port_name] = port_value;
}
}
NodeConfig config;
config.blackboard = blackboard;
config.path = prefix_path + instance_name;
config.uid = output_tree.getUID();
config.manifest = manifest;
if(type_ID == instance_name)
{
config.path += std::string("::") + std::to_string(config.uid);
}
auto AddCondition = [&](auto& conditions, const char* attr_name, auto ID) {
if(auto script = element->Attribute(attr_name))
{
conditions.insert({ ID, std::string(script) });
}
};
for(int i = 0; i < int(PreCond::COUNT_); i++)
{
auto pre = static_cast<PreCond>(i);
AddCondition(config.pre_conditions, toStr(pre).c_str(), pre);
}
for(int i = 0; i < int(PostCond::COUNT_); i++)
{
auto post = static_cast<PostCond>(i);
AddCondition(config.post_conditions, toStr(post).c_str(), post);
}
//---------------------------------------------
TreeNode::Ptr new_node;
if(node_type == NodeType::SUBTREE)
{
config.input_ports = port_remap;
new_node =
factory.instantiateTreeNode(instance_name, toStr(NodeType::SUBTREE), config);
auto subtree_node = dynamic_cast<SubTreeNode*>(new_node.get());
subtree_node->setSubtreeID(type_ID);
}
else
{
if(!manifest)
{
auto msg = StrCat("Missing manifest for element_ID: ", element_ID,
". It shouldn't happen. Please report this issue.");
throw RuntimeError(msg);
}
//Check that name in remapping can be found in the manifest
for(const auto& [name_in_subtree, _] : port_remap)
{
if(manifest->ports.count(name_in_subtree) == 0)
{
throw RuntimeError("Possible typo? In the XML, you tried to remap port \"",
name_in_subtree, "\" in node [", config.path, "(type ",
type_ID,
")], but the manifest/model of this node does not contain a "
"port "
"with this name.");
}
}
// Initialize the ports in the BB to set the type
for(const auto& [port_name, port_info] : manifest->ports)
{
auto remap_it = port_remap.find(port_name);
if(remap_it == port_remap.end())
{
continue;
}
StringView remapped_port = remap_it->second;
if(auto param_res = TreeNode::getRemappedKey(port_name, remapped_port))
{
// port_key will contain the key to find the entry in the blackboard
const auto port_key = static_cast<std::string>(param_res.value());
// if the entry already exists, check that the type is the same
if(auto prev_info = blackboard->entryInfo(port_key))
{
// Check consistency of types.
bool const port_type_mismatch =
(prev_info->isStronglyTyped() && port_info.isStronglyTyped() &&
prev_info->type() != port_info.type());
// special case related to convertFromString
bool const string_input = (prev_info->type() == typeid(std::string));
if(port_type_mismatch && !string_input)
{
blackboard->debugMessage();
throw RuntimeError("The creation of the tree failed because the port [",
port_key, "] was initially created with type [",
demangle(prev_info->type()), "] and, later type [",
demangle(port_info.type()), "] was used somewhere else.");
}
}
else
{
// not found, insert for the first time.
blackboard->createEntry(port_key, port_info);
}
}
}
// Set the port direction in config
for(const auto& remap_it : port_remap)
{
const auto& port_name = remap_it.first;
auto port_it = manifest->ports.find(port_name);
if(port_it != manifest->ports.end())
{
auto direction = port_it->second.direction();
if(direction != PortDirection::OUTPUT)
{
config.input_ports.insert(remap_it);
}
if(direction != PortDirection::INPUT)
{
config.output_ports.insert(remap_it);
}
}
}
// use default value if available for empty ports. Only inputs
for(const auto& port_it : manifest->ports)
{
const std::string& port_name = port_it.first;
const PortInfo& port_info = port_it.second;
const auto direction = port_info.direction();
const auto& default_string = port_info.defaultValueString();
if(!default_string.empty())
{
if(direction != PortDirection::OUTPUT && config.input_ports.count(port_name) == 0)
{
config.input_ports.insert({ port_name, default_string });
}
if(direction != PortDirection::INPUT &&
config.output_ports.count(port_name) == 0 &&
TreeNode::isBlackboardPointer(default_string))
{
config.output_ports.insert({ port_name, default_string });
}
}
}
new_node = factory.instantiateTreeNode(instance_name, type_ID, config);
}
// add the pointer of this node to the parent
if(node_parent != nullptr)
{
if(auto control_parent = dynamic_cast<ControlNode*>(node_parent.get()))
{
control_parent->addChild(new_node.get());
}
else if(auto decorator_parent = dynamic_cast<DecoratorNode*>(node_parent.get()))
{
decorator_parent->setChild(new_node.get());
}
}
return new_node;
}
void BT::XMLParser::PImpl::recursivelyCreateSubtree(const std::string& tree_ID,
const std::string& tree_path,
const std::string& prefix_path,
Tree& output_tree,
Blackboard::Ptr blackboard,
const TreeNode::Ptr& root_node)
{
std::function<void(const TreeNode::Ptr&, Tree::Subtree::Ptr, std::string,
const XMLElement*)>
recursiveStep;
recursiveStep = [&](TreeNode::Ptr parent_node, Tree::Subtree::Ptr subtree,
std::string prefix, const XMLElement* element) {
// create the node
auto node = createNodeFromXML(element, blackboard, parent_node, prefix, output_tree);
subtree->nodes.push_back(node);
// common case: iterate through all children
if(node->type() != NodeType::SUBTREE)
{
for(auto child_element = element->FirstChildElement(); child_element;
child_element = child_element->NextSiblingElement())
{
recursiveStep(node, subtree, prefix, child_element);
}
}
else // special case: SubTreeNode
{
auto new_bb = Blackboard::create(blackboard);
const std::string subtree_ID = element->Attribute("ID");
std::unordered_map<std::string, std::string> subtree_remapping;
bool do_autoremap = false;
for(auto attr = element->FirstAttribute(); attr != nullptr; attr = attr->Next())
{
std::string attr_name = attr->Name();
std::string attr_value = attr->Value();
if(attr_value == "{=}")
{
attr_value = StrCat("{", attr_name, "}");
}
if(attr_name == "_autoremap")
{
do_autoremap = convertFromString<bool>(attr_value);
new_bb->enableAutoRemapping(do_autoremap);
continue;
}
if(!IsAllowedPortName(attr->Name()))
{
continue;
}
subtree_remapping.insert({ attr_name, attr_value });
}
// check if this subtree has a model. If it does,
// we want to check if all the mandatory ports were remapped and
// add default ones, if necessary
auto subtree_model_it = subtree_models.find(subtree_ID);
if(subtree_model_it != subtree_models.end())
{
const auto& subtree_model_ports = subtree_model_it->second.ports;
// check if:
// - remapping contains mondatory ports
// - if any of these has default value
for(const auto& [port_name, port_info] : subtree_model_ports)
{
auto it = subtree_remapping.find(port_name);
// don't override existing remapping
if(it == subtree_remapping.end() && !do_autoremap)
{
// remapping is not explicitly defined in the XML: use the model
if(port_info.defaultValueString().empty())
{
auto msg = StrCat("In the <TreeNodesModel> the <Subtree ID=\"", subtree_ID,
"\"> is defining a mandatory port called [", port_name,
"], but you are not remapping it");
throw RuntimeError(msg);
}
else
{
subtree_remapping.insert({ port_name, port_info.defaultValueString() });
}
}
}
}
for(const auto& [attr_name, attr_value] : subtree_remapping)
{
if(TreeNode::isBlackboardPointer(attr_value))
{
// do remapping
StringView port_name = TreeNode::stripBlackboardPointer(attr_value);
new_bb->addSubtreeRemapping(attr_name, port_name);
}
else
{
// constant string: just set that constant value into the BB
// IMPORTANT: this must not be autoremapped!!!
new_bb->enableAutoRemapping(false);
new_bb->set(attr_name, static_cast<std::string>(attr_value));
new_bb->enableAutoRemapping(do_autoremap);
}
}
std::string subtree_path = subtree->instance_name;
if(!subtree_path.empty())
{
subtree_path += "/";
}
if(auto name = element->Attribute("name"))
{
subtree_path += name;
}
else
{
subtree_path += subtree_ID + "::" + std::to_string(node->UID());
}
recursivelyCreateSubtree(subtree_ID,
subtree_path, // name
subtree_path + "/", //prefix
output_tree, new_bb, node);
}
};
auto it = tree_roots.find(tree_ID);
if(it == tree_roots.end())
{
throw std::runtime_error(std::string("Can't find a tree with name: ") + tree_ID);
}
auto root_element = it->second->FirstChildElement();
//-------- start recursion -----------
// Append a new subtree to the list
auto new_tree = std::make_shared<Tree::Subtree>();
new_tree->blackboard = blackboard;
new_tree->instance_name = tree_path;
new_tree->tree_ID = tree_ID;
output_tree.subtrees.push_back(new_tree);