-
Notifications
You must be signed in to change notification settings - Fork 276
/
Physics.cc
2395 lines (2090 loc) · 85.2 KB
/
Physics.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 (C) 2018 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 "Physics.hh"
#include <ignition/msgs/contact.pb.h>
#include <ignition/msgs/contacts.pb.h>
#include <ignition/msgs/entity.pb.h>
#include <ignition/msgs/Utility.hh>
#include <algorithm>
#include <iostream>
#include <deque>
#include <map>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <ignition/common/MeshManager.hh>
#include <ignition/common/Profiler.hh>
#include <ignition/common/SystemPaths.hh>
#include <ignition/math/AxisAlignedBox.hh>
#include <ignition/math/eigen3/Conversions.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/physics/config.hh>
#include <ignition/physics/FeatureList.hh>
#include <ignition/physics/FeaturePolicy.hh>
#include <ignition/physics/RelativeQuantity.hh>
#include <ignition/physics/RequestEngine.hh>
#include <ignition/physics/BoxShape.hh>
#include <ignition/physics/CylinderShape.hh>
#include <ignition/physics/ForwardStep.hh>
#include <ignition/physics/FrameSemantics.hh>
#include <ignition/physics/FreeGroup.hh>
#include <ignition/physics/FixedJoint.hh>
#include <ignition/physics/GetContacts.hh>
#include <ignition/physics/GetBoundingBox.hh>
#include <ignition/physics/Joint.hh>
#include <ignition/physics/Link.hh>
#include <ignition/physics/RemoveEntities.hh>
#include <ignition/physics/Shape.hh>
#include <ignition/physics/SphereShape.hh>
#include <ignition/physics/mesh/MeshShape.hh>
#include <ignition/physics/sdf/ConstructCollision.hh>
#include <ignition/physics/sdf/ConstructJoint.hh>
#include <ignition/physics/sdf/ConstructLink.hh>
#include <ignition/physics/sdf/ConstructModel.hh>
#include <ignition/physics/sdf/ConstructNestedModel.hh>
#include <ignition/physics/sdf/ConstructWorld.hh>
#include <ignition/plugin/Loader.hh>
#include <ignition/plugin/PluginPtr.hh>
#include <ignition/plugin/Register.hh>
// SDF
#include <sdf/Collision.hh>
#include <sdf/Joint.hh>
#include <sdf/Link.hh>
#include <sdf/Mesh.hh>
#include <sdf/Model.hh>
#include <sdf/Surface.hh>
#include <sdf/World.hh>
#include "ignition/gazebo/EntityComponentManager.hh"
#include "ignition/gazebo/Util.hh"
// Components
#include "ignition/gazebo/components/AngularAcceleration.hh"
#include "ignition/gazebo/components/AngularVelocity.hh"
#include "ignition/gazebo/components/AngularVelocityCmd.hh"
#include "ignition/gazebo/components/AxisAlignedBox.hh"
#include "ignition/gazebo/components/BatterySoC.hh"
#include "ignition/gazebo/components/CanonicalLink.hh"
#include "ignition/gazebo/components/ChildLinkName.hh"
#include "ignition/gazebo/components/Collision.hh"
#include "ignition/gazebo/components/ContactSensorData.hh"
#include "ignition/gazebo/components/Geometry.hh"
#include "ignition/gazebo/components/Gravity.hh"
#include "ignition/gazebo/components/Inertial.hh"
#include "ignition/gazebo/components/DetachableJoint.hh"
#include "ignition/gazebo/components/Joint.hh"
#include "ignition/gazebo/components/JointAxis.hh"
#include "ignition/gazebo/components/JointPosition.hh"
#include "ignition/gazebo/components/JointPositionReset.hh"
#include "ignition/gazebo/components/JointType.hh"
#include "ignition/gazebo/components/JointVelocity.hh"
#include "ignition/gazebo/components/JointVelocityCmd.hh"
#include "ignition/gazebo/components/JointVelocityReset.hh"
#include "ignition/gazebo/components/LinearAcceleration.hh"
#include "ignition/gazebo/components/LinearVelocity.hh"
#include "ignition/gazebo/components/LinearVelocityCmd.hh"
#include "ignition/gazebo/components/Link.hh"
#include "ignition/gazebo/components/Model.hh"
#include "ignition/gazebo/components/Name.hh"
#include "ignition/gazebo/components/ParentEntity.hh"
#include "ignition/gazebo/components/ParentLinkName.hh"
#include "ignition/gazebo/components/ExternalWorldWrenchCmd.hh"
#include "ignition/gazebo/components/JointForceCmd.hh"
#include "ignition/gazebo/components/PhysicsEnginePlugin.hh"
#include "ignition/gazebo/components/Pose.hh"
#include "ignition/gazebo/components/PoseCmd.hh"
#include "ignition/gazebo/components/SelfCollide.hh"
#include "ignition/gazebo/components/SlipComplianceCmd.hh"
#include "ignition/gazebo/components/Static.hh"
#include "ignition/gazebo/components/ThreadPitch.hh"
#include "ignition/gazebo/components/World.hh"
#include "CanonicalLinkModelTracker.hh"
#include "EntityFeatureMap.hh"
using namespace ignition;
using namespace ignition::gazebo;
using namespace ignition::gazebo::systems;
using namespace ignition::gazebo::systems::physics_system;
namespace components = ignition::gazebo::components;
// Private data class.
class ignition::gazebo::systems::PhysicsPrivate
{
/// \brief This is the minimum set of features that any physics engine must
/// implement to be supported by this system.
/// New features can't be added to this list in minor / patch releases, in
/// order to maintain backwards compatibility with downstream physics plugins.
public: struct MinimumFeatureList : ignition::physics::FeatureList<
ignition::physics::FindFreeGroupFeature,
ignition::physics::SetFreeGroupWorldPose,
ignition::physics::FreeGroupFrameSemantics,
ignition::physics::LinkFrameSemantics,
ignition::physics::ForwardStep,
ignition::physics::RemoveEntities,
ignition::physics::sdf::ConstructSdfLink,
ignition::physics::sdf::ConstructSdfModel,
ignition::physics::sdf::ConstructSdfWorld
>{};
/// \brief Engine type with just the minimum features.
public: using EnginePtrType = ignition::physics::EnginePtr<
ignition::physics::FeaturePolicy3d, MinimumFeatureList>;
/// \brief World type with just the minimum features.
public: using WorldPtrType = ignition::physics::WorldPtr<
ignition::physics::FeaturePolicy3d, MinimumFeatureList>;
/// \brief Model type with just the minimum features.
public: using ModelPtrType = ignition::physics::ModelPtr<
ignition::physics::FeaturePolicy3d, MinimumFeatureList>;
/// \brief Link type with just the minimum features.
public: using LinkPtrType = ignition::physics::LinkPtr<
ignition::physics::FeaturePolicy3d, MinimumFeatureList>;
/// \brief Free group type with just the minimum features.
public: using FreeGroupPtrType = ignition::physics::FreeGroupPtr<
ignition::physics::FeaturePolicy3d, MinimumFeatureList>;
/// \brief Create physics entities
/// \param[in] _ecm Constant reference to ECM.
public: void CreatePhysicsEntities(const EntityComponentManager &_ecm);
/// \brief Remove physics entities if they are removed from the ECM
/// \param[in] _ecm Constant reference to ECM.
public: void RemovePhysicsEntities(const EntityComponentManager &_ecm);
/// \brief Update physics from components
/// \param[in] _ecm Mutable reference to ECM.
public: void UpdatePhysics(EntityComponentManager &_ecm);
/// \brief Step the simulation for each world
/// \param[in] _dt Duration
/// \returns Output data from the physics engine (this currently contains
/// data for links that experienced a pose change in the physics step)
public: ignition::physics::ForwardStep::Output Step(
const std::chrono::steady_clock::duration &_dt);
/// \brief Get data of links that were updated in the latest physics step.
/// \param[in] _ecm Mutable reference to ECM.
/// \param[in] _updatedLinks Updated link poses from the latest physics step
/// that were written to by the physics engine (some physics engines may
/// not write this data to ForwardStep::Output. If not, _ecm is used to get
/// this updated link pose data).
/// \return A map of gazebo link entities to their updated pose data.
/// std::map is used because canonical links must be in topological order
/// to ensure that nested models with multiple canonical links are updated
/// properly (models must be updated in topological order).
public: std::map<Entity, physics::FrameData3d> ChangedLinks(
EntityComponentManager &_ecm,
const ignition::physics::ForwardStep::Output &_updatedLinks);
/// \brief Update components from physics simulation
/// \param[in] _ecm Mutable reference to ECM.
/// \param[in] _linkFrameData Links that experienced a pose change in the
/// most recent physics step. The key is the entity of the link, and the
/// value is the updated frame data corresponding to that entity.
public: void UpdateSim(EntityComponentManager &_ecm,
const std::map<
Entity, physics::FrameData3d> &_linkFrameData);
/// \brief Update collision components from physics simulation
/// \param[in] _ecm Mutable reference to ECM.
public: void UpdateCollisions(EntityComponentManager &_ecm);
/// \brief FrameData relative to world at a given offset pose
/// \param[in] _link ign-physics link
/// \param[in] _pose Offset pose in which to compute the frame data
/// \returns FrameData at the given offset pose
public: physics::FrameData3d LinkFrameDataAtOffset(
const LinkPtrType &_link, const math::Pose3d &_pose) const;
/// \brief Get transform from one ancestor entity to a descendant entity
/// that are in the same model.
/// \param[in] _from An ancestor of the _to entity.
/// \param[in] _to A descendant of the _from entity.
/// \return Pose transform between the two entities
public: ignition::math::Pose3d RelativePose(const Entity &_from,
const Entity &_to, const EntityComponentManager &_ecm) const;
/// \brief Cache the top-level model for each entity.
/// The key is an entity and the value is its top level model.
public: std::unordered_map<Entity, Entity> topLevelModelMap;
/// \brief Keep track of what entities are static (models and links).
public: std::unordered_set<Entity> staticEntities;
/// \brief Keep track of poses for links attached to non-static models.
/// This allows for skipping pose updates if a link's pose didn't change
/// after a physics step.
public: std::unordered_map<Entity, ignition::math::Pose3d> linkWorldPoses;
/// \brief Keep a mapping of canonical links to models that have this
/// canonical link. Useful for updating model poses efficiently after a
/// physics step
public: CanonicalLinkModelTracker canonicalLinkModelTracker;
/// \brief Keep track of non-static model world poses. Since non-static
/// models may not move on a given iteration, we want to keep track of the
/// most recent model world pose change that took place.
public: std::unordered_map<Entity, math::Pose3d> modelWorldPoses;
/// \brief A map between model entity ids in the ECM to whether its battery
/// has drained.
public: std::unordered_map<Entity, bool> entityOffMap;
/// \brief Entities whose pose commands have been processed and should be
/// deleted the following iteration.
public: std::unordered_set<Entity> worldPoseCmdsToRemove;
/// \brief used to store whether physics objects have been created.
public: bool initialized = false;
/// \brief Pointer to the underlying ign-physics Engine entity.
public: EnginePtrType engine = nullptr;
/// \brief Vector3d equality comparison function.
public: std::function<bool(const math::Vector3d &, const math::Vector3d &)>
vec3Eql { [](const math::Vector3d &_a, const math::Vector3d &_b)
{
return _a.Equal(_b, 1e-6);
}};
/// \brief Pose3d equality comparison function.
public: std::function<bool(const math::Pose3d &, const math::Pose3d &)>
pose3Eql { [](const math::Pose3d &_a, const math::Pose3d &_b)
{
return _a.Pos().Equal(_b.Pos(), 1e-6) &&
_a.Rot().Equal(_b.Rot(), 1e-6);
}};
/// \brief AxisAlignedBox equality comparison function.
public: std::function<bool(const math::AxisAlignedBox &,
const math::AxisAlignedBox&)>
axisAlignedBoxEql { [](const math::AxisAlignedBox &_a,
const math::AxisAlignedBox &_b)
{
return _a == _b;
}};
/// \brief Environment variable which holds paths to look for engine plugins
public: std::string pluginPathEnv = "IGN_GAZEBO_PHYSICS_ENGINE_PATH";
//////////////////////////////////////////////////
////////////// Optional Features /////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// Slip Compliance
/// \brief Feature list to process `FrictionPyramidSlipCompliance` components.
public: struct FrictionPyramidSlipComplianceFeatureList
: physics::FeatureList<
MinimumFeatureList,
ignition::physics::GetShapeFrictionPyramidSlipCompliance,
ignition::physics::SetShapeFrictionPyramidSlipCompliance>{};
//////////////////////////////////////////////////
// Joints
/// \brief Feature list to handle joints.
public: struct JointFeatureList : ignition::physics::FeatureList<
MinimumFeatureList,
ignition::physics::GetBasicJointProperties,
ignition::physics::GetBasicJointState,
ignition::physics::SetBasicJointState,
ignition::physics::sdf::ConstructSdfJoint>{};
//////////////////////////////////////////////////
// Detachable joints
/// \brief Feature list to process `DetachableJoint` components.
public: struct DetachableJointFeatureList : physics::FeatureList<
JointFeatureList,
physics::AttachFixedJointFeature,
physics::DetachJointFeature,
physics::SetJointTransformFromParentFeature>{};
//////////////////////////////////////////////////
// Collisions
/// \brief Feature list to handle collisions.
public: struct CollisionFeatureList : ignition::physics::FeatureList<
MinimumFeatureList,
ignition::physics::GetContactsFromLastStepFeature,
ignition::physics::sdf::ConstructSdfCollision>{};
/// \brief Collision type with collision features.
public: using ShapePtrType = ignition::physics::ShapePtr<
ignition::physics::FeaturePolicy3d, CollisionFeatureList>;
/// \brief World type with just the minimum features. Non-pointer.
public: using WorldShapeType = ignition::physics::World<
ignition::physics::FeaturePolicy3d, CollisionFeatureList>;
//////////////////////////////////////////////////
// Collision filtering with bitmasks
/// \brief Feature list to filter collisions with bitmasks.
public: struct CollisionMaskFeatureList : ignition::physics::FeatureList<
CollisionFeatureList,
ignition::physics::CollisionFilterMaskFeature>{};
//////////////////////////////////////////////////
// Link force
/// \brief Feature list for applying forces to links.
public: struct LinkForceFeatureList : ignition::physics::FeatureList<
ignition::physics::AddLinkExternalForceTorque>{};
//////////////////////////////////////////////////
// Bounding box
/// \brief Feature list for model bounding box.
public: struct BoundingBoxFeatureList : ignition::physics::FeatureList<
MinimumFeatureList,
ignition::physics::GetModelBoundingBox>{};
//////////////////////////////////////////////////
// Joint velocity command
/// \brief Feature list for set joint velocity command.
public: struct JointVelocityCommandFeatureList : physics::FeatureList<
physics::SetJointVelocityCommandFeature>{};
//////////////////////////////////////////////////
// World velocity command
public: struct WorldVelocityCommandFeatureList :
ignition::physics::FeatureList<
ignition::physics::SetFreeGroupWorldVelocity>{};
//////////////////////////////////////////////////
// Meshes
/// \brief Feature list for meshes.
/// Include MinimumFeatureList so created collision can be automatically
/// up-cast.
public: struct MeshFeatureList : physics::FeatureList<
CollisionFeatureList,
physics::mesh::AttachMeshShapeFeature>{};
//////////////////////////////////////////////////
// Nested Models
/// \brief Feature list to construct nested models
public: struct NestedModelFeatureList : ignition::physics::FeatureList<
MinimumFeatureList,
ignition::physics::sdf::ConstructSdfNestedModel>{};
//////////////////////////////////////////////////
/// \brief World EntityFeatureMap
public: using WorldEntityMap = EntityFeatureMap3d<
physics::World,
MinimumFeatureList,
CollisionFeatureList,
NestedModelFeatureList>;
/// \brief A map between world entity ids in the ECM to World Entities in
/// ign-physics.
public: WorldEntityMap entityWorldMap;
/// \brief Model EntityFeatureMap
public: using ModelEntityMap = EntityFeatureMap3d<
physics::Model,
MinimumFeatureList,
JointFeatureList,
BoundingBoxFeatureList,
NestedModelFeatureList>;
/// \brief A map between model entity ids in the ECM to Model Entities in
/// ign-physics.
public: ModelEntityMap entityModelMap;
/// \brief Link EntityFeatureMap
public: using EntityLinkMap = EntityFeatureMap3d<
physics::Link,
MinimumFeatureList,
DetachableJointFeatureList,
CollisionFeatureList,
LinkForceFeatureList,
MeshFeatureList>;
/// \brief A map between link entity ids in the ECM to Link Entities in
/// ign-physics.
public: EntityLinkMap entityLinkMap;
/// \brief Joint EntityFeatureMap
public: using EntityJointMap = EntityFeatureMap3d<
physics::Joint,
JointFeatureList,
DetachableJointFeatureList,
JointVelocityCommandFeatureList
>;
/// \brief A map between joint entity ids in the ECM to Joint Entities in
/// ign-physics
public: EntityJointMap entityJointMap;
/// \brief Collision EntityFeatureMap
public: using EntityCollisionMap = EntityFeatureMap3d<
physics::Shape,
CollisionFeatureList,
CollisionMaskFeatureList,
FrictionPyramidSlipComplianceFeatureList
>;
/// \brief A map between collision entity ids in the ECM to Shape Entities in
/// ign-physics.
public: EntityCollisionMap entityCollisionMap;
/// \brief FreeGroup EntityFeatureMap
public: using EntityFreeGroupMap = EntityFeatureMap3d<
physics::FreeGroup,
MinimumFeatureList,
WorldVelocityCommandFeatureList
>;
/// \brief A map between collision entity ids in the ECM to FreeGroup Entities
/// in ign-physics.
public: EntityFreeGroupMap entityFreeGroupMap;
};
//////////////////////////////////////////////////
Physics::Physics() : System(), dataPtr(std::make_unique<PhysicsPrivate>())
{
}
//////////////////////////////////////////////////
void Physics::Configure(const Entity &_entity,
const std::shared_ptr<const sdf::Element> &_sdf,
EntityComponentManager &_ecm,
EventManager &/*_eventMgr*/)
{
std::string pluginLib;
// 1. Engine from component (from command line / ServerConfig)
auto engineComp = _ecm.Component<components::PhysicsEnginePlugin>(_entity);
if (engineComp && !engineComp->Data().empty())
{
pluginLib = engineComp->Data();
}
// 2. Engine from SDF
else if (_sdf->HasElement("engine"))
{
auto sdfClone = _sdf->Clone();
auto engineElem = sdfClone->GetElement("engine");
pluginLib = engineElem->Get<std::string>("filename", pluginLib).first;
}
// 3. Use DART by default
if (pluginLib.empty())
{
pluginLib = "libignition-physics-dartsim-plugin.so";
}
// Update component
if (!engineComp)
{
_ecm.CreateComponent(_entity, components::PhysicsEnginePlugin(pluginLib));
}
else
{
engineComp->SetData(pluginLib,
[](const std::string &_a, const std::string &_b){return _a == _b;});
}
// Find engine shared library
// Look in:
// * Paths from environment variable
// * Engines installed with ign-physics
common::SystemPaths systemPaths;
systemPaths.SetPluginPathEnv(this->dataPtr->pluginPathEnv);
systemPaths.AddPluginPaths({IGNITION_PHYSICS_ENGINE_INSTALL_DIR});
auto pathToLib = systemPaths.FindSharedLibrary(pluginLib);
if (pathToLib.empty())
{
ignerr << "Failed to find plugin [" << pluginLib
<< "]. Have you checked the " << this->dataPtr->pluginPathEnv
<< " environment variable?" << std::endl;
return;
}
// Load engine plugin
ignition::plugin::Loader pluginLoader;
auto plugins = pluginLoader.LoadLib(pathToLib);
if (plugins.empty())
{
ignerr << "Unable to load the [" << pathToLib << "] library.\n";
return;
}
auto classNames = pluginLoader.AllPlugins();
if (classNames.empty())
{
ignerr << "No plugins found in library [" << pathToLib << "]." << std::endl;
return;
}
// Get the first plugin that works
for (auto className : classNames)
{
auto plugin = pluginLoader.Instantiate(className);
if (!plugin)
continue;
this->dataPtr->engine = ignition::physics::RequestEngine<
ignition::physics::FeaturePolicy3d,
PhysicsPrivate::MinimumFeatureList>::From(plugin);
if (nullptr != this->dataPtr->engine)
{
igndbg << "Loaded [" << className << "] from library ["
<< pathToLib << "]" << std::endl;
break;
}
auto missingFeatures = ignition::physics::RequestEngine<
ignition::physics::FeaturePolicy3d,
PhysicsPrivate::MinimumFeatureList>::MissingFeatureNames(plugin);
std::stringstream msg;
msg << "Plugin [" << className << "] misses required features:"
<< std::endl;
for (auto feature : missingFeatures)
{
msg << "- " << feature << std::endl;
}
ignwarn << msg.str();
}
if (nullptr == this->dataPtr->engine)
{
ignerr << "Failed to load a valid physics engine from [" << pathToLib
<< "]."
<< std::endl;
}
}
//////////////////////////////////////////////////
Physics::~Physics() = default;
//////////////////////////////////////////////////
void Physics::Update(const UpdateInfo &_info, EntityComponentManager &_ecm)
{
IGN_PROFILE("Physics::Update");
// \TODO(anyone) Support rewind
if (_info.dt < std::chrono::steady_clock::duration::zero())
{
ignwarn << "Detected jump back in time ["
<< std::chrono::duration_cast<std::chrono::seconds>(_info.dt).count()
<< "s]. System may not work properly." << std::endl;
}
if (this->dataPtr->engine)
{
this->dataPtr->CreatePhysicsEntities(_ecm);
this->dataPtr->UpdatePhysics(_ecm);
ignition::physics::ForwardStep::Output stepOutput;
// Only step if not paused.
if (!_info.paused)
{
stepOutput = this->dataPtr->Step(_info.dt);
}
auto changedLinks = this->dataPtr->ChangedLinks(_ecm, stepOutput);
this->dataPtr->UpdateSim(_ecm, changedLinks);
// Entities scheduled to be removed should be removed from physics after the
// simulation step. Otherwise, since the to-be-removed entity still shows up
// in the ECM::Each the UpdatePhysics and UpdateSim calls will have an error
this->dataPtr->RemovePhysicsEntities(_ecm);
}
}
//////////////////////////////////////////////////
void PhysicsPrivate::CreatePhysicsEntities(const EntityComponentManager &_ecm)
{
// Get all the new worlds
_ecm.EachNew<components::World, components::Name, components::Gravity>(
[&](const Entity &_entity,
const components::World * /* _world */,
const components::Name *_name,
const components::Gravity *_gravity)->bool
{
// Check if world already exists
if (this->entityWorldMap.HasEntity(_entity))
{
ignwarn << "World entity [" << _entity
<< "] marked as new, but it's already on the map."
<< std::endl;
return true;
}
sdf::World world;
world.SetName(_name->Data());
world.SetGravity(_gravity->Data());
auto worldPtrPhys = this->engine->ConstructWorld(world);
this->entityWorldMap.AddEntity(_entity, worldPtrPhys);
return true;
});
_ecm.EachNew<components::Model, components::Name, components::Pose,
components::ParentEntity>(
[&](const Entity &_entity,
const components::Model *,
const components::Name *_name,
const components::Pose *_pose,
const components::ParentEntity *_parent)->bool
{
// Check if model already exists
if (this->entityModelMap.HasEntity(_entity))
{
ignwarn << "Model entity [" << _entity
<< "] marked as new, but it's already on the map."
<< std::endl;
return true;
}
// TODO(anyone) Don't load models unless they have collisions
// Check if parent world / model exists
sdf::Model model;
model.SetName(_name->Data());
model.SetRawPose(_pose->Data());
auto staticComp = _ecm.Component<components::Static>(_entity);
if (staticComp && staticComp->Data())
{
model.SetStatic(staticComp->Data());
this->staticEntities.insert(_entity);
}
auto selfCollideComp = _ecm.Component<components::SelfCollide>(_entity);
if (selfCollideComp && selfCollideComp ->Data())
{
model.SetSelfCollide(selfCollideComp->Data());
}
// check if parent is a world
if (auto worldPtrPhys =
this->entityWorldMap.Get(_parent->Data()))
{
// Use the ConstructNestedModel feature for nested models
if (model.ModelCount() > 0)
{
auto nestedModelFeature =
this->entityWorldMap.EntityCast<NestedModelFeatureList>(
_parent->Data());
if (!nestedModelFeature)
{
static bool informed{false};
if (!informed)
{
igndbg << "Attempting to construct nested models, but the "
<< "phyiscs engine doesn't support feature "
<< "[ConstructSdfNestedModelFeature]. "
<< "Nested model will be ignored."
<< std::endl;
informed = true;
}
return true;
}
auto modelPtrPhys = nestedModelFeature->ConstructNestedModel(model);
this->entityModelMap.AddEntity(_entity, modelPtrPhys);
this->topLevelModelMap.insert(std::make_pair(_entity,
topLevelModel(_entity, _ecm)));
}
else
{
auto modelPtrPhys = worldPtrPhys->ConstructModel(model);
this->entityModelMap.AddEntity(_entity, modelPtrPhys);
this->topLevelModelMap.insert(std::make_pair(_entity,
topLevelModel(_entity, _ecm)));
}
}
// check if parent is a model (nested model)
else
{
if (auto parentPtrPhys = this->entityModelMap.Get(_parent->Data()))
{
auto nestedModelFeature =
this->entityModelMap.EntityCast<NestedModelFeatureList>(
_parent->Data());
if (!nestedModelFeature)
{
static bool informed{false};
if (!informed)
{
igndbg << "Attempting to construct nested models, but the "
<< "physics engine doesn't support feature "
<< "[ConstructSdfNestedModelFeature]. "
<< "Nested model will be ignored."
<< std::endl;
informed = true;
}
return true;
}
// override static property only if parent is static.
auto parentStaticComp =
_ecm.Component<components::Static>(_parent->Data());
if (parentStaticComp && parentStaticComp->Data())
{
model.SetStatic(true);
this->staticEntities.insert(_entity);
}
auto modelPtrPhys = nestedModelFeature->ConstructNestedModel(model);
if (modelPtrPhys)
{
this->entityModelMap.AddEntity(_entity, modelPtrPhys);
this->topLevelModelMap.insert(std::make_pair(_entity,
topLevelModel(_entity, _ecm)));
}
else
{
ignerr << "Model: '" << _name->Data() << "' not loaded. "
<< "Failed to create nested model."
<< std::endl;
}
}
else
{
ignwarn << "Model's parent entity [" << _parent->Data()
<< "] not found on world / model map." << std::endl;
return true;
}
}
return true;
});
_ecm.EachNew<components::Link, components::Name, components::Pose,
components::ParentEntity>(
[&](const Entity &_entity,
const components::Link * /* _link */,
const components::Name *_name,
const components::Pose *_pose,
const components::ParentEntity *_parent)->bool
{
// Check if link already exists
if (this->entityLinkMap.HasEntity(_entity))
{
ignwarn << "Link entity [" << _entity
<< "] marked as new, but it's already on the map."
<< std::endl;
return true;
}
// TODO(anyone) Don't load links unless they have collisions
// Check if parent model exists
if (!this->entityModelMap.HasEntity(_parent->Data()))
{
ignwarn << "Link's parent entity [" << _parent->Data()
<< "] not found on model map." << std::endl;
return true;
}
auto modelPtrPhys =
this->entityModelMap.Get(_parent->Data());
sdf::Link link;
link.SetName(_name->Data());
link.SetRawPose(_pose->Data());
if (this->staticEntities.find(_parent->Data()) !=
this->staticEntities.end())
{
this->staticEntities.insert(_entity);
}
// get link inertial
auto inertial = _ecm.Component<components::Inertial>(_entity);
if (inertial)
{
link.SetInertial(inertial->Data());
}
auto linkPtrPhys = modelPtrPhys->ConstructLink(link);
this->entityLinkMap.AddEntity(_entity, linkPtrPhys);
this->topLevelModelMap.insert(std::make_pair(_entity,
topLevelModel(_entity, _ecm)));
return true;
});
// We don't need to add visuals to the physics engine.
// collisions
_ecm.EachNew<components::Collision, components::Name, components::Pose,
components::Geometry, components::CollisionElement,
components::ParentEntity>(
[&](const Entity &_entity,
const components::Collision *,
const components::Name *_name,
const components::Pose *_pose,
const components::Geometry *_geom,
const components::CollisionElement *_collElement,
const components::ParentEntity *_parent) -> bool
{
if (this->entityCollisionMap.HasEntity(_entity))
{
ignwarn << "Collision entity [" << _entity
<< "] marked as new, but it's already on the map."
<< std::endl;
return true;
}
// Check if parent link exists
if (!this->entityLinkMap.HasEntity(_parent->Data()))
{
ignwarn << "Collision's parent entity [" << _parent->Data()
<< "] not found on link map." << std::endl;
return true;
}
auto linkPtrPhys = this->entityLinkMap.Get(_parent->Data());
// Make a copy of the collision DOM so we can set its pose which has
// been resolved and is now expressed w.r.t the parent link of the
// collision.
sdf::Collision collision = _collElement->Data();
collision.SetRawPose(_pose->Data());
collision.SetPoseRelativeTo("");
auto collideBitmask = collision.Surface()->Contact()->CollideBitmask();
ShapePtrType collisionPtrPhys;
if (_geom->Data().Type() == sdf::GeometryType::MESH)
{
const sdf::Mesh *meshSdf = _geom->Data().MeshShape();
if (nullptr == meshSdf)
{
ignwarn << "Mesh geometry for collision [" << _name->Data()
<< "] missing mesh shape." << std::endl;
return true;
}
auto &meshManager = *ignition::common::MeshManager::Instance();
auto fullPath = asFullPath(meshSdf->Uri(), meshSdf->FilePath());
auto *mesh = meshManager.Load(fullPath);
if (nullptr == mesh)
{
ignwarn << "Failed to load mesh from [" << fullPath
<< "]." << std::endl;
return true;
}
auto linkMeshFeature =
this->entityLinkMap.EntityCast<MeshFeatureList>(_parent->Data());
if (!linkMeshFeature)
{
static bool informed{false};
if (!informed)
{
igndbg << "Attempting to process mesh geometries, but the physics"
<< " engine doesn't support feature "
<< "[AttachMeshShapeFeature]. Meshes will be ignored."
<< std::endl;
informed = true;
}
return true;
}
collisionPtrPhys = linkMeshFeature->AttachMeshShape(_name->Data(),
*mesh,
math::eigen3::convert(_pose->Data()),
math::eigen3::convert(meshSdf->Scale()));
}
else
{
auto linkCollisionFeature =
this->entityLinkMap.EntityCast<CollisionFeatureList>(
_parent->Data());
if (!linkCollisionFeature)
{
static bool informed{false};
if (!informed)
{
igndbg << "Attempting to process collisions, but the physics "
<< "engine doesn't support feature "
<< "[ConstructSdfCollision]. Collisions will be ignored."
<< std::endl;
informed = true;
}
return true;
}
collisionPtrPhys =
linkCollisionFeature->ConstructCollision(collision);
}
this->entityCollisionMap.AddEntity(_entity, collisionPtrPhys);
// Check that the physics engine has a filter mask feature
// Set the collide_bitmask if it does
auto filterMaskFeature =
this->entityCollisionMap.EntityCast<CollisionMaskFeatureList>(
_entity);
if (filterMaskFeature)
{
filterMaskFeature->SetCollisionFilterMask(collideBitmask);
}
else
{
static bool informed{false};
if (!informed)
{
igndbg << "Attempting to set collision bitmasks, but the physics "
<< "engine doesn't support feature [CollisionFilterMask]. "
<< "Collision bitmasks will be ignored." << std::endl;
informed = true;
}
}
this->topLevelModelMap.insert(std::make_pair(_entity,
topLevelModel(_entity, _ecm)));
return true;
});
// joints
_ecm.EachNew<components::Joint, components::Name, components::JointType,
components::Pose, components::ThreadPitch,
components::ParentEntity, components::ParentLinkName,
components::ChildLinkName>(
[&](const Entity &_entity,
const components::Joint * /* _joint */,
const components::Name *_name,
const components::JointType *_jointType,
const components::Pose *_pose,
const components::ThreadPitch *_threadPitch,
const components::ParentEntity *_parentModel,
const components::ParentLinkName *_parentLinkName,
const components::ChildLinkName *_childLinkName) -> bool
{
// Check if joint already exists
if (this->entityJointMap.HasEntity(_entity))
{
ignwarn << "Joint entity [" << _entity
<< "] marked as new, but it's already on the map."
<< std::endl;
return true;
}
// Check if parent model exists
if (!this->entityModelMap.HasEntity(_parentModel->Data()))
{
ignwarn << "Joint's parent entity [" << _parentModel->Data()
<< "] not found on model map." << std::endl;
return true;