-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathFilamentScene.cpp
1962 lines (1758 loc) · 76.1 KB
/
FilamentScene.cpp
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
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// Copyright (c) 2018-2024 www.open3d.org
// SPDX-License-Identifier: MIT
// ----------------------------------------------------------------------------
// 4068: Filament has some clang-specific vectorizing pragma's that MSVC flags
// 4146: PixelBufferDescriptor assert unsigned is positive before subtracting
// but MSVC can't figure that out.
// 4293: Filament's utils/algorithm.h utils::details::clz() does strange
// things with MSVC. Somehow sizeof(unsigned int) > 4, but its size is
// 32 so that x >> 32 gives a warning. (Or maybe the compiler can't
// determine the if statement does not run.)
// 4305: LightManager.h needs to specify some constants as floats
#include <unordered_set>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4068 4146 4293 4305)
#endif // _MSC_VER
#include <backend/PixelBufferDescriptor.h> // bogus 4146 warning on MSVC
#include <filament/Engine.h>
#include <filament/IndirectLight.h>
#include <filament/LightManager.h>
#include <filament/MaterialInstance.h>
#include <filament/Renderer.h>
#include <filament/Scene.h>
#include <filament/Skybox.h>
#include <filament/SwapChain.h>
#include <filament/Texture.h>
#include <filament/TextureSampler.h>
#include <filament/TransformManager.h>
#include <filament/VertexBuffer.h>
#include <filament/View.h>
#include <geometry/SurfaceOrientation.h>
#include <utils/EntityManager.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
// We do NOT include this first because it includes Image.h, which includes
// the fmt library, which includes windows.h (on Windows), which #defines
// OPAQUE (!!??) which causes syntax errors with filament/View.h which tries
// to make OPAQUE an member of a class enum. So include this after all the
// Filament headers to avoid this problem.
#if 1 // (enclose in #if so that apply-style doesn't move this)
#include "open3d/visualization/rendering/filament/FilamentScene.h"
#endif // 1
#include "open3d/geometry/BoundingVolume.h"
#include "open3d/geometry/LineSet.h"
#include "open3d/geometry/PointCloud.h"
#include "open3d/geometry/TriangleMesh.h"
#include "open3d/t/geometry/PointCloud.h"
#include "open3d/utility/Logging.h"
#include "open3d/visualization/rendering/Light.h"
#include "open3d/visualization/rendering/Material.h"
#include "open3d/visualization/rendering/Model.h"
#include "open3d/visualization/rendering/RendererHandle.h"
#include "open3d/visualization/rendering/filament/FilamentEngine.h"
#include "open3d/visualization/rendering/filament/FilamentEntitiesMods.h"
#include "open3d/visualization/rendering/filament/FilamentGeometryBuffersBuilder.h"
#include "open3d/visualization/rendering/filament/FilamentRenderer.h"
#include "open3d/visualization/rendering/filament/FilamentResourceManager.h"
#include "open3d/visualization/rendering/filament/FilamentView.h"
namespace { // avoid polluting global namespace, since only used here
/// @cond
static void DeallocateBuffer(void* buffer, size_t size, void* user_ptr) {
free(buffer);
}
const std::string kBackgroundName = "__background";
const std::string kGroundPlaneName = "__ground_plane";
const Eigen::Vector4f kDefaultGroundPlaneColor(0.5f, 0.5f, 0.5f, 1.f);
namespace defaults_mapping {
using GeometryType = open3d::geometry::Geometry::GeometryType;
using MaterialHandle = open3d::visualization::rendering::MaterialHandle;
using ResourceManager =
open3d::visualization::rendering::FilamentResourceManager;
std::unordered_map<std::string, MaterialHandle> shader_mappings = {
{"defaultLit", ResourceManager::kDefaultLit},
{"defaultLitTransparency",
ResourceManager::kDefaultLitWithTransparency},
{"defaultLitSSR", ResourceManager::kDefaultLitSSR},
{"defaultUnlitTransparency",
ResourceManager::kDefaultUnlitWithTransparency},
{"defaultUnlit", ResourceManager::kDefaultUnlit},
{"normals", ResourceManager::kDefaultNormalShader},
{"depth", ResourceManager::kDefaultDepthShader},
{"depthValue", ResourceManager::kDefaultDepthValueShader},
{"unlitGradient", ResourceManager::kDefaultUnlitGradientShader},
{"unlitSolidColor", ResourceManager::kDefaultUnlitSolidColorShader},
{"unlitPolygonOffset",
ResourceManager::kDefaultUnlitPolygonOffsetShader},
{"unlitBackground", ResourceManager::kDefaultUnlitBackgroundShader},
{"infiniteGroundPlane", ResourceManager::kInfinitePlaneShader},
{"unlitLine", ResourceManager::kDefaultLineShader},
{"gaussianSplat", ResourceManager::kGaussianSplatShader}};
MaterialHandle kColorOnlyMesh = ResourceManager::kDefaultUnlit;
MaterialHandle kPlainMesh = ResourceManager::kDefaultLit;
MaterialHandle kMesh = ResourceManager::kDefaultLit;
MaterialHandle kColoredPointcloud = ResourceManager::kDefaultUnlit;
MaterialHandle kPointcloud = ResourceManager::kDefaultLit;
MaterialHandle kLineset = ResourceManager::kDefaultUnlit;
} // namespace defaults_mapping
namespace converters {
using EigenMatrix =
open3d::visualization::rendering::FilamentScene::Transform::MatrixType;
using FilamentMatrix = filament::math::mat4f;
EigenMatrix EigenMatrixFromFilamentMatrix(const filament::math::mat4f& fm) {
EigenMatrix em;
em << fm(0, 0), fm(0, 1), fm(0, 2), fm(0, 3), fm(1, 0), fm(1, 1), fm(1, 2),
fm(1, 3), fm(2, 0), fm(2, 1), fm(2, 2), fm(2, 3), fm(3, 0),
fm(3, 1), fm(3, 2), fm(3, 3);
return em;
}
FilamentMatrix FilamentMatrixFromEigenMatrix(const EigenMatrix& em) {
// Filament matrices is column major and Eigen's - row major
return FilamentMatrix(FilamentMatrix::row_major_init{
em(0, 0), em(0, 1), em(0, 2), em(0, 3), em(1, 0), em(1, 1),
em(1, 2), em(1, 3), em(2, 0), em(2, 1), em(2, 2), em(2, 3),
em(3, 0), em(3, 1), em(3, 2), em(3, 3)});
}
} // namespace converters
/// @endcond
} // namespace
namespace open3d {
namespace visualization {
namespace rendering {
FilamentScene::FilamentScene(filament::Engine& engine,
FilamentResourceManager& resource_mgr,
Renderer& renderer)
: Scene(renderer), engine_(engine), resource_mgr_(resource_mgr) {
scene_ = engine_.createScene();
CreateSunDirectionalLight();
// Note: can't set background color, because ImguiFilamentBridge
// creates a Scene, and it needs to not have anything drawing, or it
// covers up any SceneWidgets in the window.
}
FilamentScene::~FilamentScene() {
for (auto& le : lights_) {
engine_.destroy(le.second.filament_entity);
le.second.filament_entity.clear();
}
engine_.destroy(sun_.filament_entity);
sun_.filament_entity.clear();
if (ibl_handle_) {
resource_mgr_.Destroy(ibl_handle_);
}
if (skybox_handle_) {
resource_mgr_.Destroy(skybox_handle_);
}
engine_.destroy(scene_);
}
Scene* FilamentScene::Copy() {
auto copy = new FilamentScene(engine_, resource_mgr_, renderer_);
copy->geometries_ = this->geometries_;
copy->lights_ = this->lights_;
copy->model_geometries_ = this->model_geometries_;
copy->background_color_ = this->background_color_;
copy->background_image_ = this->background_image_;
copy->ibl_name_ = this->ibl_name_;
copy->ibl_enabled_ = this->ibl_enabled_;
copy->skybox_enabled_ = this->skybox_enabled_;
copy->indirect_light_ = this->indirect_light_;
copy->skybox_ = this->skybox_;
copy->sun_ = this->sun_;
for (auto& name_geom : copy->geometries_) {
auto& name = name_geom.first;
auto& geom = name_geom.second;
auto& renderable_mgr = copy->engine_.getRenderableManager();
auto inst = renderable_mgr.getInstance(geom.filament_entity);
auto box = renderable_mgr.getAxisAlignedBoundingBox(inst);
auto vbuf = copy->resource_mgr_.GetVertexBuffer(geom.vb).lock();
auto ibuf = copy->resource_mgr_.GetIndexBuffer(geom.ib).lock();
auto new_entity = utils::EntityManager::get().create();
filament::RenderableManager::Builder builder(1);
builder.boundingBox(box)
.layerMask(FilamentView::kAllLayersMask,
FilamentView::kMainLayer)
.castShadows(geom.cast_shadows)
.receiveShadows(geom.receive_shadows)
.culling(geom.culling_enabled)
.geometry(0, geom.primitive_type, vbuf.get(), ibuf.get());
if (geom.priority >= 0) {
builder.priority(uint8_t(geom.priority));
}
copy->resource_mgr_.ReuseVertexBuffer(geom.vb);
auto material_instance = copy->AssignMaterialToFilamentGeometry(
builder, geom.mat.properties);
auto result = builder.build(copy->engine_, new_entity);
if (result == filament::RenderableManager::Builder::Success) {
if (geom.visible) {
copy->scene_->addEntity(new_entity);
}
geom.filament_entity = new_entity;
geom.mat.mat_instance = material_instance;
auto transform = this->GetGeometryTransform(name);
copy->SetGeometryTransform(name, transform);
copy->UpdateMaterialProperties(
copy->geometries_[name]); // for non-const
} else {
utility::LogWarning(
"Failed to copy Filament resources for geometry {}", name);
}
}
return copy;
}
ViewHandle FilamentScene::AddView(std::int32_t x,
std::int32_t y,
std::uint32_t w,
std::uint32_t h) {
auto handle = ViewHandle::Next();
auto view = std::make_unique<FilamentView>(engine_, *this, resource_mgr_);
view->SetViewport(x, y, w, h);
if (!views_.empty()) {
view->SetDiscardBuffers(View::TargetBuffers::DepthAndStencil);
}
ViewContainer c;
c.view = std::move(view);
views_.emplace(handle, std::move(c));
return handle;
}
View* FilamentScene::GetView(const ViewHandle& view_id) const {
auto found = views_.find(view_id);
if (found != views_.end()) {
return found->second.view.get();
}
return nullptr;
}
void FilamentScene::SetViewActive(const ViewHandle& view_id, bool is_active) {
auto found = views_.find(view_id);
if (found != views_.end()) {
found->second.is_active = is_active;
found->second.render_count = -1;
}
}
void FilamentScene::SetRenderOnce(const ViewHandle& view_id) {
auto found = views_.find(view_id);
if (found != views_.end()) {
found->second.is_active = true;
found->second.render_count = 1;
}
}
void FilamentScene::RemoveView(const ViewHandle& view_id) {
views_.erase(view_id);
}
void FilamentScene::AddCamera(const std::string& camera_name,
std::shared_ptr<Camera> cam) {}
void FilamentScene::RemoveCamera(const std::string& camera_name) {}
void FilamentScene::SetActiveCamera(const std::string& camera_name) {}
MaterialInstanceHandle FilamentScene::AssignMaterialToFilamentGeometry(
filament::RenderableManager::Builder& builder,
const MaterialRecord& material) {
// TODO: put this in a method
auto shader = defaults_mapping::shader_mappings[material.shader];
if (!shader) shader = defaults_mapping::kColorOnlyMesh;
auto material_instance = resource_mgr_.CreateMaterialInstance(shader);
auto wmat_instance = resource_mgr_.GetMaterialInstance(material_instance);
if (!wmat_instance.expired()) {
builder.material(0, wmat_instance.lock().get());
}
return material_instance;
}
bool FilamentScene::AddGeometry(const std::string& object_name,
const geometry::Geometry3D& geometry,
const MaterialRecord& material,
const std::string& downsampled_name /*= ""*/,
size_t downsample_threshold /*= SIZE_MAX*/) {
if (geometries_.count(object_name) > 0) {
utility::LogWarning(
"Geometry {} has already been added to scene graph.",
object_name);
return false;
}
// Basic sanity checks
if (geometry.IsEmpty()) {
utility::LogDebug(
"Geometry for object {} is empty. Not adding geometry to scene",
object_name);
return false;
}
auto tris = dynamic_cast<const geometry::TriangleMesh*>(&geometry);
if (tris && tris->vertex_normals_.empty() &&
tris->triangle_normals_.empty() &&
(material.shader == "defaultLit" ||
material.shader == "defaultLitTransparency")) {
utility::LogWarning(
"Using a shader with lighting but geometry has no normals.");
}
// Build Filament buffers
auto buffer_builder = GeometryBuffersBuilder::GetBuilder(geometry);
if (!buffer_builder) {
utility::LogWarning("Geometry type {} is not supported yet!",
static_cast<size_t>(geometry.GetGeometryType()));
return false;
}
if (!downsampled_name.empty()) {
buffer_builder->SetDownsampleThreshold(downsample_threshold);
}
buffer_builder->SetAdjustColorsForSRGBToneMapping(material.sRGB_color);
if (material.shader == "unlitLine") {
buffer_builder->SetWideLines();
}
auto buffers = buffer_builder->ConstructBuffers();
auto vb = std::get<0>(buffers);
auto ib = std::get<1>(buffers);
auto ib_downsampled = std::get<2>(buffers);
filament::Box aabb = buffer_builder->ComputeAABB(); // expensive
bool success = CreateAndAddFilamentEntity(object_name, *buffer_builder,
aabb, vb, ib, material);
if (success && ib_downsampled) {
if (!CreateAndAddFilamentEntity(downsampled_name, *buffer_builder, aabb,
vb, ib_downsampled, material,
BufferReuse::kYes)) {
utility::LogWarning(
"Internal error: could not create downsampled point cloud");
}
}
return success;
}
bool FilamentScene::AddGeometry(const std::string& object_name,
const t::geometry::Geometry& geometry,
const MaterialRecord& material,
const std::string& downsampled_name /*= ""*/,
size_t downsample_threshold /*= SIZE_MAX*/) {
// Basic sanity checks
if (geometry.IsEmpty()) {
utility::LogWarning("Geometry for object {} is empty", object_name);
return false;
}
auto buffer_builder = GeometryBuffersBuilder::GetBuilder(geometry);
if (!buffer_builder) {
utility::LogWarning(
"Unable to create GPU resources for object {}. Please check "
"console for further details.",
object_name);
return false;
}
// Setup and build filament resources
if (!downsampled_name.empty()) {
buffer_builder->SetDownsampleThreshold(downsample_threshold);
}
buffer_builder->SetAdjustColorsForSRGBToneMapping(material.sRGB_color);
if (material.shader == "unlitLine") {
buffer_builder->SetWideLines();
}
auto buffers = buffer_builder->ConstructBuffers();
auto vb = std::get<0>(buffers);
auto ib = std::get<1>(buffers);
auto ib_downsampled = std::get<2>(buffers);
filament::Box aabb = buffer_builder->ComputeAABB();
// NOTE: pointer not checked because if we get to this point then we know
// that the dynamic cast must succeed
auto* drawable_geom =
dynamic_cast<const t::geometry::DrawableGeometry*>(&geometry);
MaterialRecord internal_material = material;
if (drawable_geom->HasMaterial()) {
drawable_geom->GetMaterial().ToMaterialRecord(internal_material);
}
bool success = CreateAndAddFilamentEntity(object_name, *buffer_builder,
aabb, vb, ib, internal_material);
if (success && ib_downsampled) {
if (!CreateAndAddFilamentEntity(downsampled_name, *buffer_builder, aabb,
vb, ib_downsampled, internal_material,
BufferReuse::kYes)) {
// If we failed to create a downsampled cloud, which would be
// unlikely, create another entity with the original buffers
// (since that succeeded).
utility::LogWarning(
"Internal error: could not create downsampled point cloud");
CreateAndAddFilamentEntity(downsampled_name, *buffer_builder, aabb,
vb, ib, material, BufferReuse::kYes);
}
}
return success;
}
#ifndef NDEBUG
void OutputMaterialProperties(
const visualization::rendering::MaterialRecord& mat) {
utility::LogInfo("Material {}", mat.name);
utility::LogInfo("\tAlpha: {}", mat.has_alpha);
utility::LogInfo("\tBase Color: {},{},{},{}", mat.base_color.x(),
mat.base_color.y(), mat.base_color.z(),
mat.base_color.w());
utility::LogInfo("\tBase Metallic: {}", mat.base_metallic);
utility::LogInfo("\tBase Roughness: {}", mat.base_roughness);
utility::LogInfo("\tBase Reflectance: {}", mat.base_reflectance);
utility::LogInfo("\tBase Clear Cout: {}", mat.base_clearcoat);
}
#endif
bool FilamentScene::AddGeometry(const std::string& object_name,
const TriangleMeshModel& model) {
if (geometries_.count(object_name) > 0 ||
model_geometries_.count(object_name) > 0) {
utility::LogWarning("Model {} has already been added to scene graph.",
object_name);
return false;
}
std::vector<std::string> mesh_object_names;
std::unordered_multiset<std::string> check_duplicates;
for (const auto& mesh : model.meshes_) {
auto& mat = model.materials_[mesh.material_idx];
std::string derived_name(object_name + ":" + mesh.mesh_name);
check_duplicates.insert(derived_name);
if (check_duplicates.count(derived_name) > 1) {
derived_name +=
std::string("_") +
std::to_string(check_duplicates.count(derived_name));
}
AddGeometry(derived_name, *(mesh.mesh), mat);
mesh_object_names.push_back(derived_name);
}
model_geometries_[object_name] = mesh_object_names;
return true;
}
bool FilamentScene::CreateAndAddFilamentEntity(
const std::string& object_name,
GeometryBuffersBuilder& buffer_builder,
filament::Box& aabb,
VertexBufferHandle vb,
IndexBufferHandle ib,
const MaterialRecord& material,
BufferReuse reusing_vertex_buffer /*= kNo*/) {
auto vbuf = resource_mgr_.GetVertexBuffer(vb).lock();
auto ibuf = resource_mgr_.GetIndexBuffer(ib).lock();
auto filament_entity = utils::EntityManager::get().create();
filament::RenderableManager::Builder builder(1);
builder.boundingBox(aabb)
.layerMask(FilamentView::kAllLayersMask, FilamentView::kMainLayer)
.castShadows(true)
.receiveShadows(true)
.geometry(0, buffer_builder.GetPrimitiveType(), vbuf.get(),
ibuf.get());
auto material_instance =
AssignMaterialToFilamentGeometry(builder, material);
auto result = builder.build(engine_, filament_entity);
if (result == filament::RenderableManager::Builder::Success) {
scene_->addEntity(filament_entity);
auto giter = geometries_.emplace(std::make_pair(
object_name,
RenderableGeometry{object_name,
true,
false,
true,
true,
true,
-1,
{{}, material, material_instance},
filament_entity,
buffer_builder.GetPrimitiveType(),
vb,
ib}));
SetGeometryTransform(object_name, Transform::Identity());
UpdateMaterialProperties(giter.first->second);
} else {
// NOTE: Is there a better way to handle builder failing? That's a
// sign of a major problem.
utility::LogWarning(
"Failed to build Filament resources for geometry {}",
object_name);
return false;
}
if (reusing_vertex_buffer == BufferReuse::kYes) {
resource_mgr_.ReuseVertexBuffer(vb);
}
return true;
}
bool FilamentScene::HasGeometry(const std::string& object_name) const {
if (GeometryIsModel(object_name)) {
return true;
}
auto geom_entry = geometries_.find(object_name);
return (geom_entry != geometries_.end());
}
void FilamentScene::UpdateGeometry(const std::string& object_name,
const t::geometry::PointCloud& point_cloud,
uint32_t update_flags) {
auto geoms = GetGeometry(object_name, false);
if (!geoms.empty()) {
// Note: There should only be a single entry in geoms
auto* g = geoms[0];
auto vbuf_ptr = resource_mgr_.GetVertexBuffer(g->vb).lock();
auto vbuf = vbuf_ptr.get();
const auto& points = point_cloud.GetPointPositions();
const size_t n_vertices = points.GetLength();
// NOTE: number of points in the updated point cloud must be the
// same as the number of points when the vertex buffer was first
// created. If the number of points has changed then it cannot be
// updated. In that case, you must remove the geometry then add it
// again.
if (n_vertices > vbuf->getVertexCount()) {
utility::LogWarning(
"Geometry for point cloud {} cannot be updated because the "
"number of points exceeds the existing point count (Old: "
"{}, New: {})",
object_name, vbuf->getVertexCount(), n_vertices);
return;
}
bool geometry_update_needed = n_vertices != vbuf->getVertexCount();
bool pcloud_is_gpu = points.IsCUDA();
t::geometry::PointCloud cpu_pcloud;
if (pcloud_is_gpu) {
cpu_pcloud = point_cloud.To(core::Device("CPU:0"));
}
// Update the each of the attribute requested
if (update_flags & kUpdatePointsFlag) {
const size_t vertex_array_size = n_vertices * 3 * sizeof(float);
if (pcloud_is_gpu) {
auto vertex_data =
static_cast<float*>(malloc(vertex_array_size));
memcpy(vertex_data, cpu_pcloud.GetPointPositions().GetDataPtr(),
vertex_array_size);
filament::VertexBuffer::BufferDescriptor pts_descriptor(
vertex_data, vertex_array_size, DeallocateBuffer);
vbuf->setBufferAt(engine_, 0, std::move(pts_descriptor));
} else {
filament::VertexBuffer::BufferDescriptor pts_descriptor(
points.GetDataPtr(), vertex_array_size);
vbuf->setBufferAt(engine_, 0, std::move(pts_descriptor));
}
}
if (update_flags & kUpdateColorsFlag && point_cloud.HasPointColors()) {
const size_t color_array_size = n_vertices * 3 * sizeof(float);
if (pcloud_is_gpu) {
auto color_data = static_cast<float*>(malloc(color_array_size));
memcpy(color_data, cpu_pcloud.GetPointColors().GetDataPtr(),
color_array_size);
filament::VertexBuffer::BufferDescriptor color_descriptor(
color_data, color_array_size, DeallocateBuffer);
vbuf->setBufferAt(engine_, 1, std::move(color_descriptor));
} else {
filament::VertexBuffer::BufferDescriptor color_descriptor(
point_cloud.GetPointColors().GetDataPtr(),
color_array_size);
vbuf->setBufferAt(engine_, 1, std::move(color_descriptor));
}
}
if (update_flags & kUpdateNormalsFlag &&
point_cloud.HasPointNormals()) {
const size_t normal_array_size = n_vertices * 4 * sizeof(float);
const void* normal_data = nullptr;
if (pcloud_is_gpu) {
const auto& normals = point_cloud.GetPointNormals();
normal_data = normals.GetDataPtr();
} else {
normal_data = cpu_pcloud.GetPointNormals().GetDataPtr();
}
// Converting normals to Filament type - quaternions
auto float4v_tangents = static_cast<filament::math::quatf*>(
malloc(normal_array_size));
auto orientation = filament::geometry::SurfaceOrientation::Builder()
.vertexCount(n_vertices)
.normals(reinterpret_cast<
const filament::math::float3*>(
normal_data))
.build();
orientation->getQuats(float4v_tangents, n_vertices);
filament::VertexBuffer::BufferDescriptor normals_descriptor(
float4v_tangents, normal_array_size, DeallocateBuffer);
vbuf->setBufferAt(engine_, 2, std::move(normals_descriptor));
delete orientation;
}
if (update_flags & kUpdateUv0Flag) {
const size_t uv_array_size = n_vertices * 2 * sizeof(float);
if (point_cloud.HasPointAttr("uv")) {
filament::VertexBuffer::BufferDescriptor uv_descriptor(
point_cloud.GetPointAttr("uv").GetDataPtr(),
uv_array_size);
vbuf->setBufferAt(engine_, 3, std::move(uv_descriptor));
} else if (point_cloud.HasPointAttr("__visualization_scalar")) {
// Update in PointCloudBuffers.cpp, too:
// TPointCloudBuffersBuilder::ConstructBuffers
float* uv_array = static_cast<float*>(malloc(uv_array_size));
memset(uv_array, 0, uv_array_size);
auto vis_scalars =
point_cloud.GetPointAttr("__visualization_scalar")
.Contiguous();
const float* src =
static_cast<const float*>(vis_scalars.GetDataPtr());
const size_t n = 2 * n_vertices;
for (size_t i = 0; i < n; i += 2) {
uv_array[i] = *src++;
}
filament::VertexBuffer::BufferDescriptor uv_descriptor(
uv_array, uv_array_size, DeallocateBuffer);
vbuf->setBufferAt(engine_, 3, std::move(uv_descriptor));
}
}
// Update the geometry to reflect new geometry count
if (geometry_update_needed) {
auto& renderable_mgr = engine_.getRenderableManager();
auto inst = renderable_mgr.getInstance(g->filament_entity);
renderable_mgr.setGeometryAt(
inst, 0, filament::RenderableManager::PrimitiveType::POINTS,
0, n_vertices);
}
}
}
void FilamentScene::RemoveGeometry(const std::string& object_name) {
auto geoms = GetGeometry(object_name, false);
if (!geoms.empty()) {
for (auto* g : geoms) {
scene_->remove(g->filament_entity);
g->ReleaseResources(engine_, resource_mgr_);
geometries_.erase(g->name);
}
}
if (GeometryIsModel(object_name)) {
model_geometries_.erase(object_name);
}
}
void FilamentScene::ShowGeometry(const std::string& object_name, bool show) {
auto geoms = GetGeometry(object_name);
for (auto* g : geoms) {
if (g->visible != show) {
g->visible = show;
if (show) {
scene_->addEntity(g->filament_entity);
} else {
scene_->remove(g->filament_entity);
}
}
}
}
bool FilamentScene::GeometryIsVisible(const std::string& object_name) {
auto geoms = GetGeometry(object_name);
if (!geoms.empty()) {
// NOTE: all meshes of model share same visibility so we only need to
// check first entry of this array
return geoms[0]->visible;
} else {
return false;
}
}
utils::EntityInstance<filament::TransformManager>
FilamentScene::GetGeometryTransformInstance(RenderableGeometry* geom) {
filament::TransformManager::Instance itransform;
auto& transform_mgr = engine_.getTransformManager();
itransform = transform_mgr.getInstance(geom->filament_entity);
if (!itransform.isValid()) {
using namespace filament::math;
transform_mgr.create(geom->filament_entity);
itransform = transform_mgr.getInstance(geom->filament_entity);
transform_mgr.create(geom->filament_entity, itransform,
mat4f::translation(float3{0.0f, 0.0f, 0.0f}));
}
return itransform;
}
void FilamentScene::SetGeometryTransform(const std::string& object_name,
const Transform& transform) {
auto geoms = GetGeometry(object_name);
for (auto* g : geoms) {
auto itransform = GetGeometryTransformInstance(g);
if (itransform.isValid()) {
const auto& ematrix = transform.matrix();
auto& transform_mgr = engine_.getTransformManager();
transform_mgr.setTransform(
itransform,
converters::FilamentMatrixFromEigenMatrix(ematrix));
}
}
}
FilamentScene::Transform FilamentScene::GetGeometryTransform(
const std::string& object_name) {
Transform etransform;
auto geoms = GetGeometry(object_name);
if (!geoms.empty()) {
auto itransform = GetGeometryTransformInstance(geoms[0]);
if (itransform.isValid()) {
auto& transform_mgr = engine_.getTransformManager();
auto ftransform = transform_mgr.getTransform(itransform);
etransform = converters::EigenMatrixFromFilamentMatrix(ftransform);
}
}
return etransform;
}
geometry::AxisAlignedBoundingBox FilamentScene::GetGeometryBoundingBox(
const std::string& object_name) {
geometry::AxisAlignedBoundingBox result;
auto geoms = GetGeometry(object_name);
for (auto* g : geoms) {
auto& renderable_mgr = engine_.getRenderableManager();
auto inst = renderable_mgr.getInstance(g->filament_entity);
auto box = renderable_mgr.getAxisAlignedBoundingBox(inst);
auto& transform_mgr = engine_.getTransformManager();
auto itransform = transform_mgr.getInstance(g->filament_entity);
auto transform = transform_mgr.getWorldTransform(itransform);
box = rigidTransform(box, transform);
auto min = box.center - box.halfExtent;
auto max = box.center + box.halfExtent;
result += {{min.x, min.y, min.z}, {max.x, max.y, max.z}};
}
return result;
}
void FilamentScene::GeometryShadows(const std::string& object_name,
bool cast_shadows,
bool receive_shadows) {
auto geoms = GetGeometry(object_name);
for (auto* g : geoms) {
auto& renderable_mgr = engine_.getRenderableManager();
filament::RenderableManager::Instance inst =
renderable_mgr.getInstance(g->filament_entity);
renderable_mgr.setCastShadows(inst, cast_shadows);
renderable_mgr.setReceiveShadows(inst, receive_shadows);
}
}
void FilamentScene::SetGeometryCulling(const std::string& object_name,
bool enable) {
auto geoms = GetGeometry(object_name);
for (auto* g : geoms) {
auto& renderable_mgr = engine_.getRenderableManager();
filament::RenderableManager::Instance inst =
renderable_mgr.getInstance(g->filament_entity);
renderable_mgr.setCulling(inst, enable);
g->culling_enabled = enable;
}
}
void FilamentScene::SetGeometryPriority(const std::string& object_name,
uint8_t priority) {
auto geoms = GetGeometry(object_name);
for (auto* g : geoms) {
auto& renderable_mgr = engine_.getRenderableManager();
filament::RenderableManager::Instance inst =
renderable_mgr.getInstance(g->filament_entity);
renderable_mgr.setPriority(inst, priority);
g->priority = (int)priority;
}
}
void FilamentScene::UpdateDefaultLit(GeometryMaterialInstance& geom_mi) {
auto& material = geom_mi.properties;
auto& maps = geom_mi.maps;
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetColor("baseColor", material.base_color, false)
.SetParameter("pointSize", material.point_size)
.SetParameter("baseRoughness", material.base_roughness)
.SetParameter("baseMetallic", material.base_metallic)
.SetParameter("reflectance", material.base_reflectance)
.SetParameter("clearCoat", material.base_clearcoat)
.SetParameter("clearCoatRoughness",
material.base_clearcoat_roughness)
.SetParameter("anisotropy", material.base_anisotropy)
.SetTexture("albedo", maps.albedo_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("normalMap", maps.normal_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("ao_rough_metalMap", maps.ao_rough_metal_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("reflectanceMap", maps.reflectance_map,
rendering::TextureSamplerParameters::Pretty())
// NOTE: Disabled temporarily to avoid Filament warning until
// defaultLit is reworked to use fewer samplers
// .SetTexture("clearCoatMap", maps.clear_coat_map,
// rendering::TextureSamplerParameters::Pretty())
// .SetTexture("clearCoatRoughnessMap",
// maps.clear_coat_roughness_map,
// rendering::TextureSamplerParameters::Pretty())
// .SetTexture("anisotropyMap", maps.anisotropy_map,
// rendering::TextureSamplerParameters::Pretty())
.Finish();
}
void FilamentScene::UpdateGaussianSplat(GeometryMaterialInstance& geom_mi) {
auto& material = geom_mi.properties;
auto& maps = geom_mi.maps;
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetColor("baseColor", material.base_color, false)
.SetParameter("pointSize", material.point_size)
.SetParameter("baseRoughness", material.base_roughness)
.SetParameter("baseMetallic", material.base_metallic)
.SetParameter("reflectance", material.base_reflectance)
.SetParameter("clearCoat", material.base_clearcoat)
.SetParameter("clearCoatRoughness",
material.base_clearcoat_roughness)
.SetParameter("anisotropy", material.base_anisotropy)
.SetParameter("shDegree", material.sh_degree)
.SetTexture("albedo", maps.albedo_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("normalMap", maps.normal_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("ao_rough_metalMap", maps.ao_rough_metal_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("reflectanceMap", maps.reflectance_map,
rendering::TextureSamplerParameters::Pretty())
.Finish();
}
void FilamentScene::UpdateDefaultLitSSR(GeometryMaterialInstance& geom_mi) {
auto& material = geom_mi.properties;
auto& maps = geom_mi.maps;
auto absorption_float3 = filament::Color::absorptionAtDistance(
filament::math::float3(material.absorption_color.x(),
material.absorption_color.y(),
material.absorption_color.z()),
material.absorption_distance);
Eigen::Vector3f absorption(absorption_float3.x, absorption_float3.y,
absorption_float3.z);
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetColor("baseColor", material.base_color, false)
.SetParameter("pointSize", material.point_size)
.SetParameter("baseRoughness", material.base_roughness)
.SetParameter("baseMetallic", material.base_metallic)
.SetParameter("reflectance", material.base_reflectance)
.SetParameter("clearCoat", material.base_clearcoat)
.SetParameter("clearCoatRoughness",
material.base_clearcoat_roughness)
.SetParameter("anisotropy", material.base_anisotropy)
.SetParameter("thickness", material.thickness)
.SetParameter("transmission", material.transmission)
.SetParameter("absorption", absorption)
.SetTexture("albedo", maps.albedo_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("normalMap", maps.normal_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("ao_rough_metalMap", maps.ao_rough_metal_map,
rendering::TextureSamplerParameters::Pretty())
.SetTexture("reflectanceMap", maps.reflectance_map,
rendering::TextureSamplerParameters::Pretty())
.Finish();
}
void FilamentScene::UpdateDefaultUnlit(GeometryMaterialInstance& geom_mi) {
float srgb = (geom_mi.properties.sRGB_vertex_color ? 1.f : 0.f);
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetColor("baseColor", geom_mi.properties.base_color, true)
.SetParameter("pointSize", geom_mi.properties.point_size)
.SetParameter("srgbColor", srgb)
.SetTexture("albedo", geom_mi.maps.albedo_map,
rendering::TextureSamplerParameters::Pretty())
.Finish();
}
void FilamentScene::UpdateNormalShader(GeometryMaterialInstance& geom_mi) {
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetParameter("pointSize", geom_mi.properties.point_size)
.Finish();
}
void FilamentScene::UpdateDepthShader(GeometryMaterialInstance& geom_mi) {
auto* camera = views_.begin()->second.view->GetCamera();
const float f = float(camera->GetFar());
const float n = float(camera->GetNear());
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetParameter("pointSize", geom_mi.properties.point_size)
.SetParameter("cameraNear", n)
.SetParameter("cameraFar", f)
.Finish();
}
void FilamentScene::UpdateDepthValueShader(GeometryMaterialInstance& geom_mi) {
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetParameter("pointSize", geom_mi.properties.point_size)
.Finish();
}
void FilamentScene::UpdateGradientShader(GeometryMaterialInstance& geom_mi) {
bool isLUT =
(geom_mi.properties.gradient->GetMode() == Gradient::Mode::kLUT);
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetParameter("minValue", geom_mi.properties.scalar_min)
.SetParameter("maxValue", geom_mi.properties.scalar_max)
.SetParameter("isLUT", (isLUT ? 1.0f : 0.0f))
.SetParameter("pointSize", geom_mi.properties.point_size)
.SetTexture(
"gradient", geom_mi.maps.gradient_texture,
isLUT ? rendering::TextureSamplerParameters::Simple()
: rendering::TextureSamplerParameters::LinearClamp())
.Finish();
}
void FilamentScene::UpdateSolidColorShader(GeometryMaterialInstance& geom_mi) {
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetColor("baseColor", geom_mi.properties.base_color, true)
.SetParameter("pointSize", geom_mi.properties.point_size)
.Finish();
}
void FilamentScene::UpdateBackgroundShader(GeometryMaterialInstance& geom_mi) {
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetColor("baseColor", geom_mi.properties.base_color, true)
.SetParameter("aspectRatio", geom_mi.properties.aspect_ratio)
.SetParameter("yOrigin", 1.0f)
.SetTexture("albedo", geom_mi.maps.albedo_map,
rendering::TextureSamplerParameters::LinearClamp())
.Finish();
}
void FilamentScene::UpdateGroundPlaneShader(GeometryMaterialInstance& geom_mi) {
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetColor("baseColor", geom_mi.properties.base_color, true)
.SetParameter("axis", geom_mi.properties.ground_plane_axis)
.Finish();
}
void FilamentScene::UpdateLineShader(GeometryMaterialInstance& geom_mi) {
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetColor("baseColor", geom_mi.properties.base_color, true)
.SetColor("emissiveColor", geom_mi.properties.emissive_color, false)
.SetParameter("lineWidth", geom_mi.properties.line_width)
.Finish();
}
void FilamentScene::UpdateUnlitPolygonOffsetShader(
GeometryMaterialInstance& geom_mi) {
renderer_.ModifyMaterial(geom_mi.mat_instance)
.SetParameter("pointSize", geom_mi.properties.point_size)
.Finish();
}