-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathSDFFeatures.cc
More file actions
1569 lines (1417 loc) · 53.6 KB
/
SDFFeatures.cc
File metadata and controls
1569 lines (1417 loc) · 53.6 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
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) 2022 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 "SDFFeatures.hh"
#include <BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h>
#include <gz/common/Mesh.hh>
#include <gz/common/MeshManager.hh>
#include <gz/common/SubMesh.hh>
#include <gz/math/eigen3/Conversions.hh>
#include <gz/math/Helpers.hh>
#include <sdf/Box.hh>
#include <sdf/Capsule.hh>
#include <sdf/Cone.hh>
#include <sdf/Cylinder.hh>
#include <sdf/Ellipsoid.hh>
#include <sdf/Geometry.hh>
#include <sdf/Joint.hh>
#include <sdf/JointAxis.hh>
#include <sdf/Link.hh>
#include <sdf/Mesh.hh>
#include <sdf/Physics.hh>
#include <sdf/Plane.hh>
#include <sdf/Sphere.hh>
#include <sdf/Surface.hh>
#include <BulletDynamics/Featherstone/btMultiBodyLinkCollider.h>
#include <BulletDynamics/Featherstone/btMultiBodyJointLimitConstraint.h>
#include <LinearMath/btQuaternion.h>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
namespace gz {
namespace physics {
namespace bullet_featherstone {
/////////////////////////////////////////////////
/// \brief Resolve the pose of an SDF DOM object with respect to its relative_to
/// frame. If that fails, return the raw pose
static std::optional<Eigen::Isometry3d> ResolveSdfPose(
const ::sdf::SemanticPose &_semPose)
{
math::Pose3d pose;
::sdf::Errors errors = _semPose.Resolve(pose);
if (!errors.empty())
{
if (!_semPose.RelativeTo().empty())
{
gzerr << "There was an error in SemanticPose::Resolve:\n";
for (const auto &err : errors)
{
gzerr << err.Message() << std::endl;
}
gzerr << "There is no optimal fallback since the relative_to attribute["
<< _semPose.RelativeTo() << "] of the pose is not empty. "
<< "Falling back to using the raw Pose.\n";
}
pose = _semPose.RawPose();
}
return math::eigen3::convert(pose);
}
/////////////////////////////////////////////////
Identity SDFFeatures::ConstructSdfWorld(
const Identity &_engine,
const ::sdf::World &_sdfWorld)
{
const Identity worldID = this->ConstructEmptyWorld(_engine, _sdfWorld.Name());
const WorldInfoPtr &worldInfo = this->worlds.at(worldID);
worldInfo->world->setGravity(convertVec(_sdfWorld.Gravity()));
const ::sdf::Physics *physics = _sdfWorld.PhysicsByIndex(0);
if (physics)
worldInfo->stepSize = physics->MaxStepSize();
else
worldInfo->stepSize = 0.001;
for (std::size_t i = 0; i < _sdfWorld.ModelCount(); ++i)
{
const ::sdf::Model *model = _sdfWorld.ModelByIndex(i);
if (!model)
continue;
this->ConstructSdfModel(worldID, *model);
}
return worldID;
}
/////////////////////////////////////////////////
struct ParentInfo
{
const ::sdf::Joint *joint;
const ::sdf::Model *model;
const ::sdf::Link *link;
const ::sdf::Link *parent;
};
/////////////////////////////////////////////////
struct Structure
{
/// The root link of the model
const ::sdf::Link *rootLink;
const ::sdf::Model *model;
const ::sdf::Joint *rootJoint;
btScalar mass;
btVector3 inertia;
math::Pose3d linkToPrincipalAxesPose;
/// Is the root link fixed
bool fixedBase;
/// Get the parent joint of the link
std::unordered_map<const ::sdf::Link*, ParentInfo> parentOf;
/// This contains all the links except the root link
std::vector<const ::sdf::Link*> flatLinks;
};
/////////////////////////////////////////////////
void extractInertial(
const math::Inertiald &_inertial,
btScalar &_mass,
btVector3 &_principalInertiaMoments,
math::Pose3d &_linkToPrincipalAxesPose)
{
const auto &M = _inertial.MassMatrix();
_mass = static_cast<btScalar>(M.Mass());
_principalInertiaMoments = convertVec(M.PrincipalMoments());
_linkToPrincipalAxesPose = _inertial.Pose();
_linkToPrincipalAxesPose.Rot() *= M.PrincipalAxesOffset();
}
/////////////////////////////////////////////////
/// \brief Get pose of joint relative to link
/// \param[out] _resolvedPose Pose of joint relative to link
/// \param[in] _model Parent model of joint
/// \param[in] _joint Joint name
/// \param[in] _link Scoped link name
::sdf::Errors resolveJointPoseRelToLink(math::Pose3d &_resolvedPose,
const ::sdf::Model *_model,
const std::string &_joint, const std::string &_link)
{
::sdf::Errors errors;
const auto *joint = _model->JointByName(_joint);
if (!joint)
{
gzerr << "No joint [" << _joint << "] found in model ["
<< _model->Name() << "]" << std::endl;
return errors;
}
std::string childLinkName;
errors = joint->ResolveChildLink(childLinkName);
if (!errors.empty())
{
childLinkName = joint->ChildName();
}
// joint pose is expressed relative to child link so return joint pose
// if input link is the child link
if (childLinkName == _link)
{
errors = joint->SemanticPose().Resolve(_resolvedPose);
return errors;
}
// compute joint pose relative to specified link
const auto *link = _model->LinkByName(_link);
if (!link)
{
gzerr << "No link [" << _link << "] found in model ["
<< _model->Name() << "]" << std::endl;
return errors;
}
math::Pose3d jointPoseRelToModel;
errors = _model->SemanticPose().Resolve(jointPoseRelToModel,
_model->Name() + "::" + _joint);
jointPoseRelToModel = jointPoseRelToModel.Inverse();
math::Pose3d modelPoseRelToLink;
errors = _model->SemanticPose().Resolve(modelPoseRelToLink,
_model->Name() + "::" + _link);
_resolvedPose = modelPoseRelToLink * jointPoseRelToModel;
return errors;
}
/////////////////////////////////////////////////
/// \brief Recursively build a tree of parent-child data structures from the
/// input Model SDF.
/// \param[in] _sdfModel input Model SDF.
/// \param[out] _parentOf A map of child link to its parent
/// \param[out] _linkTree A map of parent link to its child links
bool buildTrees(const ::sdf::Model *_sdfModel,
std::unordered_map<const ::sdf::Link*, ParentInfo> &_parentOf,
std::unordered_map<const ::sdf::Link*,
std::vector<const ::sdf::Link*>> &_linkTree)
{
for (std::size_t i = 0; i < _sdfModel->JointCount(); ++i)
{
const auto *joint = _sdfModel->JointByIndex(i);
std::string parentLinkName;
::sdf::Errors errors = joint->ResolveParentLink(parentLinkName);
if (!errors.empty())
{
parentLinkName = joint->ParentName();
}
std::string childLinkName;
errors = joint->ResolveChildLink(childLinkName);
if (!errors.empty())
{
childLinkName = joint->ChildName();
}
const std::string &modelName = _sdfModel->Name();
const auto *parent = _sdfModel->LinkByName(parentLinkName);
const auto *child = _sdfModel->LinkByName(childLinkName);
switch (joint->Type())
{
case ::sdf::JointType::FIXED:
case ::sdf::JointType::REVOLUTE:
case ::sdf::JointType::PRISMATIC:
case ::sdf::JointType::BALL:
break;
default:
gzerr << "Joint type [" << (std::size_t)(joint->Type())
<< "] is not supported by "
<< "gz-physics-bullet-featherstone-plugin. "
<< "Replaced by a fixed joint.\n";
}
if (child == parent)
{
gzerr << "The Link [" << parentLinkName << "] is being attached to "
<< "itself by Joint [" << joint->Name() << "] in Model ["
<< modelName << "]. That is not allowed.\n";
return false;
}
if (nullptr == parent && parentLinkName != "world")
{
gzerr << "The link [" << parentLinkName << "] cannot be found in "
<< "Model [" << modelName << "], but joint ["
<< joint->Name() << "] wants to use it as its parent link\n";
return false;
}
else if (nullptr == parent)
{
// This link is attached to the world, making it the root
if (joint->Type() != ::sdf::JointType::FIXED)
{
gzerr << "Link [" << child->Name() << "] in Model ["
<< modelName << "] is being connected to the "
<< "world by Joint [" << joint->Name() << "] with a ["
<< (std::size_t)(joint->Type()) << "] joint type, but only "
<< "Fixed (" << (std::size_t)(::sdf::JointType::FIXED)
<< ") is supported by "
<< "gz-physics-bullet-featherstone-plugin\n";
return false;
}
}
if (!_parentOf.insert(
std::make_pair(child, ParentInfo{joint, _sdfModel, child, parent}))
.second)
{
gzerr << "The Link [" << childLinkName << "] in Model ["
<< modelName << "] has multiple parent joints. That is not "
<< "supported by the gz-physics-bullet-featherstone plugin.\n";
}
if (parent != nullptr)
{
_linkTree[parent].push_back(child);
}
}
// Recursively build tree from nested models
for (std::size_t i = 0; i < _sdfModel->ModelCount(); ++i)
{
const auto *model = _sdfModel->ModelByIndex(i);
if (!buildTrees(model, _parentOf, _linkTree))
return false;
}
return true;
}
/////////////////////////////////////////////////
/// \brief Find all the root links given a model SDF
/// \param[in] _sdfModel Model SDF
/// \param[in] _parentOf A map of child link to its parent info
/// \param[out] _rootLinks A vector of root links paired with their
/// immediate parent model
void findRootLinks(const ::sdf::Model *_sdfModel,
const std::unordered_map<const ::sdf::Link*, ParentInfo> &_parentOf,
std::vector<std::pair<const ::sdf::Link*, const ::sdf::Model*>> &_rootLinks)
{
for (std::size_t i = 0; i < _sdfModel->LinkCount(); ++i)
{
const auto *link = _sdfModel->LinkByIndex(i);
auto parentOfIt = _parentOf.find(link);
if (parentOfIt == _parentOf.end() || !parentOfIt->second.parent)
{
// If there is not parent or parent is null (world),
// this link must be a root.
_rootLinks.push_back({link, _sdfModel});
}
}
for (std::size_t i = 0; i < _sdfModel->ModelCount(); ++i)
{
const auto *model = _sdfModel->ModelByIndex(i);
findRootLinks(model, _parentOf, _rootLinks);
}
}
/////////////////////////////////////////////////
/// \brief Build a structure for each root link
/// \param[in] _rootLink Root link in a model tree
/// \param[in] _parentOf A map of child link to its parent
/// \param[in] _linkTree A map of parent link to its child links
std::optional<Structure> buildStructure(
const ::sdf::Link * _rootLink,
const ::sdf::Model * _model,
const std::unordered_map<const ::sdf::Link*, ParentInfo> &_parentOf,
std::unordered_map<const ::sdf::Link*, std::vector<const ::sdf::Link*>>
&_linkTree)
{
bool fixed = false;
const ::sdf::Joint *rootJoint = nullptr;
// rootJoint only exists if root link is connected to world by a joint
auto linkIt = _parentOf.find(_rootLink);
if (linkIt != _parentOf.end())
{
const auto &parentInfo = linkIt->second;
rootJoint = parentInfo.joint;
fixed = true;
}
// The documentation for bullet does not mention whether parent links must
// have a lower index than their child links, but the Featherstone Algorithm
// needs to crawl up and down the tree systematically, and so the flattened
// tree structures used by the algorithm usually do expect the parents to
// come before their children in the array, and do not work correctly if that
// ordering is not held. Out of an abundance of caution we will assume that
// ordering is necessary.
std::vector<const ::sdf::Link*> flatLinks;
std::function<void(const ::sdf::Link *)> flattenLinkTree =
[&](const ::sdf::Link *link)
{
if (link != _rootLink)
{
flatLinks.push_back(link);
}
if (auto it = _linkTree.find(link); it != _linkTree.end())
{
for (const auto &childLink : it->second)
{
flattenLinkTree(childLink);
}
}
};
flattenLinkTree(_rootLink);
btScalar mass;
btVector3 inertia;
math::Pose3d linkToPrincipalAxesPose;
extractInertial(_rootLink->Inertial(), mass, inertia,
linkToPrincipalAxesPose);
// Uncomment to debug structure
// std::cout << "Structure: " << std::endl;
// std::cout << " model: " << _model->Name() << std::endl;
// std::cout << " root link: " << _rootLink->Name() << std::endl;
// std::cout << " root joint: " << ((rootJoint) ? rootJoint->Name() : "N/A")
// << std::endl;
// std::cout << " mass: " << mass << std::endl;
// std::cout << " fixed: " << fixed << std::endl;
// std::cout << " flatLinks size: " << flatLinks.size() << std::endl;
return Structure{
_rootLink, _model, rootJoint, mass, inertia, linkToPrincipalAxesPose, fixed,
_parentOf, flatLinks};
}
/////////////////////////////////////////////////
/// \brief Validate input model SDF and build a vector of structures.
/// Each structure represents a single kinematic tree in the model
/// \param[in] _sdfModel Input model SDF
/// \return A vector of structures
std::vector<Structure> validateModel(const ::sdf::Model &_sdfModel)
{
// A map of child link and its parent info
std::unordered_map<const ::sdf::Link*, ParentInfo> parentOf;
// A map of parent link to a vector of its child links
std::unordered_map<const ::sdf::Link*, std::vector<const ::sdf::Link*>>
linkTree;
// A vector of root link of its parent model
// Use a vector to preseve order of entities defined in sdf
std::vector<std::pair<const ::sdf::Link*, const ::sdf::Model*>> rootLinks;
buildTrees(&_sdfModel, parentOf, linkTree);
findRootLinks(&_sdfModel, parentOf, rootLinks);
std::vector<Structure> structures;
if (rootLinks.empty())
{
// No root link was found in this model
gzerr << "No root links are found in this model" << std::endl;
return structures;
}
// Build subtrees
for (const auto &rootLinkIt : rootLinks)
{
auto structure = buildStructure(rootLinkIt.first, rootLinkIt.second,
parentOf, linkTree);
if (structure.has_value())
{
structures.push_back(*structure);
}
}
return structures;
}
/////////////////////////////////////////////////
Identity SDFFeatures::ConstructSdfNestedModel(const Identity &_parentID,
const ::sdf::Model &_sdfModel)
{
return this->ConstructSdfModelImpl(_parentID, _sdfModel);
}
/////////////////////////////////////////////////
Identity SDFFeatures::ConstructSdfModelImpl(
std::size_t _parentID,
const ::sdf::Model &_sdfModel)
{
// The ConstructSdfModelImpl function constructs the entire sdf model tree,
// including nested models So return the nested model identity if it is
// constructed already
auto wIt = this->worlds.find(_parentID);
if (wIt == this->worlds.end())
{
auto mIt = this->models.find(_parentID);
std::size_t nestedModelID = mIt->second->nestedModelNameToEntityId.at(
_sdfModel.Name());
return this->GenerateIdentity(nestedModelID,
this->models.at(nestedModelID));
}
auto structures = validateModel(_sdfModel);
if (structures.empty())
return this->GenerateInvalidId();
if (structures.size() > 1)
{
// multiple sub-trees detected in model
// \todo(iche033) support multiple kinematic trees and
// multiple floating links in a single model
// https://github.com/gazebosim/gz-physics/issues/550
gzerr << "Multiple sub-trees / floating links detected in a model. "
<< "This is not supported in bullet-featherstone implementation yet."
<< std::endl;
}
// Create model for the first structure.
auto &structure = structures[0];
const bool isStatic = _sdfModel.Static();
WorldInfo *world = nullptr;
const auto modelToRootLink =
ResolveSdfPose(structure.rootLink->SemanticPose());
if (!modelToRootLink)
return this->GenerateInvalidId();
const auto rootInertialToLink =
gz::math::eigen3::convert(structure.linkToPrincipalAxesPose).inverse();
// A map of link sdf to parent model identity
std::unordered_map<const ::sdf::Link*, std::size_t> linkParentModelIds;
std::unordered_map<const ::sdf::Model*, Identity> modelIDs;
std::size_t rootModelID = 0u;
std::shared_ptr<GzMultiBody> rootMultiBody;
auto getModelScopedName = [&](const ::sdf::Model *_targetModel,
const ::sdf::Model *_parentModel, const std::string &_prefix,
std::string &_modelScopedName, auto &&_getModelScopedName)
{
for (std::size_t i = 0u; i < _parentModel->ModelCount(); ++i)
{
auto childModel = _parentModel->ModelByIndex(i);
if (childModel == _targetModel)
{
_modelScopedName = _prefix + childModel->Name();
return true;
}
else
{
if (_getModelScopedName(_targetModel, childModel,
_prefix + childModel->Name() + "::", _modelScopedName,
_getModelScopedName))
return true;
}
}
return false;
};
// Add all models, including nested models
auto addModels = [&](std::size_t _modelOrWorldID, const ::sdf::Model *_model,
auto &&_addModels)
{
if (!_model)
return false;
auto worldIt = this->worlds.find(_modelOrWorldID);
const bool isNested = worldIt == this->worlds.end();
auto modelID = [&] {
if (isNested)
{
auto modelIt = this->models.find(_modelOrWorldID);
auto worldIdentity = modelIt->second->world;
auto modelIdentity =
this->GenerateIdentity(_modelOrWorldID, modelIt->second);
std::string modelScopedName;
if (!getModelScopedName(_model, &_sdfModel,
_sdfModel.Name() + "::", modelScopedName, getModelScopedName))
this->GenerateInvalidId();
math::Pose3d modelPose;
auto errors = _sdfModel.SemanticPose().Resolve(modelPose,
modelScopedName);
if (!errors.empty())
this->GenerateInvalidId();
auto modelToNestedModel = math::eigen3::convert(modelPose).inverse();
auto nestedModelFromRootLink =
modelToRootLink->inverse() * modelToNestedModel;
return this->AddNestedModel(
_model->Name(), modelIdentity, worldIdentity,
nestedModelFromRootLink, rootInertialToLink,
rootMultiBody);
}
else
{
auto worldIdentity = this->GenerateIdentity(
_modelOrWorldID, worldIt->second);
rootMultiBody = std::make_shared<GzMultiBody>(
static_cast<int>(structure.flatLinks.size()),
structure.mass,
structure.inertia,
structure.fixedBase || isStatic,
true);
world = this->ReferenceInterface<WorldInfo>(worldIdentity);
auto id = this->AddModel(
_model->Name(), worldIdentity,
modelToRootLink->inverse(),
rootInertialToLink,
rootMultiBody);
rootModelID = id;
return id;
}
}();
// build link to model map for use later when adding links
for (std::size_t i = 0; i < _model->LinkCount(); ++i)
{
const ::sdf::Link *link = _model->LinkByIndex(i);
linkParentModelIds[link] = modelID;
}
modelIDs.insert(std::make_pair(_model, modelID));
// recursively add nested models
for (std::size_t i = 0; i < _model->ModelCount(); ++i)
{
if (!_addModels(modelID, _model->ModelByIndex(i), _addModels))
return false;
}
return true;
};
if (!addModels(_parentID, &_sdfModel, addModels))
{
return this->GenerateInvalidId();
}
// Add base link
std::size_t baseLinkModelID = linkParentModelIds.at(structure.rootLink);
const auto rootID =
this->AddLink(LinkInfo{
structure.rootLink->Name(), std::nullopt,
this->GenerateIdentity(baseLinkModelID, this->models.at(baseLinkModelID)),
rootInertialToLink
});
rootMultiBody->setUserIndex(std::size_t(rootID));
auto modelID =
this->GenerateIdentity(rootModelID, this->models[rootModelID]);
auto *model = this->ReferenceInterface<ModelInfo>(modelID);
// Add world joint
if (structure.rootJoint)
{
const auto &parentInfo = structure.parentOf.at(structure.rootLink);
this->AddJoint(
JointInfo{
structure.rootJoint->Name(),
RootJoint{},
std::nullopt,
rootID,
Eigen::Isometry3d::Identity(),
Eigen::Isometry3d::Identity(),
modelIDs.find(parentInfo.model)->second
});
}
model->body->setLinearDamping(0.0);
model->body->setAngularDamping(0.0);
std::unordered_map<const ::sdf::Link*, Identity> linkIDs;
linkIDs.insert(std::make_pair(structure.rootLink, rootID));
// Add all links and joints
for (int i = 0; i < static_cast<int>(structure.flatLinks.size()); ++i)
{
const auto *link = structure.flatLinks[static_cast<std::size_t>(i)];
btScalar mass;
btVector3 inertia;
math::Pose3d linkToPrincipalAxesPose;
extractInertial(link->Inertial(), mass, inertia, linkToPrincipalAxesPose);
const Eigen::Isometry3d linkToComTf = gz::math::eigen3::convert(
linkToPrincipalAxesPose);
if (linkIDs.find(link) == linkIDs.end())
{
std::size_t parentModelID = linkParentModelIds[link];
const auto linkID = this->AddLink(
LinkInfo{link->Name(), i,
this->GenerateIdentity(parentModelID, this->models.at(parentModelID)),
linkToComTf.inverse()});
linkIDs.insert(std::make_pair(link, linkID));
}
if (auto *linkInfo = this->ReferenceInterface<LinkInfo>(linkIDs.at(link)))
{
linkInfo->mass = static_cast<double>(mass);
linkInfo->inertia = Eigen::Vector3d(
static_cast<double>(inertia[0]),
static_cast<double>(inertia[1]),
static_cast<double>(inertia[2]));
}
if (!structure.parentOf.empty())
{
const auto &parentInfo = structure.parentOf.at(link);
const auto *joint = parentInfo.joint;
std::string parentLinkName;
::sdf::Errors errors = joint->ResolveParentLink(parentLinkName);
if (!errors.empty())
{
parentLinkName = joint->ParentName();
}
const auto &parentLinkID = linkIDs.at(
parentInfo.model->LinkByName(parentLinkName));
const auto *parentLinkInfo = this->ReferenceInterface<LinkInfo>(
parentLinkID);
int parentIndex = -1;
if (parentLinkInfo->indexInModel.has_value())
parentIndex = *parentLinkInfo->indexInModel;
Eigen::Isometry3d poseParentLinkToJoint;
Eigen::Isometry3d poseParentComToJoint;
{
gz::math::Pose3d gzPoseParentToJoint;
errors = resolveJointPoseRelToLink(gzPoseParentToJoint,
parentInfo.model, joint->Name(), parentLinkName);
if (!errors.empty())
{
gzerr << "An error occurred while resolving the transform of Joint ["
<< joint->Name() << "] in Model [" << parentInfo.model->Name()
<< "]:\n";
for (const auto &error : errors)
{
gzerr << error << "\n";
}
return this->GenerateInvalidId();
}
poseParentLinkToJoint = gz::math::eigen3::convert(gzPoseParentToJoint);
poseParentComToJoint =
poseParentLinkToJoint * parentLinkInfo->inertiaToLinkFrame;
}
Eigen::Isometry3d poseJointToChild;
{
gz::math::Pose3d gzPoseChildToJoint;
// this retrieves the joint pose relative to link
std::string childLinkName;
errors = joint->ResolveChildLink(childLinkName);
if (!errors.empty())
{
childLinkName = joint->ChildName();
}
errors = resolveJointPoseRelToLink(gzPoseChildToJoint,
parentInfo.model, joint->Name(), childLinkName);
if (!errors.empty())
{
gzerr << "An error occured while resolving the transform of Link ["
<< link->Name() << "]:\n";
for (const auto &error : errors)
{
gzerr << error << "\n";
}
return this->GenerateInvalidId();
}
gz::math::Pose3d gzPoseJointToChild;
gzPoseJointToChild = gzPoseChildToJoint.Inverse();
poseJointToChild = gz::math::eigen3::convert(gzPoseJointToChild);
}
btQuaternion btRotParentComToJoint;
convertMat(poseParentComToJoint.linear())
.getRotation(btRotParentComToJoint);
btTransform parentLocalInertialFrame = convertTf(
parentLinkInfo->inertiaToLinkFrame);
btTransform parent2jointBt = convertTf(
poseParentLinkToJoint); // X_PJ
// offsetInABt = parent COM to pivot (X_IpJ)
// offsetInBBt = current COM to pivot (X_IcJ)
//
// X_PIp
// X_PJ
// X_IpJ = X_PIp^-1 * X_PJ
//
// X_IcJ = X_CIc^-1 * X_CJ
btTransform offsetInABt, offsetInBBt;
offsetInABt = parentLocalInertialFrame * parent2jointBt;
offsetInBBt =
convertTf(linkToComTf.inverse() * poseJointToChild.inverse());
// R_IcJ * R_IpJ ^ -1 = R_IcIp;
btQuaternion parentRotToThis =
offsetInBBt.getRotation() * offsetInABt.inverse().getRotation();
auto jointID = this->AddJoint(
JointInfo{
joint->Name(),
InternalJoint{i},
linkIDs.find(parentInfo.parent)->second,
linkIDs.find(link)->second,
poseParentLinkToJoint,
poseJointToChild,
modelIDs.find(parentInfo.model)->second
});
auto jointInfo = this->ReferenceInterface<JointInfo>(jointID);
if (::sdf::JointType::PRISMATIC == joint->Type() ||
::sdf::JointType::REVOLUTE == joint->Type() ||
::sdf::JointType::BALL == joint->Type())
{
if (::sdf::JointType::REVOLUTE == joint->Type())
{
const auto axis = convertVec(joint->Axis()->Xyz());
model->body->setupRevolute(
i, mass, inertia, parentIndex,
parentRotToThis,
quatRotate(offsetInBBt.getRotation(), axis),
offsetInABt.getOrigin(),
-offsetInBBt.getOrigin(),
true);
}
else if (::sdf::JointType::PRISMATIC == joint->Type())
{
const auto axis = convertVec(joint->Axis()->Xyz());
model->body->setupPrismatic(
i, mass, inertia, parentIndex,
parentRotToThis,
quatRotate(offsetInBBt.getRotation(), axis),
offsetInABt.getOrigin(),
-offsetInBBt.getOrigin(),
true);
}
else if (::sdf::JointType::BALL == joint->Type())
{
model->body->setupSpherical(
i, mass, inertia, parentIndex,
parentRotToThis,
offsetInABt.getOrigin(),
-offsetInBBt.getOrigin(),
true);
}
}
else
{
model->body->setupFixed(
i, mass, inertia, parentIndex,
parentRotToThis,
offsetInABt.getOrigin(),
-offsetInBBt.getOrigin());
}
if (::sdf::JointType::PRISMATIC == joint->Type() ||
::sdf::JointType::REVOLUTE == joint->Type() ||
::sdf::JointType::BALL == joint->Type())
{
// Note: These m_joint* properties below are currently not supported by
// bullet-featherstone and so setting them does not have any effect.
// The lower and uppper limit is supported via the
// btMultiBodyJointLimitConstraint.
if (joint->Axis())
{
model->body->getLink(i).m_jointLowerLimit =
static_cast<btScalar>(joint->Axis()->Lower());
model->body->getLink(i).m_jointUpperLimit =
static_cast<btScalar>(joint->Axis()->Upper());
model->body->getLink(i).m_jointFriction =
static_cast<btScalar>(joint->Axis()->Friction());
model->body->getLink(i).m_jointMaxVelocity =
static_cast<btScalar>(joint->Axis()->MaxVelocity());
model->body->getLink(i).m_jointMaxForce =
static_cast<btScalar>(joint->Axis()->Effort());
jointInfo->minEffort = -joint->Axis()->Effort();
jointInfo->maxEffort = joint->Axis()->Effort();
jointInfo->minVelocity = -joint->Axis()->MaxVelocity();
jointInfo->maxVelocity = joint->Axis()->MaxVelocity();
jointInfo->axisLower = joint->Axis()->Lower();
jointInfo->axisUpper = joint->Axis()->Upper();
jointInfo->damping = joint->Axis()->Damping();
jointInfo->springStiffness = joint->Axis()->SpringStiffness();
jointInfo->springReference = joint->Axis()->SpringReference();
}
if (::sdf::JointType::BALL != joint->Type())
{
jointInfo->jointLimits =
std::make_shared<btMultiBodyJointLimitConstraint>(
model->body.get(), i,
static_cast<btScalar>(joint->Axis()->Lower()),
static_cast<btScalar>(joint->Axis()->Upper()));
world->world->addMultiBodyConstraint(jointInfo->jointLimits.get());
}
}
jointInfo->jointFeedback = std::make_shared<btMultiBodyJointFeedback>();
jointInfo->jointFeedback->m_reactionForces.setZero();
model->body->getLink(i).m_jointFeedback = jointInfo->jointFeedback.get();
}
}
model->body->setHasSelfCollision(_sdfModel.SelfCollide());
model->body->finalizeMultiDof();
const auto worldToModel = ResolveSdfPose(_sdfModel.SemanticPose());
if (!worldToModel)
return this->GenerateInvalidId();
auto modelToNestedModel = Eigen::Isometry3d::Identity();
// if the model of the root link is nested in a top level model, compute
// its pose relative to top level model
if (structure.model != &_sdfModel)
{
// get the scoped name of the model
// This is used to resolve the model pose
std::string modelScopedName;
math::Pose3d modelPose;
if (!getModelScopedName(structure.model, &_sdfModel,
_sdfModel.Name() + "::", modelScopedName, getModelScopedName))
return this->GenerateInvalidId();
auto errors = _sdfModel.SemanticPose().Resolve(modelPose,
modelScopedName);
if (!errors.empty())
return this->GenerateInvalidId();
modelToNestedModel = math::eigen3::convert(modelPose).inverse();
}
const auto worldToRootCom =
*worldToModel * modelToNestedModel * *modelToRootLink *
rootInertialToLink.inverse();
model->body->SetBaseWorldTransform(convertTf(worldToRootCom));
model->body->setBaseVel(btVector3(0, 0, 0));
model->body->setBaseOmega(btVector3(0, 0, 0));
{
const auto *link = structure.rootLink;
btScalar mass;
btVector3 inertia;
math::Pose3d linkToPrincipalAxesPose;
extractInertial(link->Inertial(), mass, inertia, linkToPrincipalAxesPose);
model->body->setBaseMass(mass);
model->body->setBaseInertia(inertia);
model->baseMass = mass;
model->baseInertia = inertia;
if (auto *linkInfo = this->ReferenceInterface<LinkInfo>(rootID))
{
linkInfo->mass = static_cast<double>(mass);
linkInfo->inertia = Eigen::Vector3d(inertia[0], inertia[1], inertia[2]);
}
}
world->world->addMultiBody(model->body.get());
for (const auto& [linkSdf, linkID] : linkIDs)
{
if (linkSdf->CollisionCount() == 0u)
{
// create empty link collider and compound shape if there are no
// collisions
this->CreateLinkCollider(linkID, isStatic);
}
else
{
for (std::size_t c = 0; c < linkSdf->CollisionCount(); ++c)
{
// If we fail to add the collision, just keep building the model. It may
// need to be constructed outside of the SDF generation pipeline, e.g.
// with AttachHeightmap.
this->AddSdfCollision(linkID, *linkSdf->CollisionByIndex(c), isStatic);
}
}
}
// Add the remaining links in the model without constructing the bullet
// objects. These are dummy links for book-keeping purposes
// \todo(iche033) The code will need to be updated when multiple subtrees in
// a single model is supported.
for (std::size_t i = 1u; i < structures.size(); ++i)
{
auto otherStructure = structures[i];
// Add base link
std::size_t rootLinkModelID = linkParentModelIds[otherStructure.rootLink];
auto rootLinkModelInfo = this->models.at(rootLinkModelID);
this->AddLink(LinkInfo{
otherStructure.rootLink->Name(),
std::nullopt,
this->GenerateIdentity(rootLinkModelID, rootLinkModelInfo),
gz::math::eigen3::convert(
otherStructure.linkToPrincipalAxesPose).inverse()
});
gzwarn << "Floating body / sub-tree detected. Disabling link: '"
<< otherStructure.rootLink->Name() << "' "
<< "from model '" << rootLinkModelInfo->name << "'." << std::endl;
// other links
for (int j = 0; j < static_cast<int>(otherStructure.flatLinks.size()); ++j)
{
const auto *link = otherStructure.flatLinks[static_cast<std::size_t>(j)];
std::size_t parentModelID = linkParentModelIds[link];
btScalar mass;
btVector3 inertia;
math::Pose3d linkToPrincipalAxesPose;
extractInertial(link->Inertial(), mass, inertia, linkToPrincipalAxesPose);
auto parentModelInfo = this->models.at(parentModelID);
const auto linkID = this->AddLink(
LinkInfo{link->Name(), std::nullopt,
this->GenerateIdentity(parentModelID, parentModelInfo),
gz::math::eigen3::convert(linkToPrincipalAxesPose).inverse()});
gzwarn << "Floating body / sub-tree detected. Disabling link: '"
<< link->Name() << "' " << "from model '" << parentModelInfo->name
<< "'." << std::endl;
}
}
return modelID;
}
/////////////////////////////////////////////////
Identity SDFFeatures::ConstructSdfModel(