-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
geometry_state_test.cc
4128 lines (3628 loc) · 171 KB
/
geometry_state_test.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
#include "drake/geometry/geometry_state.h"
#include <algorithm>
#include <map>
#include <memory>
#include <set>
#include <unordered_set>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/find_resource.h"
#include "drake/common/nice_type_name.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/geometry/geometry_frame.h"
#include "drake/geometry/geometry_instance.h"
#include "drake/geometry/geometry_roles.h"
#include "drake/geometry/geometry_set.h"
#include "drake/geometry/geometry_version.h"
#include "drake/geometry/internal_frame.h"
#include "drake/geometry/proximity/make_sphere_mesh.h"
#include "drake/geometry/render/render_label.h"
#include "drake/geometry/shape_specification.h"
#include "drake/geometry/test_utilities/dummy_render_engine.h"
namespace drake {
namespace geometry {
using Eigen::Translation3d;
using Eigen::Vector3d;
using internal::DummyRenderEngine;
using internal::FrameNameSet;
using internal::InternalFrame;
using internal::InternalGeometry;
using internal::ProximityEngine;
using math::RigidTransform;
using math::RigidTransformd;
using render::RenderLabel;
using std::make_unique;
using std::map;
using std::move;
using std::pair;
using std::set;
using std::string;
using std::unique_ptr;
using std::unordered_map;
using std::unordered_set;
using std::vector;
template <typename T>
using IdPoseMap = unordered_map<GeometryId, RigidTransform<T>>;
// Implementation of friend class that allows me to peek into the geometry state
// to confirm invariants on the state's internal workings as a result of
// operations.
template <class T>
class GeometryStateTester {
public:
void set_state(GeometryState<T>* state) { state_ = state; }
FrameId get_world_frame() const { return InternalFrame::world_frame_id(); }
SourceId get_self_source_id() const {
return state_->self_source_;
}
const unordered_map<SourceId, string>& get_source_name_map() const {
return state_->source_names_;
}
const unordered_map<SourceId, FrameIdSet>& get_source_frame_id_map() const {
return state_->source_frame_id_map_;
}
const unordered_map<SourceId, FrameNameSet>& get_source_frame_name_map()
const {
return state_->source_frame_name_map_;
}
const unordered_map<SourceId, FrameIdSet>& get_source_root_frame_map() const {
return state_->source_root_frame_map_;
}
const unordered_map<SourceId, unordered_set<GeometryId>>&
get_source_anchored_geometry_map() const {
return state_->source_anchored_geometry_map_;
}
const unordered_map<FrameId, InternalFrame>& get_frames() const {
return state_->frames_;
}
const unordered_map<GeometryId, InternalGeometry>& get_geometries() const {
return state_->geometries_;
}
const vector<FrameId>& get_frame_index_id_map() const {
return state_->frame_index_to_id_map_;
}
const IdPoseMap<T>& get_geometry_world_poses() const {
return state_->kinematics_data_.X_WGs;
}
const vector<RigidTransform<T>>& get_frame_world_poses() const {
return state_->kinematics_data_.X_WFs;
}
const vector<RigidTransform<T>>& get_frame_parent_poses() const {
return state_->kinematics_data_.X_PFs;
}
internal::KinematicsData<T>& mutable_kinematics_data() const {
return state_->mutable_kinematics_data();
}
void SetFramePoses(SourceId source_id, const FramePoseVector<T>& poses,
internal::KinematicsData<T>* kinematics_data) {
state_->SetFramePoses(source_id, poses, kinematics_data);
}
void SetGeometryConfiguration(
SourceId source_id, const GeometryConfigurationVector<T>& configuration,
internal::KinematicsData<T>* kinematics_data) {
state_->SetGeometryConfiguration(source_id, configuration, kinematics_data);
}
void FinalizePoseUpdate() {
state_->FinalizePoseUpdate(state_->kinematics_data_,
&state_->mutable_proximity_engine(),
state_->GetMutableRenderEngines());
}
template <typename ValueType>
void ValidateFrameIds(
SourceId source_id,
const KinematicsVector<FrameId, ValueType>& data) const {
state_->ValidateFrameIds(source_id, data);
}
const InternalGeometry* GetGeometry(GeometryId id) const {
return state_->GetGeometry(id);
}
const render::RenderEngine& GetRenderEngineOrThrow(
const std::string& name) const {
return state_->GetRenderEngineOrThrow(name);
}
const ProximityEngine<T>& proximity_engine() const {
return *state_->geometry_engine_;
}
const unordered_map<string, copyable_unique_ptr<render::RenderEngine>>&
render_engines() const {
return state_->render_engines_;
}
const GeometryVersion& geometry_version() const {
return state_->geometry_version_;
}
private:
GeometryState<T>* state_;
};
namespace internal {
class ProximityEngineTester {
public:
static const hydroelastic::Geometries& hydroelastic_geometries(
const ProximityEngine<double>& engine) {
return engine.hydroelastic_geometries();
}
};
} // namespace internal
namespace {
// Class to aid in testing Shape introspection. Instantiated with a model
// Shape instance, it registers a copy of that shape and confirms that the
// introspected Shape matches in type and parameters.
template <typename ShapeType>
class ShapeMatcher final : public ShapeReifier {
public:
explicit ShapeMatcher(const ShapeType& expected)
: expected_(expected), result_(::testing::AssertionFailure()) {}
// Tests shape introspection.
::testing::AssertionResult ShapeIntrospects(GeometryState<double>* state,
SourceId source_id,
FrameId frame_id) {
GeometryId g_id = state->RegisterGeometry(
source_id, frame_id,
make_unique<GeometryInstance>(RigidTransformd::Identity(),
make_unique<ShapeType>(expected_),
"shape"));
state->GetShape(g_id).Reify(this);
return result_;
}
// Shape reifier implementations.
using ShapeReifier::ImplementGeometry;
void ImplementGeometry(const Sphere& sphere, void*) final {
if (IsExpectedType(sphere)) {
TestShapeParameters(sphere);
}
}
void ImplementGeometry(const Cylinder& cylinder, void*) final {
if (IsExpectedType(cylinder)) {
TestShapeParameters(cylinder);
}
}
void ImplementGeometry(const HalfSpace& half_space, void*) final {
// Halfspace has no parameters; so no further testing is necessary.
IsExpectedType(half_space);
}
void ImplementGeometry(const Box& box, void*) final {
if (IsExpectedType(box)) {
TestShapeParameters(box);
}
}
void ImplementGeometry(const Capsule& capsule, void*) final {
if (IsExpectedType(capsule)) {
TestShapeParameters(capsule);
}
}
void ImplementGeometry(const Mesh& mesh, void*) final {
if (IsExpectedType(mesh)) {
TestShapeParameters(mesh);
}
}
void ImplementGeometry(const Convex& convex, void*) final {
if (IsExpectedType(convex)) {
TestShapeParameters(convex);
}
}
private:
// Base template signature for comparing shape parameters. By default, it
// fails.
template <typename TestType>
void TestShapeParameters(const TestType& test) {
error() << "Not implemented for " << NiceTypeName::Get<ShapeType>() << " vs"
<< NiceTypeName::Get<TestType>();
}
// Convenience method for logging errors.
::testing::AssertionResult error() {
if (result_) result_ = ::testing::AssertionFailure();
return result_;
}
// Tests type of parameter against reference type. If they match, resets the
// result to the best known answer (success). Subsequent parameter testing
// will revert it to false via invocations to error().
template <typename TestShape>
bool IsExpectedType(const TestShape& test) {
if (typeid(ShapeType) == typeid(const TestShape)) {
result_ = ::testing::AssertionSuccess();
return true;
} else {
result_ << "Expected '" << NiceTypeName::Get<ShapeType>() << "', given '"
<< NiceTypeName::Get<TestShape>() << "'";
return false;
}
}
// The model shape.
const ShapeType expected_;
// The result of the test (with appropriate failure messages).
::testing::AssertionResult result_;
};
// Specializations for where the ShapeMatcher's ShapeType match the reified
// TestType.
template <>
template <>
void ShapeMatcher<Sphere>::TestShapeParameters(const Sphere& test) {
if (test.radius() != expected_.radius()) {
error() << "\nExpected sphere radius " << expected_.radius() << ", "
<< "received sphere radius " << test.radius();
}
}
template <>
template <>
void ShapeMatcher<Cylinder>::TestShapeParameters(const Cylinder& test) {
if (test.radius() != expected_.radius()) {
error() << "\nExpected cylinder radius " << expected_.radius() << ", "
<< "received cylinder radius " << test.radius();
}
if (test.length() != expected_.length()) {
error() << "\nExpected cylinder length " << expected_.length()
<< ", received cylinder length " << test.length();
}
}
template <>
template <>
void ShapeMatcher<Box>::TestShapeParameters(const Box& test) {
if (test.width() != expected_.width()) {
error() << "\nExpected box width " << expected_.width() << ", "
<< "received box width " << test.width();
}
if (test.height() != expected_.height()) {
error() << "\nExpected box height " << expected_.height()
<< ", received box height " << test.height();
}
if (test.depth() != expected_.depth()) {
error() << "\nExpected box depth " << expected_.depth()
<< ", received box depth " << test.depth();
}
}
template <>
template <>
void ShapeMatcher<Capsule>::TestShapeParameters(const Capsule& test) {
if (test.radius() != expected_.radius()) {
error() << "\nExpected capsule radius " << expected_.radius() << ", "
<< "received capsule radius " << test.radius();
}
if (test.length() != expected_.length()) {
error() << "\nExpected capsule length " << expected_.length()
<< ", received capsule length " << test.length();
}
}
template <>
template <>
void ShapeMatcher<Mesh>::TestShapeParameters(const Mesh& test) {
if (test.filename() != expected_.filename()) {
error() << "\nExpected mesh filename " << expected_.filename() << ", "
<< "received mesh filename " << test.filename();
}
if (test.scale() != expected_.scale()) {
error() << "\nExpected mesh scale " << expected_.scale()
<< ", received mesh scale " << test.scale();
}
}
template <>
template <>
void ShapeMatcher<Convex>::TestShapeParameters(const Convex& test) {
if (test.filename() != expected_.filename()) {
error() << "\nExpected convex filename " << expected_.filename() << ", "
<< "received convex filename " << test.filename();
}
if (test.scale() != expected_.scale()) {
error() << "\nExpected convex scale " << expected_.scale()
<< ", received convex scale " << test.scale();
}
}
// A mask-style enumeration for indicating which of a set of roles should be
// assigned to the newly configured geometry.
enum class Assign {
kNone = 0,
kProximity = 1,
kIllustration = 2,
kPerception = 4
};
Assign operator&(Assign a, Assign b) {
return static_cast<Assign>(static_cast<int>(a) & static_cast<int>(b));
}
Assign operator|(Assign a, Assign b) {
return static_cast<Assign>(static_cast<int>(a) | static_cast<int>(b));
}
// The fundamental base class for the geometry state tests; it provides
// utilities for configuring an owned geometry state. This class allows us to
// create arbitrary test harnesses using the same infrastructure. (See
// GeometryStateTest and RemoveRoleTests -- this latter comes in a future PR.)
class GeometryStateTestBase {
public:
GeometryStateTestBase() = default;
// The initialization to be done prior to each test; the derived test class
// should invoke this in its SetUp() method.
void TestInit(bool add_renderer = true) {
frame_ = make_unique<GeometryFrame>("ref_frame");
instance_pose_.set_translation({10, 20, 30});
instance_ = make_unique<GeometryInstance>(
instance_pose_, make_unique<Sphere>(1.0), "instance");
gs_tester_.set_state(&geometry_state_);
if (add_renderer) {
auto render_engine = make_unique<DummyRenderEngine>();
render_engine_ = render_engine.get();
geometry_state_.AddRenderer(kDummyRenderName, move(render_engine));
}
}
// Utility method for adding a source to the state.
SourceId NewSource(const string& name = "") {
return geometry_state_.RegisterNewSource(name == "" ? kSourceName : name);
}
// This method sets up a dummy tree to facilitate testing. It creates a single
// source with a fixed configuration of frames with a pre-determined number of
// geometries per frame.
//
// Creates the following tree:
// s_id
// ├───┬────────────┐
// │ │ │
// f0 f1 a
// ╱ │ ├───┬───┐
// g0 g1 │ │ │
// f2 g2 g3
// ╱ ╲
// g4 g5
//
// Default frame configuration
// f0 is @ <1, 2, 3>, with a 90-degree rotation around x.
// f1 is @ <10, 20, 30>, with a 90-degree rotation around y.
// f2 is @ <-10, -20, -30>, with a -90-degree rotation around y.
// NOTE: f2's pose is the inverse of f1. As such, for g4 & g5, the pose
// relative to the parent frame f2 is the same as to the world, e.g.,
// X_PG = X_WG.
// a is an anchored box of size (100, 100, 2), positioned at <0, 0 -1> (so
// that it's top face lies on the z = 0 plane.
// Geometry configuration
// gi is at position <i + 1, 0, 0>, with a rotation of iπ/2 radians around
// the x-axis.
// Each of the dynamic geometries are spheres of radius one at the following
// positions (expressed in the world frame) (with identity rotation):
// p_WG0 = <1, 2, 3>
// p_WG1 = <2, 2, 3>
// p_WG2 = <10, 20, 33>
// p_WG3 = <10, 20, 34>
// p_WG4 = <5, 0, 0>
// p_WG5 = <6, 0, 0)
//
// In the default configuration, there are only two colliding pairs:
// (a, g4) and (a, g5)
// Although the sibling geometries affixed to each frame overlap, the pairs
// (g0, g1), (g2, g3), and (g4, g5) are implicitly filtered because they are
// sibling geometries affixed to the same frame.
//
// By default, no roles are assigned to the geometries. However, roles can
// be assigned to *all* registered geometries by indicating the type of role
// to assign (via `roles_to_assign`).
SourceId SetUpSingleSourceTree(Assign roles_to_assign = Assign::kNone) {
using std::to_string;
source_id_ = NewSource();
// Create f0.
// 90° around x-axis.
RigidTransformd pose(AngleAxis<double>(M_PI_2, Vector3d::UnitX()),
Vector3d{1, 2, 3});
frames_.push_back(geometry_state_.RegisterFrame(
source_id_, GeometryFrame("f0")));
X_WFs_.push_back(pose);
X_PFs_.push_back(pose);
// Create f1.
// 90° around y-axis.
pose = RigidTransformd(AngleAxis<double>(M_PI_2, Vector3d::UnitY()),
Vector3d{10, 20, 30});
frames_.push_back(geometry_state_.RegisterFrame(
source_id_, GeometryFrame("f1")));
X_WFs_.push_back(pose);
X_PFs_.push_back(pose);
// Create f2.
pose = pose.inverse();
frames_.push_back(geometry_state_.RegisterFrame(
source_id_, frames_[1], GeometryFrame("f2")));
X_WFs_.push_back(X_WFs_[1] * pose);
X_PFs_.push_back(pose);
// Add geometries to each frame.
const Vector3<double> x_axis(1, 0, 0);
geometries_.resize(kFrameCount * kGeometryCount);
geometry_names_.resize(geometries_.size());
int g_count = 0;
for (auto frame_id : frames_) {
for (int i = 0; i < kGeometryCount; ++i) {
pose = RigidTransformd(AngleAxis<double>(g_count * M_PI_2, x_axis),
Vector3d{g_count + 1.0, 0, 0});
// Have the name reflect the frame and the index in the geometry.
const string& name = to_string(frame_id) + "_g" + to_string(i);
geometry_names_[g_count] = name;
geometries_[g_count] = geometry_state_.RegisterGeometry(
source_id_, frame_id,
make_unique<GeometryInstance>(pose, make_unique<Sphere>(1), name));
X_FGs_.push_back(pose);
++g_count;
}
}
// Create anchored geometry.
X_WA_ = RigidTransformd{Translation3d{0, 0, -1}};
// This simultaneously tests the named registration function and
// _implicitly_ tests registration of geometry against the world frame id
// (as that is how `RegisterAnchoredGeometry()` works.
anchored_geometry_ = geometry_state_.RegisterAnchoredGeometry(
source_id_, make_unique<GeometryInstance>(
X_WA_, make_unique<Box>(100, 100, 2), anchored_name_));
if ((roles_to_assign & Assign::kProximity) != Assign::kNone) {
AssignProximityToSingleSourceTree();
}
if ((roles_to_assign & Assign::kPerception) != Assign::kNone) {
AssignPerceptionToSingleSourceTree();
}
if ((roles_to_assign & Assign::kIllustration) != Assign::kNone) {
AssignIllustrationToSingleSourceTree();
}
return source_id_;
}
// Reports characteristics of the dummy tree.
int single_tree_frame_count() const {
// Added dynamic frames plus the world frame.
return kFrameCount + 1;
}
int single_tree_total_geometry_count() const {
return single_tree_dynamic_geometry_count() + anchored_geometry_count();
}
int single_tree_dynamic_geometry_count() const {
return kFrameCount * kGeometryCount;
}
int anchored_geometry_count() const { return 1; }
vector<GeometryId> all_geometry_ids() const {
vector<GeometryId> ids(geometries_);
ids.push_back(anchored_geometry_);
return ids;
}
int default_collision_pair_count() const {
// Without filtering, this should be the expected pairs:
// (a, g4), (a, g5)
return 2;
}
// Members owned by the test class.
unique_ptr<GeometryFrame> frame_;
unique_ptr<GeometryInstance> instance_;
RigidTransformd instance_pose_{RigidTransformd::Identity()};
GeometryState<double> geometry_state_;
GeometryStateTester<double> gs_tester_;
DummyRenderEngine* render_engine_{};
// Values for setting up and testing the dummy tree.
enum Counts {
kFrameCount = 3,
kGeometryCount = 2 // Geometries *per frame*.
};
// The frame ids created in the dummy tree instantiation.
vector<FrameId> frames_;
// TODO(SeanCurtis-TRI): geometries_ and geometry_names_ have long since
// been invalid names -- with the addition of the anchored geometry, these
// are now strictly dynamic geometries (and names) and should be renamed
// accordingly.
// The geometry ids created in the dummy tree instantiation.
vector<GeometryId> geometries_;
// The names for all the geometries (as registered).
vector<string> geometry_names_;
// The single, anchored geometry id.
GeometryId anchored_geometry_;
// The registered name of the anchored geometry.
const string anchored_name_{"anchored"};
// The id of the single-source tree.
SourceId source_id_;
// The poses of the frames in the world frame.
vector<RigidTransformd> X_WFs_;
// The poses of the frames in the parent's frame.
vector<RigidTransformd> X_PFs_;
// The poses of the dynamic geometries in the parent frame.
vector<RigidTransformd> X_FGs_;
// The pose of the anchored geometry in the world frame.
RigidTransformd X_WA_;
// The default source name.
const string kSourceName{"default_source"};
// The name of the dummy renderer added to the geometry state.
const string kDummyRenderName{"dummy_renderer"};
private:
// Convenience method for assigning illustration properties to all geometries
// in the single source tree.
void AssignProximityToSingleSourceTree() {
ASSERT_TRUE(source_id_.is_valid());
ProximityProperties properties;
AssignRoleToSingleSourceTree(properties);
}
// Convenience method for assigning illustration properties to all geometries
// in the single source tree.
void AssignIllustrationToSingleSourceTree() {
ASSERT_TRUE(source_id_.is_valid());
IllustrationProperties properties;
properties.AddProperty("phong", "diffuse",
Vector4<double>{0.8, 0.8, 0.8, 1.0});
AssignRoleToSingleSourceTree(properties);
}
// Convenience method for assigning perception properties to all geometries
// in the single source tree.
void AssignPerceptionToSingleSourceTree() {
ASSERT_TRUE(source_id_.is_valid());
// If no render engine has been added, we need to get the accepting
// properties from a temporary.
PerceptionProperties properties =
render_engine_ ? render_engine_->accepting_properties()
: DummyRenderEngine().accepting_properties();
properties.AddProperty("phong", "diffuse",
Vector4<double>{0.8, 0.8, 0.8, 1.0});
properties.AddProperty("label", "id", RenderLabel::kDontCare);
AssignRoleToSingleSourceTree(properties);
}
template <typename PropertyType>
void AssignRoleToSingleSourceTree(const PropertyType& properties) {
ASSERT_TRUE(source_id_.is_valid());
for (GeometryId id : geometries_) {
geometry_state_.AssignRole(source_id_, id, properties);
}
geometry_state_.AssignRole(source_id_, anchored_geometry_, properties);
}
};
// Class for performing most tests on GeometryState. It does *not* populate the
// GeometryState at all, but relies on each test to do so as appropriate
// (via the SetUpSingleSourceTree() method).
class GeometryStateTest : public GeometryStateTestBase, public ::testing::Test {
protected:
void SetUp() override { TestInit(); }
// Helpers for forwarding member methods of Geometry State and verifying
// behaviors of Geometry Versions.
//
// The helpers are templatized on the return type of the method and two sets
// of arguments, DeclaredArgs and GivenArgs. While generally one would
// assume the two sets of args are of the same type, separating them this
// way facilitates type deduction. For example, passing in a string literal
// as a parameter to a function that expects a const string would defy type
// deduction with just a single argument template. But separating them at
// the call to this function, defers the resolution to the actual call of
// the function.
// Forward a function call to a member method of GeometryState and return the
// GeometryVersions before and after the call.
template <typename ReturnType, typename... DeclaredArgs,
typename... GivenArgs>
std::tuple<GeometryVersion, GeometryVersion> ForwardAndGetRevisions(
ReturnType (GeometryState<double>::*f)(DeclaredArgs...),
GivenArgs&&... args) {
GeometryVersion old_version = geometry_state_.geometry_version();
(geometry_state_.*f)(std::forward<GivenArgs>(args)...);
GeometryVersion new_version = geometry_state_.geometry_version();
return {old_version, new_version};
}
// Forward a call to a member function in GeometryState and verify that the
// version of the given `role` is modified but all other versions are
// unchanged in this function.
template <typename ReturnType, typename... DeclaredArgs,
typename... GivenArgs>
void VerifyRoleVersionModified(
Role role, ReturnType (GeometryState<double>::*f)(DeclaredArgs...),
GivenArgs&&... args) {
auto [old_version, new_version] =
ForwardAndGetRevisions(f, std::forward<GivenArgs>(args)...);
for (Role test_role :
{Role::kProximity, Role::kPerception, Role::kIllustration}) {
// We expect versions to match when the test_role is different from the
// declared role.
EXPECT_EQ(old_version.IsSameAs(new_version, test_role),
role != test_role);
}
}
// Forward a call to a non-void member function in GeometryState and verify
// that all versions are unchanged in this function. Return the return
// value of the forwarded call.
template <typename ReturnType, typename... DeclaredArgs,
typename... GivenArgs>
ReturnType VerifyVersionUnchanged(
ReturnType (GeometryState<double>::*f)(DeclaredArgs...),
GivenArgs&&... args) {
GeometryVersion old_version = geometry_state_.geometry_version();
ReturnType ret = (geometry_state_.*f)(std::forward<GivenArgs>(args)...);
GeometryVersion new_version = geometry_state_.geometry_version();
EXPECT_TRUE(old_version.IsSameAs(new_version, Role::kProximity));
EXPECT_TRUE(old_version.IsSameAs(new_version, Role::kPerception));
EXPECT_TRUE(old_version.IsSameAs(new_version, Role::kIllustration));
return ret;
}
// Forward a call to a void member function in GeometryState and verify that
// all versions are unchanged in this function.
template <typename... DeclaredArgs, typename... GivenArgs>
void VerifyVersionUnchanged(void (GeometryState<double>::*f)(DeclaredArgs...),
GivenArgs&&... args) {
auto [old_version, new_version] =
ForwardAndGetRevisions(f, std::forward<GivenArgs>(args)...);
EXPECT_TRUE(old_version.IsSameAs(new_version, Role::kProximity));
EXPECT_TRUE(old_version.IsSameAs(new_version, Role::kPerception));
EXPECT_TRUE(old_version.IsSameAs(new_version, Role::kIllustration));
}
void VerifyIdenticalVersions(const GeometryState<double>& gs1,
const GeometryState<double>& gs2) const {
const auto& v1 = gs1.geometry_version();
const auto& v2 = gs2.geometry_version();
EXPECT_TRUE(v1.IsSameAs(v2, Role::kProximity));
EXPECT_TRUE(v1.IsSameAs(v2, Role::kPerception));
EXPECT_TRUE(v1.IsSameAs(v2, Role::kIllustration));
}
};
// Confirms that a new GeometryState has no data.
TEST_F(GeometryStateTest, Constructor) {
// GeometryState has a "self source".
EXPECT_EQ(geometry_state_.get_num_sources(), 1);
// GeometryState always has a world frame.
EXPECT_EQ(geometry_state_.get_num_frames(), 1);
EXPECT_EQ(geometry_state_.get_num_geometries(), 0);
EXPECT_EQ(gs_tester_.get_source_frame_name_map().find(
gs_tester_.get_self_source_id())->second,
internal::FrameNameSet{"world"});
}
// Confirms that the registered shapes are correctly returned upon
// introspection.
TEST_F(GeometryStateTest, IntrospectShapes) {
const SourceId source_id = geometry_state_.RegisterNewSource("test_source");
const FrameId frame_id = geometry_state_.RegisterFrame(
source_id, GeometryFrame("frame"));
// Test across all valid shapes.
{
ShapeMatcher<Sphere> matcher(Sphere(0.25));
EXPECT_TRUE(
matcher.ShapeIntrospects(&geometry_state_, source_id, frame_id));
}
{
ShapeMatcher<Cylinder> matcher(Cylinder(0.25, 2.0));
EXPECT_TRUE(
matcher.ShapeIntrospects(&geometry_state_, source_id, frame_id));
}
{
ShapeMatcher<Box> matcher(Box(0.25, 2.0, 32.0));
EXPECT_TRUE(
matcher.ShapeIntrospects(&geometry_state_, source_id, frame_id));
}
{
ShapeMatcher<Capsule> matcher(Capsule(0.25, 2.0));
EXPECT_TRUE(
matcher.ShapeIntrospects(&geometry_state_, source_id, frame_id));
}
{
ShapeMatcher<HalfSpace> matcher(HalfSpace{});
EXPECT_TRUE(
matcher.ShapeIntrospects(&geometry_state_, source_id, frame_id));
}
{
ShapeMatcher<Mesh> matcher(Mesh{"Path/to/mesh", 0.25});
EXPECT_TRUE(
matcher.ShapeIntrospects(&geometry_state_, source_id, frame_id));
}
{
ShapeMatcher<Convex> matcher(Convex{"Path/to/convex", 0.25});
EXPECT_TRUE(
matcher.ShapeIntrospects(&geometry_state_, source_id, frame_id));
}
// Test invalid id.
DRAKE_EXPECT_THROWS_MESSAGE(
geometry_state_.GetShape(GeometryId::get_new_id()),
"No geometry available for invalid geometry id: .+");
}
// Confirms semantics of user-specified source name.
// - The source name is stored and retrievable,
// - duplicate names are detected and considered errors, and
// - unrecognized source ids do not produce names.
TEST_F(GeometryStateTest, SourceRegistrationWithNames) {
using std::to_string;
// Case: Successful registration of unique source id and name.
SourceId s_id;
const string name = "Unique";
DRAKE_EXPECT_NO_THROW((s_id = geometry_state_.RegisterNewSource(name)));
EXPECT_TRUE(geometry_state_.SourceIsRegistered(s_id));
EXPECT_EQ(geometry_state_.GetName(s_id), name);
// Case: User-specified name duplicates previously registered name.
DRAKE_EXPECT_THROWS_MESSAGE(
geometry_state_.RegisterNewSource(name),
"Registering new source with duplicate name: Unique.");
// Case: query with invalid source id.
DRAKE_EXPECT_THROWS_MESSAGE(
geometry_state_.GetName(SourceId::get_new_id()),
"Querying source name for an invalid source id: \\d+.");
}
// Tests the geometry statistics values. It uses the single-source tree to
// create a state with interesting metrics. Also confirms the "is registered"
// -ness of known valid sources and known invalid sources.
TEST_F(GeometryStateTest, GeometryStatistics) {
const SourceId dummy_source = SetUpSingleSourceTree();
EXPECT_TRUE(geometry_state_.SourceIsRegistered(dummy_source));
// Dummy source + self source.
EXPECT_EQ(geometry_state_.get_num_sources(), 2);
EXPECT_EQ(geometry_state_.get_num_frames(), single_tree_frame_count());
EXPECT_EQ(geometry_state_.NumFramesForSource(source_id_),
single_tree_frame_count() - 1); // subtract the world frame.
DRAKE_EXPECT_THROWS_MESSAGE(
geometry_state_.NumFramesForSource(SourceId::get_new_id()),
"Referenced geometry source .* is not registered.");
EXPECT_EQ(geometry_state_.NumDynamicGeometries(),
single_tree_dynamic_geometry_count());
EXPECT_EQ(geometry_state_.NumAnchoredGeometries(),
anchored_geometry_count());
EXPECT_EQ(
geometry_state_.NumAnchoredGeometries(),
geometry_state_.NumGeometriesForFrame(InternalFrame::world_frame_id()));
EXPECT_EQ(geometry_state_.get_num_geometries(),
single_tree_total_geometry_count());
const SourceId false_id = SourceId::get_new_id();
EXPECT_FALSE(geometry_state_.SourceIsRegistered(false_id));
}
TEST_F(GeometryStateTest, GetOwningSourceName) {
SetUpSingleSourceTree();
EXPECT_EQ(kSourceName, geometry_state_.GetOwningSourceName(frames_[0]));
EXPECT_EQ(kSourceName, geometry_state_.GetOwningSourceName(geometries_[0]));
EXPECT_EQ(kSourceName,
geometry_state_.GetOwningSourceName(anchored_geometry_));
DRAKE_EXPECT_THROWS_MESSAGE(
geometry_state_.GetOwningSourceName(FrameId::get_new_id()),
"Referenced frame .* has not been registered.");
DRAKE_EXPECT_THROWS_MESSAGE(
geometry_state_.GetOwningSourceName(GeometryId::get_new_id()),
"Geometry id .* does not map to a registered geometry");
}
// Compares the transmogrified geometry state (embedded in its tester) against
// the double state to confirm they have the same values/topology.
template <typename T>
void ExpectSuccessfulTransmogrification(
const GeometryStateTester<T>& T_tester,
const GeometryStateTester<double>& d_tester) {
// 1. Test all of the identifier -> trivially testable value maps
EXPECT_EQ(T_tester.get_self_source_id(), d_tester.get_self_source_id());
EXPECT_EQ(T_tester.get_source_name_map(), d_tester.get_source_name_map());
EXPECT_EQ(T_tester.get_source_frame_id_map(),
d_tester.get_source_frame_id_map());
EXPECT_EQ(T_tester.get_source_frame_name_map(),
d_tester.get_source_frame_name_map());
EXPECT_EQ(T_tester.get_source_root_frame_map(),
d_tester.get_source_root_frame_map());
EXPECT_EQ(T_tester.get_source_anchored_geometry_map(),
d_tester.get_source_anchored_geometry_map());
EXPECT_EQ(T_tester.get_geometries(), d_tester.get_geometries());
EXPECT_EQ(T_tester.get_frames(), d_tester.get_frames());
// 2. Confirm that the ids all made it across.
EXPECT_EQ(T_tester.get_frame_index_id_map(),
d_tester.get_frame_index_id_map());
// 3. Compare RigidTransformd with RigidTransform<AutoDiffXd>.
for (const auto& id_geom_pair : T_tester.get_geometries()) {
const GeometryId id = id_geom_pair.first;
const auto& T_geometry = id_geom_pair.second;
EXPECT_TRUE(CompareMatrices(
T_geometry.X_FG().GetAsMatrix34(),
d_tester.get_geometries().at(id).X_FG().GetAsMatrix34()));
}
// 4. Compare RigidTransform<AutoDiffXd> with RigidTransformd.
auto test_T_vs_double_pose = [](const RigidTransform<T>& test,
const RigidTransformd& ref) {
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 4; ++col) {
EXPECT_EQ(ExtractDoubleOrThrow(test.GetAsMatrix34()(row, col)),
ref.GetAsMatrix34()(row, col));
}
}
};
auto test_T_vs_double = [test_T_vs_double_pose](
const vector<RigidTransform<T>>& test,
const vector<RigidTransformd>& ref) {
EXPECT_EQ(test.size(), ref.size());
for (size_t i = 0; i < ref.size(); ++i) {
test_T_vs_double_pose(test[i], ref[i]);
}
};
auto test_T_vs_double_map = [test_T_vs_double_pose](
const IdPoseMap<T>& test,
const IdPoseMap<double>& ref) {
ASSERT_EQ(test.size(), ref.size());
for (const auto& id_pose_pair : ref) {
const GeometryId id = id_pose_pair.first;
const RigidTransformd& ref_pose = id_pose_pair.second;
test_T_vs_double_pose(test.at(id), ref_pose);
}
};
test_T_vs_double(T_tester.get_frame_parent_poses(),
d_tester.get_frame_parent_poses());
test_T_vs_double_map(T_tester.get_geometry_world_poses(),
d_tester.get_geometry_world_poses());
test_T_vs_double(T_tester.get_frame_world_poses(),
d_tester.get_frame_world_poses());
// 5. Engine transmogrification tested in its own test; it will *not* be done
// here.
}
// This tests the ability to assign a GeometryState<double> to a
// GeometryState<T>. Implicitly uses transmogrification.
TEST_F(GeometryStateTest, AssignDoubleToScalarType) {
SetUpSingleSourceTree();
GeometryState<AutoDiffXd> ad_state{};
ad_state = geometry_state_;
GeometryStateTester<AutoDiffXd> ad_tester;
ad_tester.set_state(&ad_state);
ExpectSuccessfulTransmogrification(ad_tester, gs_tester_);
GeometryState<symbolic::Expression> sym_state{};
sym_state = geometry_state_;
GeometryStateTester<symbolic::Expression> sym_tester;
sym_tester.set_state(&sym_state);
ExpectSuccessfulTransmogrification(sym_tester, gs_tester_);
}
// Uses the single source tree to confirm that the data has migrated properly.
TEST_F(GeometryStateTest, Transmogrify) {
SetUpSingleSourceTree();
unique_ptr<GeometryState<AutoDiffXd>> ad_state =
geometry_state_.ToAutoDiffXd();
GeometryStateTester<AutoDiffXd> ad_tester;
ad_tester.set_state(ad_state.get());
ExpectSuccessfulTransmogrification(ad_tester, gs_tester_);
}
// Confirms that the actions of initializing the single-source tree leave the
// geometry state in the expected configuration.
TEST_F(GeometryStateTest, ValidateSingleSourceTree) {
// NOTE: There are *two* sources -- the built-in self source id for geometry
// state and the id added here.
const SourceId s_id = SetUpSingleSourceTree();
// The source has *direct* access to all registered frames.
{
const auto& s_f_id_map = gs_tester_.get_source_frame_id_map();
EXPECT_EQ(s_f_id_map.size(), 2);
EXPECT_NE(s_f_id_map.find(s_id), s_f_id_map.end());
const auto &f_id_set = s_f_id_map.at(s_id);
EXPECT_EQ(frames_.size(), f_id_set.size());
for (int f = 0; f < kFrameCount; ++f) {
EXPECT_NE(f_id_set.find(frames_[f]), f_id_set.end());
}
}
// The root map *only* includes the root frames. Frames 0 & 1 *should* be
// included; frame 2 should *not*.
{
const auto& s_root_map = gs_tester_.get_source_root_frame_map();
EXPECT_EQ(s_root_map.size(), 2);
EXPECT_NE(s_root_map.find(s_id), s_root_map.end());
const auto &root_id_set = s_root_map.at(s_id);
EXPECT_NE(root_id_set.find(frames_[0]), root_id_set.end());
EXPECT_NE(root_id_set.find(frames_[1]), root_id_set.end());