-
Notifications
You must be signed in to change notification settings - Fork 268
/
RenderUtil.cc
1730 lines (1530 loc) · 58.2 KB
/
RenderUtil.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) 2019 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 <map>
#include <string>
#include <tuple>
#include <unordered_map>
#include <variant>
#include <vector>
#include <sdf/Actor.hh>
#include <sdf/Collision.hh>
#include <sdf/Element.hh>
#include <sdf/Light.hh>
#include <sdf/Link.hh>
#include <sdf/Model.hh>
#include <sdf/parser.hh>
#include <sdf/Scene.hh>
#include <sdf/SDFImpl.hh>
#include <sdf/Visual.hh>
#include <ignition/common/Profiler.hh>
#include <ignition/common/Skeleton.hh>
#include <ignition/common/SkeletonAnimation.hh>
#include <ignition/math/Color.hh>
#include <ignition/math/Helpers.hh>
#include <ignition/math/Matrix4.hh>
#include <ignition/math/Pose3.hh>
#include <ignition/rendering.hh>
#include <ignition/rendering/RenderEngine.hh>
#include <ignition/rendering/RenderingIface.hh>
#include <ignition/rendering/Scene.hh>
#include "ignition/gazebo/components/Actor.hh"
#include "ignition/gazebo/components/Camera.hh"
#include "ignition/gazebo/components/CastShadows.hh"
#include "ignition/gazebo/components/Collision.hh"
#include "ignition/gazebo/components/DepthCamera.hh"
#include "ignition/gazebo/components/GpuLidar.hh"
#include "ignition/gazebo/components/Geometry.hh"
#include "ignition/gazebo/components/Light.hh"
#include "ignition/gazebo/components/Link.hh"
#include "ignition/gazebo/components/Material.hh"
#include "ignition/gazebo/components/Model.hh"
#include "ignition/gazebo/components/Name.hh"
#include "ignition/gazebo/components/ParentEntity.hh"
#include "ignition/gazebo/components/Pose.hh"
#include "ignition/gazebo/components/RgbdCamera.hh"
#include "ignition/gazebo/components/Scene.hh"
#include "ignition/gazebo/components/SourceFilePath.hh"
#include "ignition/gazebo/components/Temperature.hh"
#include "ignition/gazebo/components/TemperatureRange.hh"
#include "ignition/gazebo/components/ThermalCamera.hh"
#include "ignition/gazebo/components/Transparency.hh"
#include "ignition/gazebo/components/Visibility.hh"
#include "ignition/gazebo/components/Visual.hh"
#include "ignition/gazebo/components/World.hh"
#include "ignition/gazebo/EntityComponentManager.hh"
#include "ignition/gazebo/rendering/RenderUtil.hh"
#include "ignition/gazebo/rendering/SceneManager.hh"
#include "ignition/gazebo/rendering/MarkerManager.hh"
#include "ignition/gazebo/Util.hh"
using namespace ignition;
using namespace gazebo;
// Private data class.
class ignition::gazebo::RenderUtilPrivate
{
/// True if the rendering component is initialized
public: bool initialized = false;
/// \brief Create rendering entities
/// \param[in] _ecm The entity-component manager
public: void CreateRenderingEntities(const EntityComponentManager &_ecm,
const UpdateInfo &_info);
/// \brief Remove rendering entities
/// \param[in] _ecm The entity-component manager
public: void RemoveRenderingEntities(const EntityComponentManager &_ecm,
const UpdateInfo &_info);
/// \brief Update rendering entities
/// \param[in] _ecm The entity-component manager
public: void UpdateRenderingEntities(const EntityComponentManager &_ecm);
/// \brief Total time elapsed in simulation. This will not increase while
/// paused.
public: std::chrono::steady_clock::duration simTime{0};
/// \brief Name of rendering engine
public: std::string engineName = "ogre2";
/// \brief Name of scene
public: std::string sceneName = "scene";
/// \brief Scene background color
public: math::Color backgroundColor = math::Color::Black;
/// \brief Ambient color
public: math::Color ambientLight = math::Color(1.0, 1.0, 1.0, 1.0);
/// \brief Scene manager
public: SceneManager sceneManager;
/// \brief Marker manager
public: MarkerManager markerManager;
/// \brief Pointer to rendering engine.
public: ignition::rendering::RenderEngine *engine{nullptr};
/// \brief rendering scene to be managed by the scene manager and used to
/// generate sensor data
public: rendering::ScenePtr scene;
/// \brief Flag to indicate if the current GL context should be used
public: bool useCurrentGLContext = false;
/// \brief New scenes to be created
public: std::vector<sdf::Scene> newScenes;
/// \brief New models to be created. The elements in the tuple are:
/// [0] entity id, [1], SDF DOM, [2] parent entity id, [3] sim iteration
public: std::vector<std::tuple<Entity, sdf::Model, Entity, uint64_t>>
newModels;
/// \brief New links to be created. The elements in the tuple are:
/// [0] entity id, [1], SDF DOM, [2] parent entity id
public: std::vector<std::tuple<Entity, sdf::Link, Entity>> newLinks;
/// \brief New visuals to be created. The elements in the tuple are:
/// [0] entity id, [1], SDF DOM, [2] parent entity id
public: std::vector<std::tuple<Entity, sdf::Visual, Entity>> newVisuals;
/// \brief New actors to be created. The elements in the tuple are:
/// [0] entity id, [1], SDF DOM, [2] parent entity id
public: std::vector<std::tuple<Entity, sdf::Actor, Entity>> newActors;
/// \brief New lights to be created. The elements in the tuple are:
/// [0] entity id, [1], SDF DOM, [2] parent entity id
public: std::vector<std::tuple<Entity, sdf::Light, Entity>> newLights;
/// \brief New sensors to be created. The elements in the tuple are:
/// [0] entity id, [1], SDF DOM, [2] parent entity id
public: std::vector<std::tuple<Entity, sdf::Sensor, Entity>>
newSensors;
/// \brief Map of ids of entites to be removed and sim iteration when the
/// remove request is received
public: std::unordered_map<Entity, uint64_t> removeEntities;
/// \brief A map of entity ids and pose updates.
public: std::unordered_map<Entity, math::Pose3d> entityPoses;
/// \brief A map of entity ids and actor transforms.
public: std::map<Entity, std::map<std::string, math::Matrix4d>>
actorTransforms;
/// \brief A map of entity ids and temperature data.
/// The value of this map (tuple) represents either a single (uniform)
/// temperature, or a heat signature with a min/max temperature. If the string
/// in the tuple is empty, then this entity has a uniform temperature across
/// its surface, and this uniform temperature is stored in the first float of
/// the tuple (the second float and string are unused for uniform temperature
/// entities). If the string in the tuple is not empty, then the string
/// represents the entity's heat signature (a path to a heat signature texture
/// file), and the floats represent the min/max temperatures of the heat
/// signature, respectively.
///
/// All temperatures are in Kelvin.
public: std::map<Entity, std::tuple<float, float, std::string>> entityTemp;
/// \brief A map of entity ids and wire boxes
public: std::unordered_map<Entity, ignition::rendering::WireBoxPtr> wireBoxes;
/// \brief A map of entity ids and trajectory pose updates.
public: std::unordered_map<Entity, math::Pose3d> trajectoryPoses;
/// \brief A map of entity ids and actor animation info.
public: std::unordered_map<Entity, AnimationUpdateData> actorAnimationData;
/// \brief True to update skeletons manually using bone poses
/// (see actorTransforms). False to let render engine update animation
/// based on sim time.
/// \todo(anyone) Let this be turned on from a component
public: bool actorManualSkeletonUpdate = false;
/// \brief Mutex to protect updates
public: std::mutex updateMutex;
//// \brief Flag to indicate whether to create sensors
public: bool enableSensors = false;
/// \brief A set containing all the entities with attached rendering sensors
public: std::unordered_set<Entity> sensorEntities;
/// \brief Callback function for creating sensors.
/// The function args are: entity id, sensor sdf, and parent name.
/// The function returns the id of the rendering sensor created.
public: std::function<std::string(const gazebo::Entity &, const sdf::Sensor &,
const std::string &)> createSensorCb;
/// \brief Callback function for removing sensors.
/// The function arg is the entity id
public: std::function<void(const gazebo::Entity &)> removeSensorCb;
/// \brief Currently selected entities, organized by order of selection.
public: std::vector<Entity> selectedEntities;
/// \brief Map of original emissive colors for nodes currently highlighted.
public: std::map<std::string, math::Color> originalEmissive;
/// \brief Whether the transform gizmo is being dragged.
public: bool transformActive{false};
/// \brief Highlight a node and all its children.
/// \param[in] _node Node to be highlighted
public: void HighlightNode(const rendering::NodePtr &_node);
/// \brief Restore a highlighted node to normal.
/// \param[in] _node Node to be restored.
public: void LowlightNode(const rendering::NodePtr &_node);
/// \brief New collisions to be created
public: std::vector<Entity> newCollisions;
/// \brief Finds the links (collision parent) that are used to create child
/// collision visuals in RenderUtil::Update
/// \param[in] _ecm The entity-component manager
public: void FindCollisionLinks(const EntityComponentManager &_ecm);
/// \brief A list of links used to create new collision visuals
public: std::vector<Entity> newCollisionLinks;
/// \brief A map of collision entity ids and their SDF DOM
public: std::map<Entity, sdf::Collision> entityCollisions;
/// \brief A map of model entities and their corresponding children links
public: std::map<Entity, std::vector<Entity>> modelToLinkEntities;
/// \brief A map of link entities and their corresponding children collisions
public: std::map<Entity, std::vector<Entity>> linkToCollisionEntities;
/// \brief A map of created collision entities and if they are currently
/// visible
public: std::map<Entity, bool> viewingCollisions;
};
//////////////////////////////////////////////////
RenderUtil::RenderUtil() : dataPtr(std::make_unique<RenderUtilPrivate>())
{
}
//////////////////////////////////////////////////
RenderUtil::~RenderUtil() = default;
//////////////////////////////////////////////////
rendering::ScenePtr RenderUtil::Scene() const
{
return this->dataPtr->scene;
}
//////////////////////////////////////////////////
void RenderUtil::UpdateFromECM(const UpdateInfo &_info,
const EntityComponentManager &_ecm)
{
IGN_PROFILE("RenderUtil::UpdateFromECM");
std::lock_guard<std::mutex> lock(this->dataPtr->updateMutex);
this->dataPtr->simTime = _info.simTime;
this->dataPtr->CreateRenderingEntities(_ecm, _info);
this->dataPtr->UpdateRenderingEntities(_ecm);
this->dataPtr->RemoveRenderingEntities(_ecm, _info);
this->dataPtr->markerManager.SetSimTime(_info.simTime);
this->dataPtr->FindCollisionLinks(_ecm);
}
//////////////////////////////////////////////////
void RenderUtilPrivate::FindCollisionLinks(const EntityComponentManager &_ecm)
{
if (this->newCollisions.empty())
return;
for (const auto &entity : this->newCollisions)
{
std::vector<Entity> links;
if (_ecm.EntityMatches(entity,
std::set<ComponentTypeId>{components::Model::typeId}))
{
links = _ecm.EntitiesByComponents(components::ParentEntity(entity),
components::Link());
}
else if (_ecm.EntityMatches(entity,
std::set<ComponentTypeId>{components::Link::typeId}))
{
links.push_back(entity);
}
else
{
ignerr << "Entity [" << entity
<< "] for viewing collision must be a model or link"
<< std::endl;
continue;
}
this->newCollisionLinks.insert(this->newCollisionLinks.end(),
links.begin(),
links.end());
}
this->newCollisions.clear();
}
//////////////////////////////////////////////////
int RenderUtil::PendingSensors() const
{
if (!this->dataPtr->initialized)
return -1;
if (!this->dataPtr->scene)
return -1;
this->dataPtr->updateMutex.lock();
int nSensors = this->dataPtr->newSensors.size();
this->dataPtr->updateMutex.unlock();
return nSensors;
}
//////////////////////////////////////////////////
void RenderUtil::Update()
{
IGN_PROFILE("RenderUtil::Update");
if (!this->dataPtr->initialized)
return;
if (!this->dataPtr->scene)
return;
this->dataPtr->updateMutex.lock();
auto newScenes = std::move(this->dataPtr->newScenes);
auto newModels = std::move(this->dataPtr->newModels);
auto newLinks = std::move(this->dataPtr->newLinks);
auto newVisuals = std::move(this->dataPtr->newVisuals);
auto newActors = std::move(this->dataPtr->newActors);
auto newLights = std::move(this->dataPtr->newLights);
auto removeEntities = std::move(this->dataPtr->removeEntities);
auto entityPoses = std::move(this->dataPtr->entityPoses);
auto trajectoryPoses = std::move(this->dataPtr->trajectoryPoses);
auto actorTransforms = std::move(this->dataPtr->actorTransforms);
auto actorAnimationData = std::move(this->dataPtr->actorAnimationData);
auto entityTemp = std::move(this->dataPtr->entityTemp);
auto newCollisionLinks = std::move(this->dataPtr->newCollisionLinks);
this->dataPtr->newScenes.clear();
this->dataPtr->newModels.clear();
this->dataPtr->newLinks.clear();
this->dataPtr->newVisuals.clear();
this->dataPtr->newActors.clear();
this->dataPtr->newLights.clear();
this->dataPtr->removeEntities.clear();
this->dataPtr->entityPoses.clear();
this->dataPtr->trajectoryPoses.clear();
this->dataPtr->actorTransforms.clear();
this->dataPtr->actorAnimationData.clear();
this->dataPtr->entityTemp.clear();
this->dataPtr->newCollisionLinks.clear();
this->dataPtr->markerManager.Update();
std::vector<std::tuple<Entity, sdf::Sensor, Entity>> newSensors;
if (this->dataPtr->enableSensors)
{
newSensors = std::move(this->dataPtr->newSensors);
this->dataPtr->newSensors.clear();
}
this->dataPtr->updateMutex.unlock();
// scene - only one scene is supported for now
// extend the sensor system to support mutliple scenes in the future
for (auto &scene : newScenes)
{
this->dataPtr->scene->SetAmbientLight(scene.Ambient());
this->dataPtr->scene->SetBackgroundColor(scene.Background());
if (scene.Grid() && !this->dataPtr->enableSensors)
this->ShowGrid();
// only one scene so break
break;
}
// remove existing entities
{
IGN_PROFILE("RenderUtil::Update Remove");
for (auto &entity : removeEntities)
{
auto node = this->dataPtr->sceneManager.NodeById(entity.first);
this->dataPtr->selectedEntities.erase(std::remove(
this->dataPtr->selectedEntities.begin(),
this->dataPtr->selectedEntities.end(), entity.first),
this->dataPtr->selectedEntities.end());
this->dataPtr->sceneManager.RemoveEntity(entity.first);
// delete associated sensor, if existing
auto sensorEntityIt = this->dataPtr->sensorEntities.find(entity.first);
if (sensorEntityIt != this->dataPtr->sensorEntities.end())
{
this->dataPtr->removeSensorCb(entity.first);
this->dataPtr->sensorEntities.erase(sensorEntityIt);
}
}
}
// create new entities
{
IGN_PROFILE("RenderUtil::Update Create");
for (const auto &model : newModels)
{
uint64_t iteration = std::get<3>(model);
Entity entityId = std::get<0>(model);
// since entites to be created and removed are queued, we need
// to check their creation timestamp to make sure we do not create a new
// entity when there is also a remove request with a more recent
// timestamp
// \todo(anyone) add test to check scene entities are properly added
// and removed.
auto removeIt = removeEntities.find(entityId);
if (removeIt != removeEntities.end())
{
uint64_t removeIteration = removeIt->second;
if (iteration < removeIteration)
continue;
}
this->dataPtr->sceneManager.CreateModel(
entityId, std::get<1>(model), std::get<2>(model));
}
for (const auto &link : newLinks)
{
this->dataPtr->sceneManager.CreateLink(
std::get<0>(link), std::get<1>(link), std::get<2>(link));
}
for (const auto &visual : newVisuals)
{
this->dataPtr->sceneManager.CreateVisual(
std::get<0>(visual), std::get<1>(visual), std::get<2>(visual));
}
for (const auto &actor : newActors)
{
this->dataPtr->sceneManager.CreateActor(
std::get<0>(actor), std::get<1>(actor), std::get<2>(actor));
}
for (const auto &light : newLights)
{
this->dataPtr->sceneManager.CreateLight(
std::get<0>(light), std::get<1>(light), std::get<2>(light));
}
if (this->dataPtr->enableSensors && this->dataPtr->createSensorCb)
{
for (const auto &sensor : newSensors)
{
Entity entity = std::get<0>(sensor);
const sdf::Sensor &dataSdf = std::get<1>(sensor);
Entity parent = std::get<2>(sensor);
// two sensors with the same name cause conflicts. We'll need to use
// scoped names
// TODO(anyone) do this in ign-sensors?
auto parentNode = this->dataPtr->sceneManager.NodeById(parent);
if (!parentNode)
{
ignerr << "Failed to create sensor with name[" << dataSdf.Name()
<< "] for entity [" << entity
<< "]. Parent not found with ID[" << parent << "]."
<< std::endl;
continue;
}
std::string sensorName =
this->dataPtr->createSensorCb(entity, dataSdf, parentNode->Name());
// Add to the system's scene manager
if (!this->dataPtr->sceneManager.AddSensor(entity, sensorName, parent))
{
ignerr << "Failed to create sensor [" << sensorName << "]"
<< std::endl;
}
}
}
}
// update entities' pose
{
IGN_PROFILE("RenderUtil::Update Poses");
for (const auto &pose : entityPoses)
{
auto node = this->dataPtr->sceneManager.NodeById(pose.first);
if (!node)
continue;
// Don't move entity being manipulated (last selected)
// TODO(anyone) Check top level visual instead of parent
auto vis = std::dynamic_pointer_cast<rendering::Visual>(node);
int updateNode = 0;
Entity entityId = kNullEntity;
if (vis)
{
// Get information from the visual's user data to indicate if
// the render thread should pause updating it's true location,
// this functionality is needed for temporal placement of a
// visual such as an align preview
updateNode = std::get<int>(vis->UserData("pause-update"));
entityId = std::get<int>(vis->UserData("gazebo-entity"));
}
if ((this->dataPtr->transformActive &&
(pose.first == this->dataPtr->selectedEntities.back() ||
entityId == this->dataPtr->selectedEntities.back())) ||
updateNode)
{
continue;
}
node->SetLocalPose(pose.second);
}
// update entities' local transformations
if (this->dataPtr->actorManualSkeletonUpdate)
{
for (auto &tf : actorTransforms)
{
auto actorMesh = this->dataPtr->sceneManager.ActorMeshById(tf.first);
auto actorVisual = this->dataPtr->sceneManager.NodeById(tf.first);
if (!actorMesh || !actorVisual)
{
ignerr << "Actor with Entity ID '" << tf.first << "'. not found. "
<< "Skipping skeleton animation update." << std::endl;
continue;
}
math::Pose3d globalPose;
if (entityPoses.find(tf.first) != entityPoses.end())
{
globalPose = entityPoses[tf.first];
}
math::Pose3d trajPose;
// Trajectory from the ECS
if (trajectoryPoses.find(tf.first) != trajectoryPoses.end())
{
trajPose = trajectoryPoses[tf.first];
}
// Trajectory from the SDF script
else
{
trajPose.Pos() = tf.second["actorPose"].Translation();
trajPose.Rot() = tf.second["actorPose"].Rotation();
}
actorVisual->SetLocalPose(trajPose + globalPose);
tf.second.erase("actorPose");
actorMesh->SetSkeletonLocalTransforms(tf.second);
}
}
else
{
for (auto &it : actorAnimationData)
{
auto actorMesh = this->dataPtr->sceneManager.ActorMeshById(it.first);
auto actorVisual = this->dataPtr->sceneManager.NodeById(it.first);
auto actorSkel = this->dataPtr->sceneManager.ActorSkeletonById(
it.first);
if (!actorMesh || !actorVisual || !actorSkel)
{
ignerr << "Actor with Entity ID '" << it.first << "'. not found. "
<< "Skipping skeleton animation update." << std::endl;
continue;
}
AnimationUpdateData &animData = it.second;
if (!animData.valid)
{
ignerr << "invalid animation update data" << std::endl;
continue;
}
// Enable skeleton animation
if (!actorMesh->SkeletonAnimationEnabled(animData.animationName))
{
// disable all animations for this actor
for (unsigned int i = 0; i < actorSkel->AnimationCount(); ++i)
{
actorMesh->SetSkeletonAnimationEnabled(
actorSkel->Animation(i)->Name(), false, false, 0.0);
}
// enable requested animation
actorMesh->SetSkeletonAnimationEnabled(
animData.animationName, true, animData.loop);
// Set skeleton root node weight to zero so it is not affected by
// the animation being played. This is needed if trajectory animation
// is enabled. We need to let the trajectory animation set the
// position of the actor instead
common::SkeletonPtr skeleton =
this->dataPtr->sceneManager.ActorSkeletonById(it.first);
if (skeleton)
{
float rootBoneWeight = (animData.followTrajectory) ? 0.0 : 1.0;
std::unordered_map<std::string, float> weights;
weights[skeleton->RootNode()->Name()] = rootBoneWeight;
actorMesh->SetSkeletonWeights(weights);
}
}
// Update skeleton animation by setting animation time.
// Note that animation time is different from sim time. An actor can
// have multiple animations. Animation time is associated with
// current animation that is being played. It is also adjusted if
// interpotate_x is enabled.
actorMesh->UpdateSkeletonAnimation(animData.time);
// manually update root transform in order to sync with trajectory
// animation
if (animData.followTrajectory)
{
common::SkeletonPtr skeleton =
this->dataPtr->sceneManager.ActorSkeletonById(it.first);
std::map<std::string, math::Matrix4d> rootTf;
rootTf[skeleton->RootNode()->Name()] = animData.rootTransform;
actorMesh->SetSkeletonLocalTransforms(rootTf);
}
// update actor trajectory animation
math::Pose3d globalPose;
if (entityPoses.find(it.first) != entityPoses.end())
{
globalPose = entityPoses[it.first];
}
math::Pose3d trajPose;
// Trajectory from the ECS
if (trajectoryPoses.find(it.first) != trajectoryPoses.end())
{
trajPose = trajectoryPoses[it.first];
}
else
{
// trajectory from sdf script
common::PoseKeyFrame poseFrame(0.0);
if (animData.followTrajectory)
animData.trajectory.Waypoints()->InterpolatedKeyFrame(poseFrame);
trajPose.Pos() = poseFrame.Translation();
trajPose.Rot() = poseFrame.Rotation();
}
actorVisual->SetLocalPose(trajPose + globalPose);
}
}
}
// set visual temperature
for (const auto &temp : entityTemp)
{
auto node = this->dataPtr->sceneManager.NodeById(temp.first);
if (!node)
continue;
auto visual =
std::dynamic_pointer_cast<rendering::Visual>(node);
if (!visual)
continue;
const auto &heatSignature = std::get<2>(temp.second);
if (heatSignature.empty())
visual->SetUserData("temperature", std::get<0>(temp.second));
else
{
visual->SetUserData("minTemp", std::get<0>(temp.second));
visual->SetUserData("maxTemp", std::get<1>(temp.second));
visual->SetUserData("temperature", heatSignature);
}
}
// create new collision visuals
{
for (const auto &link : newCollisionLinks)
{
std::vector<Entity> colEntities =
this->dataPtr->linkToCollisionEntities[link];
for (const auto &colEntity : colEntities)
{
if (!this->dataPtr->sceneManager.HasEntity(colEntity))
{
auto vis = this->dataPtr->sceneManager.CreateCollision(colEntity,
this->dataPtr->entityCollisions[colEntity], link);
this->dataPtr->viewingCollisions[colEntity] = true;
// add geometry material to originalEmissive map
for (auto g = 0u; g < vis->GeometryCount(); ++g)
{
auto geom = vis->GeometryByIndex(g);
// Geometry material
auto geomMat = geom->Material();
if (nullptr == geomMat)
continue;
if (this->dataPtr->originalEmissive.find(geom->Name()) ==
this->dataPtr->originalEmissive.end())
{
this->dataPtr->originalEmissive[geom->Name()] =
geomMat->Emissive();
}
}
}
}
}
}
}
//////////////////////////////////////////////////
void RenderUtilPrivate::CreateRenderingEntities(
const EntityComponentManager &_ecm, const UpdateInfo &_info)
{
IGN_PROFILE("RenderUtilPrivate::CreateRenderingEntities");
auto addNewSensor = [&_ecm, this](Entity _entity, const sdf::Sensor &_sdfData,
Entity _parent,
const std::string &_topicSuffix)
{
sdf::Sensor sdfDataCopy(_sdfData);
std::string sensorScopedName =
removeParentScope(scopedName(_entity, _ecm, "::", false), "::");
sdfDataCopy.SetName(sensorScopedName);
// check topic
if (sdfDataCopy.Topic().empty())
{
sdfDataCopy.SetTopic(scopedName(_entity, _ecm) + _topicSuffix);
}
this->newSensors.push_back(
std::make_tuple(_entity, std::move(sdfDataCopy), _parent));
this->sensorEntities.insert(_entity);
};
const std::string cameraSuffix{"/image"};
const std::string depthCameraSuffix{"/depth_image"};
const std::string rgbdCameraSuffix{""};
const std::string thermalCameraSuffix{""};
const std::string gpuLidarSuffix{"/scan"};
// Treat all pre-existent entities as new at startup
// TODO(anyone) refactor Each and EachNew below to reduce duplicate code
if (!this->initialized)
{
// Get all the new worlds
// TODO(anyone) Only one scene is supported for now
// extend the sensor system to support mutliple scenes in the future
_ecm.Each<components::World, components::Scene>(
[&](const Entity & _entity,
const components::World *,
const components::Scene *_scene)->bool
{
this->sceneManager.SetWorldId(_entity);
const sdf::Scene &sceneSdf = _scene->Data();
this->newScenes.push_back(sceneSdf);
return true;
});
_ecm.Each<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
{
sdf::Model model;
model.SetName(_name->Data());
model.SetRawPose(_pose->Data());
this->newModels.push_back(
std::make_tuple(_entity, model, _parent->Data(),
_info.iterations));
return true;
});
_ecm.Each<components::Link, components::Name, components::Pose,
components::ParentEntity>(
[&](const Entity &_entity,
const components::Link *,
const components::Name *_name,
const components::Pose *_pose,
const components::ParentEntity *_parent)->bool
{
sdf::Link link;
link.SetName(_name->Data());
link.SetRawPose(_pose->Data());
this->newLinks.push_back(
std::make_tuple(_entity, link, _parent->Data()));
// used for collsions
this->modelToLinkEntities[_parent->Data()].push_back(_entity);
return true;
});
// visuals
_ecm.Each<components::Visual, components::Name, components::Pose,
components::Geometry,
components::CastShadows,
components::Transparency,
components::VisibilityFlags,
components::ParentEntity>(
[&](const Entity &_entity,
const components::Visual *,
const components::Name *_name,
const components::Pose *_pose,
const components::Geometry *_geom,
const components::CastShadows *_castShadows,
const components::Transparency *_transparency,
const components::VisibilityFlags *_visibilityFlags,
const components::ParentEntity *_parent)->bool
{
sdf::Visual visual;
visual.SetName(_name->Data());
visual.SetRawPose(_pose->Data());
visual.SetGeom(_geom->Data());
visual.SetCastShadows(_castShadows->Data());
visual.SetTransparency(_transparency->Data());
visual.SetVisibilityFlags(_visibilityFlags->Data());
// Optional components
auto material = _ecm.Component<components::Material>(_entity);
if (material != nullptr)
{
visual.SetMaterial(material->Data());
}
if (auto temp = _ecm.Component<components::Temperature>(_entity))
{
// get the uniform temperature for the entity
this->entityTemp[_entity] =
std::make_tuple<float, float, std::string>(
temp->Data().Kelvin(), 0.0, "");
}
else
{
// entity doesn't have a uniform temperature. Check if it has
// a heat signature with an associated temperature range
auto heatSignature =
_ecm.Component<components::SourceFilePath>(_entity);
auto tempRange =
_ecm.Component<components::TemperatureRange>(_entity);
if (heatSignature && tempRange)
{
this->entityTemp[_entity] =
std::make_tuple<float, float, std::string>(
tempRange->Data().min.Kelvin(),
tempRange->Data().max.Kelvin(),
std::string(heatSignature->Data()));
}
}
this->newVisuals.push_back(
std::make_tuple(_entity, visual, _parent->Data()));
return true;
});
// actors
_ecm.Each<components::Actor, components::ParentEntity>(
[&](const Entity &_entity,
const components::Actor *_actor,
const components::ParentEntity *_parent) -> bool
{
this->newActors.push_back(
std::make_tuple(_entity, _actor->Data(), _parent->Data()));
return true;
});
// lights
_ecm.Each<components::Light, components::ParentEntity>(
[&](const Entity &_entity,
const components::Light *_light,
const components::ParentEntity *_parent) -> bool
{
this->newLights.push_back(
std::make_tuple(_entity, _light->Data(), _parent->Data()));
return true;
});
// collisions
_ecm.Each<components::Collision, components::Name, components::Pose,
components::Geometry, components::CollisionElement,
components::ParentEntity>(
[&](const Entity &_entity,
const components::Collision *,
const components::Name *,
const components::Pose *,
const components::Geometry *,
const components::CollisionElement *_collElement,
const components::ParentEntity *_parent) -> bool
{
this->entityCollisions[_entity] = _collElement->Data();
this->linkToCollisionEntities[_parent->Data()].push_back(_entity);
return true;
});
if (this->enableSensors)
{
// Create cameras
_ecm.Each<components::Camera, components::ParentEntity>(
[&](const Entity &_entity,
const components::Camera *_camera,
const components::ParentEntity *_parent)->bool
{
addNewSensor(_entity, _camera->Data(), _parent->Data(),
cameraSuffix);
return true;
});
// Create depth cameras
_ecm.Each<components::DepthCamera, components::ParentEntity>(
[&](const Entity &_entity,
const components::DepthCamera *_depthCamera,
const components::ParentEntity *_parent)->bool
{
addNewSensor(_entity, _depthCamera->Data(), _parent->Data(),
depthCameraSuffix);
return true;
});
// Create rgbd cameras
_ecm.Each<components::RgbdCamera, components::ParentEntity>(
[&](const Entity &_entity,
const components::RgbdCamera *_rgbdCamera,
const components::ParentEntity *_parent)->bool
{
addNewSensor(_entity, _rgbdCamera->Data(), _parent->Data(),
rgbdCameraSuffix);
return true;
});
// Create gpu lidar
_ecm.Each<components::GpuLidar, components::ParentEntity>(
[&](const Entity &_entity,
const components::GpuLidar *_gpuLidar,
const components::ParentEntity *_parent)->bool
{
addNewSensor(_entity, _gpuLidar->Data(), _parent->Data(),
gpuLidarSuffix);
return true;
});
// Create thermal camera
_ecm.Each<components::ThermalCamera, components::ParentEntity>(
[&](const Entity &_entity,
const components::ThermalCamera *_thermalCamera,
const components::ParentEntity *_parent)->bool
{
addNewSensor(_entity, _thermalCamera->Data(), _parent->Data(),
thermalCameraSuffix);
return true;
});
}
this->initialized = true;
}
else
{
// Get all the new worlds
// TODO(anyone) Only one scene is supported for now
// extend the sensor system to support mutliple scenes in the future
_ecm.EachNew<components::World, components::Scene>(
[&](const Entity & _entity,
const components::World *,
const components::Scene *_scene)->bool
{
this->sceneManager.SetWorldId(_entity);
const sdf::Scene &sceneSdf = _scene->Data();
this->newScenes.push_back(sceneSdf);
return true;
});
_ecm.EachNew<components::Model, components::Name, components::Pose,
components::ParentEntity>(
[&](const Entity &_entity,