-
Notifications
You must be signed in to change notification settings - Fork 98
/
parser.cc
3014 lines (2702 loc) · 94.3 KB
/
parser.cc
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 2012 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <cstdlib>
#include <map>
#include <set>
#include <string>
#include <unordered_set>
#include <gz/math/SemanticVersion.hh>
#include "sdf/Console.hh"
#include "sdf/Filesystem.hh"
#include "sdf/Frame.hh"
#include "sdf/Joint.hh"
#include "sdf/JointAxis.hh"
#include "sdf/Link.hh"
#include "sdf/Model.hh"
#include "sdf/Param.hh"
#include "sdf/Root.hh"
#include "sdf/SDFImpl.hh"
#include "sdf/World.hh"
#include "sdf/parser.hh"
#include "sdf/ParserConfig.hh"
#include "sdf/sdf_config.h"
#include "Converter.hh"
#include "FrameSemantics.hh"
#include "ParamPassing.hh"
#include "ScopedGraph.hh"
#include "Utils.hh"
#include "parser_private.hh"
#include "parser_urdf.hh"
namespace sdf
{
inline namespace SDF_VERSION_NAMESPACE {
namespace
{
//////////////////////////////////////////////////
/// Holds information about the location of a particular point in an SDFormat
/// file
struct SourceLocation
{
/// \brief Xml path where the error was raised.
public: std::optional<std::string> xmlPath = std::nullopt;
/// \brief File path where the error was raised.
public: std::optional<std::string> filePath = std::nullopt;
/// \brief Line number in the file path where the error was raised.
public: std::optional<int> lineNumber = std::nullopt;
/// \brief Sets the source location on an sdf::Error object
/// \param[in,out] _error sdf::Error object on which the source location is to
/// be set.
public: void SetSourceLocationOnError(sdf::Error &_error) const
{
if (this->xmlPath.has_value())
{
_error.SetXmlPath(*this->xmlPath);
}
if (this->filePath.has_value())
{
_error.SetFilePath(*this->filePath);
}
if (this->lineNumber.has_value())
{
_error.SetLineNumber(*this->lineNumber);
}
}
};
}
//////////////////////////////////////////////////
/// \brief Internal helper for readFile, which populates the SDF values
/// from a file
///
/// This populates the given sdf pointer from a file. If the file is a URDF
/// file it is converted to SDF first. Conversion to the latest
/// SDF version is controlled by a function parameter.
/// \param[in] _filename Name of the SDF file
/// \param[in] _convert Convert to the latest version if true.
/// \param[in] _config Custom parser configuration
/// \param[out] _sdf Pointer to an SDF object.
/// \param[out] _errors Parsing errors will be appended to this variable.
/// \return True if successful.
bool readFileInternal(
const std::string &_filename,
const bool _convert,
const ParserConfig &_config,
SDFPtr _sdf,
Errors &_errors);
/// \brief Internal helper for readString, which populates the SDF values
/// from a string
///
/// This populates the sdf pointer from a string. If the string is from a URDF
/// file it is converted to SDF first. Conversion to the latest
/// SDF version is controlled by a function parameter.
/// \param[in] _xmlString XML string to be parsed.
/// \param[in] _convert Convert to the latest version if true.
/// \param[in] _config Custom parser configuration
/// \param[out] _sdf Pointer to an SDF object.
/// \param[out] _errors Parsing errors will be appended to this variable.
/// \return True if successful.
bool readStringInternal(
const std::string &_xmlString,
const bool _convert,
const ParserConfig &_config,
SDFPtr _sdf,
Errors &_errors);
//////////////////////////////////////////////////
/// \brief Internal helper for creating XMLDocuments
///
/// This creates an XMLDocument with whitespace collapse
/// on, which is not default behavior in tinyxml2.
/// This function is to consolidate locations it is used.
///
/// There is a performance impact associated with collapsing whitespace.
///
/// For more information on the behavior and performance implications,
/// consult the TinyXML2 documentation: https://leethomason.github.io/tinyxml2/
inline auto makeSdfDoc()
{
return tinyxml2::XMLDocument(true, tinyxml2::COLLAPSE_WHITESPACE);
}
//////////////////////////////////////////////////
static bool isSdfFile(const std::string &_fileName)
{
std::size_t periodIndex = _fileName.rfind('.');
if (periodIndex != std::string::npos)
{
const std::string ext = _fileName.substr(periodIndex);
return ext == ".sdf" || ext == ".world";
}
return false;
}
//////////////////////////////////////////////////
template <typename TPtr>
static inline bool _initFile(const std::string &_filename,
const ParserConfig &_config,
TPtr _sdf,
sdf::Errors &_errors)
{
auto xmlDoc = makeSdfDoc();
if (tinyxml2::XML_SUCCESS != xmlDoc.LoadFile(_filename.c_str()))
{
_errors.emplace_back(sdf::Error(ErrorCode::FILE_READ,
"Unable to load file[" + _filename +
xmlDoc.ErrorStr() + "]"));
return false;
}
return initDoc(_errors, _sdf, &xmlDoc, _config);
}
//////////////////////////////////////////////////
/// Helper function to insert included elements into a parent element.
/// \param[in] _includeSDF The SDFPtr corresponding to the included element
/// \param[in] _sourceLoc The location of the include element in the file
/// \param[in] _merge Whether the included element should be merged into the
/// parent element. If true, children elements of _includeSDF will be copied to
/// _parent without introducing a new model scope. N.B, this only works for
/// included nested models.
/// \param[in,out] _parent The parent element that contains the <include> tag.
/// The contents of _includeSDF will be added to this.
/// \param[out] _errors Captures errors encountered during parsing.
static void insertIncludedElement(sdf::SDFPtr _includeSDF,
const SourceLocation &_sourceLoc, bool _merge,
sdf::ElementPtr _parent,
const ParserConfig &_config,
sdf::Errors &_errors)
{
Error invalidFileError(ErrorCode::FILE_READ,
"Included model is invalid. Skipping model.");
_sourceLoc.SetSourceLocationOnError(invalidFileError);
sdf::ElementPtr rootElem = _includeSDF->Root();
if (nullptr == rootElem)
{
_errors.push_back(invalidFileError);
return;
}
sdf::ElementPtr firstElem = rootElem->GetFirstElement();
if (nullptr == firstElem)
{
_errors.push_back(invalidFileError);
return;
}
if (!_merge)
{
_parent->InsertElement(firstElem, true);
return;
}
else if (firstElem->GetName() != "model")
{
Error unsupportedError(
ErrorCode::MERGE_INCLUDE_UNSUPPORTED,
"Merge-include is only supported for included models");
_sourceLoc.SetSourceLocationOnError(unsupportedError);
_errors.push_back(unsupportedError);
return;
}
else if (_parent->GetName() != "model" && _parent->GetName() != "world")
{
Error unsupportedError(
ErrorCode::MERGE_INCLUDE_UNSUPPORTED,
"Merge-include does not support parent element of type " +
_parent->GetName());
_sourceLoc.SetSourceLocationOnError(unsupportedError);
_errors.push_back(unsupportedError);
return;
}
// Validate included model's frame semantics
if (!_config.CustomModelParsers().empty())
{
// Since we have custom parsers, we can't create a throwaway sdf::Root
// object to validate the merge-included model. This is because calling
// `sdf::Root::Load` here would call the custom parsers if this model
// contains a nested model that is custom parsed. But the custom parsers
// will be called again later when we construct the final `sdf::Root`
// object. We also can't do the merge here since we'd be doing so without
// validating the model.
// We could forego validating the model and just merge all its children to
// the parent element, but we wouldn't be able to handle placement frames
// since that requires building a frame graph for the model.
// So instead we add a hidden flag here to tell `sdf::Model` or `sdf::World`
// that this model is meant to be merged.
firstElem->AddAttribute("__merge__", "bool", "false", false,
"Indicates whether this is a merge included model");
firstElem->GetAttribute("__merge__")->Set<bool>(true);
_parent->InsertElement(firstElem, true);
return;
}
// We create a throwaway sdf::Root object in order to validate the
// included entity.
sdf::Root includedRoot;
sdf::Errors includeDOMerrors = includedRoot.Load(_includeSDF, _config);
_errors.insert(_errors.end(), includeDOMerrors.begin(),
includeDOMerrors.end());
const sdf::Model *model = includedRoot.Model();
if (nullptr == model)
{
Error unsupportedError(ErrorCode::MERGE_INCLUDE_UNSUPPORTED,
"Included model is invalid. Skipping model.");
_sourceLoc.SetSourceLocationOnError(unsupportedError);
_errors.push_back(unsupportedError);
return;
}
ElementPtr proxyModelFrame = _parent->AddElement("frame");
const std::string proxyModelFrameName =
computeMergedModelProxyFrameName(model->Name());
proxyModelFrame->GetAttribute("name")->Set(proxyModelFrameName);
// Determine the canonical link so the proxy frame can be attached to it
const std::string canonicalLinkName =
model->CanonicalLinkAndRelativeName().second;
proxyModelFrame->GetAttribute("attached_to")->Set(canonicalLinkName);
auto modelPose = model->RawPose();
if (!model->PlacementFrameName().empty())
{
// M - model frame (__model__)
// R - The `relative_to` frame of the placement frame's //pose element.
// See resolveModelPoseWithPlacementFrame in FrameSemantics.cc for
// notation and documentation
gz::math::Pose3d X_RM = model->RawPose();
sdf::Errors resolveErrors = model->SemanticPose().Resolve(X_RM);
_errors.insert(_errors.end(), resolveErrors.begin(), resolveErrors.end());
modelPose = X_RM;
}
ElementPtr proxyModelFramePose = proxyModelFrame->AddElement("pose");
proxyModelFramePose->Set(modelPose);
// Set the proxyModelFrame's //pose/@relative_to to the frame used in
// //include/pose/@relative_to.
std::string modelPoseRelativeTo = model->PoseRelativeTo();
// If empty, use "__model__" or "world", since leaving it empty would make it
// relative_to the canonical link frame specified in //frame/@attached_to.
if (modelPoseRelativeTo.empty())
{
if (_parent->GetName() == "model")
{
modelPoseRelativeTo = "__model__";
}
else
{
modelPoseRelativeTo = "world";
}
}
proxyModelFramePose->GetAttribute("relative_to")->Set(modelPoseRelativeTo);
auto setAttributeToProxyFrame =
[&proxyModelFrameName](const std::string &_attr, sdf::ElementPtr _elem,
bool updateIfEmpty)
{
if (nullptr == _elem)
return;
auto attribute = _elem->GetAttribute(_attr);
if (attribute->GetAsString() == "__model__" ||
(updateIfEmpty && attribute->GetAsString().empty()))
{
attribute->Set(proxyModelFrameName);
}
};
sdf::ElementPtr nextElem = nullptr;
for (auto elem = firstElem->GetFirstElement(); elem; elem = nextElem)
{
// We need to fetch the next element here before we call elem->SetParent
// later in this block.
nextElem = elem->GetNextElement();
if ((elem->GetName() == "link") || (elem->GetName() == "model"))
{
// Add a pose element even if the element doesn't originally have one
setAttributeToProxyFrame("relative_to", elem->GetElement("pose"), true);
}
else if (elem->GetName() == "frame")
{
// If //frame/@attached_to is empty, explicitly set it to the name
// of the nested model frame.
setAttributeToProxyFrame("attached_to", elem, true);
setAttributeToProxyFrame("relative_to", elem->GetElementImpl("pose"),
false);
}
else if (elem->GetName() == "joint")
{
setAttributeToProxyFrame("relative_to", elem->GetElementImpl("pose"),
false);
auto parent = elem->FindElement("parent");
if (nullptr != parent && parent->Get<std::string>() == "__model__")
{
parent->Set(proxyModelFrameName);
}
auto child = elem->FindElement("child");
if (nullptr != child && child->Get<std::string>() == "__model__")
{
child->Set(proxyModelFrameName);
}
// cppcheck-suppress syntaxError
// cppcheck-suppress unmatchedSuppression
if (auto axis = elem->GetElementImpl("axis"); axis)
{
setAttributeToProxyFrame("expressed_in", axis->GetElementImpl("xyz"),
false);
}
if (auto axis2 = elem->GetElementImpl("axis2"); axis2)
{
setAttributeToProxyFrame("expressed_in", axis2->GetElementImpl("xyz"),
false);
}
}
// Only named and custom elements are copied. Other elements, such as
// <static>, <self_collide>, and <enable_wind> are ignored.
if ((elem->GetName() == "link") || (elem->GetName() == "model") ||
(elem->GetName() == "joint") || (elem->GetName() == "frame") ||
(elem->GetName() == "gripper") || (elem->GetName() == "plugin") ||
(elem->GetName().find(':') != std::string::npos))
{
if (_parent->GetName() == "world" &&
(elem->GetName() == "link" || elem->GetName() == "gripper"))
{
Error unsupportedError(
ErrorCode::MERGE_INCLUDE_UNSUPPORTED,
"Merge-include for <world> does not support element of type " +
elem->GetName() + " in included model");
_sourceLoc.SetSourceLocationOnError(unsupportedError);
_errors.push_back(unsupportedError);
continue;
}
_parent->InsertElement(elem, true);
}
}
}
//////////////////////////////////////////////////
bool init(SDFPtr _sdf)
{
return init(_sdf, ParserConfig::GlobalConfig());
}
//////////////////////////////////////////////////
bool init(SDFPtr _sdf, const ParserConfig &_config)
{
sdf::Errors errors;
bool result = init(errors, _sdf, _config);
sdf::throwOrPrintErrors(errors);
return result;
}
//////////////////////////////////////////////////
bool init(sdf::Errors &_errors, SDFPtr _sdf, const ParserConfig &_config)
{
std::string xmldata = SDF::EmbeddedSpec("root.sdf", false);
auto xmlDoc = makeSdfDoc();
xmlDoc.Parse(xmldata.c_str());
return initDoc(_errors, _sdf, &xmlDoc, _config);
}
//////////////////////////////////////////////////
bool initFile(const std::string &_filename, SDFPtr _sdf)
{
return initFile(_filename, ParserConfig::GlobalConfig(), _sdf);
}
//////////////////////////////////////////////////
bool initFile(const std::string &_filename, const ParserConfig &_config,
SDFPtr _sdf)
{
sdf::Errors errors;
bool result = initFile(_filename, _config, _sdf, errors);
sdf::throwOrPrintErrors(errors);
return result;
}
//////////////////////////////////////////////////
bool initFile(const std::string &_filename, const ParserConfig &_config,
SDFPtr _sdf, sdf::Errors &_errors)
{
std::string xmldata = SDF::EmbeddedSpec(_filename, true);
if (!xmldata.empty())
{
auto xmlDoc = makeSdfDoc();
xmlDoc.Parse(xmldata.c_str());
return initDoc(_errors, _sdf, &xmlDoc, _config);
}
return _initFile(sdf::findFile(_filename, true, false, _config), _config,
_sdf, _errors);
}
//////////////////////////////////////////////////
bool initFile(const std::string &_filename, ElementPtr _sdf)
{
return initFile(_filename, ParserConfig::GlobalConfig(), _sdf);
}
//////////////////////////////////////////////////
bool initFile(
const std::string &_filename, const ParserConfig &_config, ElementPtr _sdf)
{
sdf::Errors errors;
bool result = initFile(_filename, _config, _sdf, errors);
sdf::throwOrPrintErrors(errors);
return result;
}
//////////////////////////////////////////////////
bool initFile(const std::string &_filename, const ParserConfig &_config,
ElementPtr _sdf, sdf::Errors &_errors)
{
std::string xmldata = SDF::EmbeddedSpec(_filename, true);
if (!xmldata.empty())
{
auto xmlDoc = makeSdfDoc();
xmlDoc.Parse(xmldata.c_str());
return initDoc(_errors, _sdf, &xmlDoc, _config);
}
return _initFile(sdf::findFile(_filename, true, false, _config), _config,
_sdf, _errors);
}
//////////////////////////////////////////////////
bool initString(const std::string &_xmlString, const ParserConfig &_config,
SDFPtr _sdf)
{
sdf::Errors errors;
bool result = initString(_xmlString, _config, _sdf, errors);
sdf::throwOrPrintErrors(errors);
return result;
}
//////////////////////////////////////////////////
bool initString(const std::string &_xmlString, const ParserConfig &_config,
SDFPtr _sdf, sdf::Errors &_errors)
{
auto xmlDoc = makeSdfDoc();
if (xmlDoc.Parse(_xmlString.c_str()))
{
_errors.push_back({ErrorCode::PARSING_ERROR, "Failed to parse string"
" as XML: " + std::string(xmlDoc.ErrorStr())});
return false;
}
return initDoc(_errors, _sdf, &xmlDoc, _config);
}
//////////////////////////////////////////////////
bool initString(const std::string &_xmlString, SDFPtr _sdf)
{
sdf::Errors errors;
bool result = initString(_xmlString, ParserConfig::GlobalConfig(),
_sdf, errors);
sdf::throwOrPrintErrors(errors);
return result;
}
//////////////////////////////////////////////////
inline tinyxml2::XMLElement *_initDocGetElement(tinyxml2::XMLDocument *_xmlDoc,
sdf::Errors &_errors)
{
if (!_xmlDoc)
{
_errors.push_back({ErrorCode::PARSING_ERROR, "Could not parse the xml"});
return nullptr;
}
tinyxml2::XMLElement *element = _xmlDoc->FirstChildElement("element");
if (!element)
{
_errors.push_back({ErrorCode::ELEMENT_MISSING, "Could not find the "
"'element' element in the xml file"});
return nullptr;
}
return element;
}
//////////////////////////////////////////////////
bool initDoc(sdf::Errors &_errors,
SDFPtr _sdf,
tinyxml2::XMLDocument *_xmlDoc,
const ParserConfig &_config)
{
auto element = _initDocGetElement(_xmlDoc, _errors);
if (!element)
{
return false;
}
return initXml(_errors, _sdf->Root(), element, _config);
}
//////////////////////////////////////////////////
bool initDoc(sdf::Errors &_errors,
ElementPtr _sdf,
tinyxml2::XMLDocument *_xmlDoc,
const ParserConfig &_config)
{
auto element = _initDocGetElement(_xmlDoc, _errors);
if (!element)
{
return false;
}
return initXml(_errors, _sdf, element, _config);
}
//////////////////////////////////////////////////
bool initXml(sdf::Errors &_errors,
ElementPtr _sdf,
tinyxml2::XMLElement *_xml,
const ParserConfig &_config)
{
const char *refString = _xml->Attribute("ref");
if (refString)
{
_sdf->SetReferenceSDF(std::string(refString));
}
const char *nameString = _xml->Attribute("name");
if (!nameString)
{
_errors.push_back({ErrorCode::ATTRIBUTE_MISSING,
"Element is missing the name attribute"});
return false;
}
_sdf->SetName(std::string(nameString));
const char *requiredString = _xml->Attribute("required");
if (!requiredString)
{
_errors.push_back({ErrorCode::ATTRIBUTE_MISSING,
"Element is missing the required attribute"});
return false;
}
_sdf->SetRequired(requiredString);
const char *elemTypeString = _xml->Attribute("type");
if (elemTypeString)
{
bool required = std::string(requiredString) == "1" ? true : false;
const char *elemDefaultValue = _xml->Attribute("default");
std::string description;
tinyxml2::XMLElement *descChild = _xml->FirstChildElement("description");
if (descChild && descChild->GetText())
{
description = descChild->GetText();
}
std::string minValue;
const char *elemMinValue = _xml->Attribute("min");
if (nullptr != elemMinValue)
{
minValue = elemMinValue;
}
std::string maxValue;
const char *elemMaxValue = _xml->Attribute("max");
if (nullptr != elemMaxValue)
{
maxValue = elemMaxValue;
}
_sdf->AddValue(elemTypeString, elemDefaultValue, required, minValue,
maxValue, description);
}
// Get all attributes
for (tinyxml2::XMLElement *child = _xml->FirstChildElement("attribute");
child; child = child->NextSiblingElement("attribute"))
{
auto *descriptionChild = child->FirstChildElement("description");
const char *name = child->Attribute("name");
const char *type = child->Attribute("type");
const char *defaultValue = child->Attribute("default");
requiredString = child->Attribute("required");
if (!name)
{
_errors.push_back({ErrorCode::ATTRIBUTE_INVALID,
"Attribute is missing a name"});
return false;
}
if (!type)
{
_errors.push_back({ErrorCode::ATTRIBUTE_INVALID,
"Attribute is missing a type"});
return false;
}
if (!defaultValue)
{
_errors.push_back({ErrorCode::ATTRIBUTE_INVALID,
"Attribute[" + std::string(name)
+ "] is missing a default"});
return false;
}
if (!requiredString)
{
_errors.push_back({ErrorCode::ATTRIBUTE_INVALID,
"Attribute is missing a required string"});
return false;
}
std::string requiredStr = sdf::trim(requiredString);
bool required = requiredStr == "1" ? true : false;
std::string description;
if (descriptionChild && descriptionChild->GetText())
{
description = descriptionChild->GetText();
}
_sdf->AddAttribute(name, type, defaultValue, required, description);
}
// Read the element description
tinyxml2::XMLElement *descChild = _xml->FirstChildElement("description");
if (descChild && descChild->GetText())
{
_sdf->SetDescription(descChild->GetText());
}
// Get all child elements
for (tinyxml2::XMLElement *child = _xml->FirstChildElement("element");
child; child = child->NextSiblingElement("element"))
{
const char *copyDataString = child->Attribute("copy_data");
if (copyDataString &&
(std::string(copyDataString) == "true" ||
std::string(copyDataString) == "1"))
{
_sdf->SetCopyChildren(true);
}
else
{
ElementPtr element(new Element);
initXml(_errors, element, child, _config);
_sdf->AddElementDescription(element);
}
}
// Get all include elements
for (tinyxml2::XMLElement *child = _xml->FirstChildElement("include");
child; child = child->NextSiblingElement("include"))
{
std::string filename = child->Attribute("filename");
ElementPtr element(new Element);
initFile(filename, _config, element);
// override description for include elements
tinyxml2::XMLElement *description = child->FirstChildElement("description");
if (description)
{
element->SetDescription(description->GetText());
}
_sdf->AddElementDescription(element);
}
return true;
}
//////////////////////////////////////////////////
SDFPtr readFile(const std::string &_filename, Errors &_errors)
{
return readFile(_filename, ParserConfig::GlobalConfig(), _errors);
}
//////////////////////////////////////////////////
SDFPtr readFile(
const std::string &_filename, const ParserConfig &_config, Errors &_errors)
{
// Create and initialize the data structure that will hold the parsed SDF data
sdf::SDFPtr sdfParsed(new sdf::SDF());
sdf::init(sdfParsed, _config);
// Read an SDF file, and store the result in sdfParsed.
if (!sdf::readFile(_filename, _config, sdfParsed, _errors))
{
return SDFPtr();
}
return sdfParsed;
}
//////////////////////////////////////////////////
SDFPtr readFile(const std::string &_filename)
{
Errors errors;
SDFPtr result = readFile(_filename, errors);
// Output errors
for (auto const &e : errors)
std::cerr << e << std::endl;
return result;
}
//////////////////////////////////////////////////
bool readFile(const std::string &_filename, SDFPtr _sdf)
{
Errors errors;
bool result = readFile(_filename, _sdf, errors);
// Output errors
for (auto const &e : errors)
std::cerr << e << std::endl;
return result;
}
//////////////////////////////////////////////////
bool readFile(const std::string &_filename, SDFPtr _sdf, Errors &_errors)
{
return readFile(_filename, ParserConfig::GlobalConfig(), _sdf, _errors);
}
//////////////////////////////////////////////////
bool readFile(const std::string &_filename, const ParserConfig &_config,
SDFPtr _sdf, Errors &_errors)
{
return readFileInternal(_filename, true, _config, _sdf, _errors);
}
//////////////////////////////////////////////////
bool readFileWithoutConversion(
const std::string &_filename, SDFPtr _sdf, Errors &_errors)
{
return readFileWithoutConversion(
_filename, ParserConfig::GlobalConfig(), _sdf, _errors);
}
//////////////////////////////////////////////////
bool readFileWithoutConversion(const std::string &_filename,
const ParserConfig &_config, SDFPtr _sdf, Errors &_errors)
{
return readFileInternal(_filename, false, _config, _sdf, _errors);
}
//////////////////////////////////////////////////
bool readFileInternal(const std::string &_filename, const bool _convert,
const ParserConfig &_config, SDFPtr _sdf, Errors &_errors)
{
auto xmlDoc = makeSdfDoc();
std::string filename = sdf::findFile(_filename, true, true, _config);
if (filename.empty())
{
_errors.push_back({ErrorCode::FILE_READ, "Error finding file [" +
std::string(_filename) + "]."});
return false;
}
if (filesystem::is_directory(filename))
{
filename = getModelFilePath(_errors, filename);
}
if (!filesystem::exists(filename))
{
_errors.push_back({ErrorCode::FILE_READ, "File [" +
std::string(filename) + "] doesn't exist."});
return false;
}
auto error_code = xmlDoc.LoadFile(filename.c_str());
if (error_code)
{
_errors.push_back({ErrorCode::FILE_READ, "Error parsing XML in file [" +
std::string(filename) + "]: " +
std::string(xmlDoc.ErrorStr())});
return false;
}
tinyxml2::XMLElement *sdfXml = xmlDoc.FirstChildElement("sdf");
if (sdfXml)
{
// Suppress deprecation for sdf::URDF2SDF
return readDoc(&xmlDoc, _sdf, filename, _convert, _config, _errors);
}
else
{
tinyxml2::XMLElement *robotXml = xmlDoc.FirstChildElement("robot");
if (robotXml)
{
URDF2SDF u2g;
auto doc = makeSdfDoc();
u2g.InitModelFile(filename, _config, &doc);
if (sdf::readDoc(&doc, _sdf, filename, _convert, _config, _errors))
{
sdfdbg << "Converting URDF file [" << _filename << "] to SDFormat"
<< " and parsing it.\n";
return true;
}
else
{
_errors.push_back({ErrorCode::PARSING_ERROR,
"Failed to parse the URDF file after converting to SDFormat."});
return false;
}
}
else
{
_errors.push_back({ErrorCode::PARSING_ERROR,
"XML does not seem to be an SDFormat or an URDF file."});
return false;
}
}
return false;
}
//////////////////////////////////////////////////
bool readString(const std::string &_xmlString, SDFPtr _sdf)
{
Errors errors;
bool result = readString(_xmlString, _sdf, errors);
// Output errors
for (auto const &e : errors)
std::cerr << e << std::endl;
return result;
}
//////////////////////////////////////////////////
bool readString(const std::string &_xmlString, SDFPtr _sdf, Errors &_errors)
{
return readString(_xmlString, ParserConfig::GlobalConfig(), _sdf, _errors);
}
//////////////////////////////////////////////////
bool readString(const std::string &_xmlString, const ParserConfig &_config,
SDFPtr _sdf, Errors &_errors)
{
return readStringInternal(_xmlString, true, _config, _sdf, _errors);
}
//////////////////////////////////////////////////
bool readStringWithoutConversion(
const std::string &_filename, SDFPtr _sdf, Errors &_errors)
{
return readStringWithoutConversion(
_filename, ParserConfig::GlobalConfig(), _sdf, _errors);
}
//////////////////////////////////////////////////
bool readStringWithoutConversion(const std::string &_filename,
const ParserConfig &_config, SDFPtr _sdf, Errors &_errors)
{
return readStringInternal(_filename, false, _config, _sdf, _errors);
}
//////////////////////////////////////////////////
bool readStringInternal(const std::string &_xmlString, const bool _convert,
const ParserConfig &_config, SDFPtr _sdf, Errors &_errors)
{
auto xmlDoc = makeSdfDoc();
xmlDoc.Parse(_xmlString.c_str());
if (xmlDoc.Error())
{
_errors.push_back({ErrorCode::STRING_READ,
"Error parsing XML from string: " +
std::string(xmlDoc.ErrorStr())});
return false;
}
tinyxml2::XMLElement *sdfXml = xmlDoc.FirstChildElement("sdf");
if (sdfXml)
{
return readDoc(&xmlDoc, _sdf, std::string(kSdfStringSource), _convert,
_config, _errors);
}
else
{
tinyxml2::XMLElement *robotXml = xmlDoc.FirstChildElement("robot");
if (robotXml)
{
URDF2SDF u2g;
auto doc = makeSdfDoc();
u2g.InitModelString(_xmlString, _config, &doc);
if (sdf::readDoc(&doc, _sdf, std::string(kUrdfStringSource), _convert,
_config, _errors))
{
sdfdbg << "Converting URDF to SDFormat and parsing it.\n";
return true;
}
else
{
_errors.push_back({ErrorCode::PARSING_ERROR,
"Failed to parse the URDF file after converting to SDFormat."});
return false;
}
}
else
{
_errors.push_back({ErrorCode::PARSING_ERROR,
"XML does not seem to be an SDFormat or an URDF string."});
return false;
}
}
return false;
}
//////////////////////////////////////////////////
bool readString(const std::string &_xmlString, ElementPtr _sdf)
{
Errors errors;
bool result = readString(_xmlString, _sdf, errors);
// Output errors
for (auto const &e : errors)
std::cerr << e << std::endl;
return result;
}
//////////////////////////////////////////////////
bool readString(const std::string &_xmlString, ElementPtr _sdf, Errors &_errors)
{
return readString(_xmlString, ParserConfig::GlobalConfig(), _sdf, _errors);
}