-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathtestbed.cu
2288 lines (1968 loc) · 85.1 KB
/
testbed.cu
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) 2020-2022, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
/** @file testbed.cu
* @author Thomas Müller & Alex Evans, NVIDIA
*/
#include <neural-graphics-primitives/common.h>
#include <neural-graphics-primitives/common_device.cuh>
#include <neural-graphics-primitives/json_binding.h>
#include <neural-graphics-primitives/marching_cubes.h>
#include <neural-graphics-primitives/nerf_loader.h>
#include <neural-graphics-primitives/nerf_network.h>
#include <neural-graphics-primitives/render_buffer.h>
#include <neural-graphics-primitives/takikawa_encoding.cuh>
#include <neural-graphics-primitives/testbed.h>
#include <neural-graphics-primitives/tinyexr_wrapper.h>
#include <neural-graphics-primitives/trainable_buffer.cuh>
#include <neural-graphics-primitives/triangle_bvh.cuh>
#include <neural-graphics-primitives/triangle_octree.cuh>
#include <tiny-cuda-nn/encodings/grid.h>
#include <tiny-cuda-nn/loss.h>
#include <tiny-cuda-nn/network.h>
#include <tiny-cuda-nn/network_with_input_encoding.h>
#include <tiny-cuda-nn/optimizer.h>
#include <tiny-cuda-nn/trainer.h>
#include <json/json.hpp>
#include <filesystem/path.h>
#include <fstream>
#ifdef NGP_GUI
# include <imgui/imgui.h>
# include <imgui/backends/imgui_impl_glfw.h>
# include <imgui/backends/imgui_impl_opengl3.h>
# include <imguizmo/ImGuizmo.h>
# ifdef _WIN32
# include <GL/gl3w.h>
# else
# include <GL/glew.h>
# endif
# include <GLFW/glfw3.h>
#endif
#undef min
#undef max
using namespace Eigen;
using namespace tcnn;
namespace fs = filesystem;
NGP_NAMESPACE_BEGIN
std::atomic<size_t> g_total_n_bytes_allocated{0};
json merge_parent_network_config(const json &child, const fs::path &child_filename) {
if (!child.contains("parent")) {
return child;
}
fs::path parent_filename = child_filename.parent_path() / std::string(child["parent"]);
tlog::info() << "Loading parent network config from: " << parent_filename.str();
std::ifstream f{parent_filename.str()};
json parent = json::parse(f, nullptr, true, true);
parent = merge_parent_network_config(parent, parent_filename);
parent.merge_patch(child);
return parent;
}
static bool ends_with(const std::string& str, const std::string& ending) {
if (ending.length() > str.length()) {
return false;
}
return std::equal(std::rbegin(ending), std::rend(ending), std::rbegin(str));
}
void Testbed::load_training_data(const std::string& data_path) {
m_data_path = data_path;
if (!m_data_path.exists()) {
throw std::runtime_error{std::string{"Data path '"} + m_data_path.str() + "' does not exist."};
}
switch (m_testbed_mode) {
case ETestbedMode::Nerf: load_nerf(); break;
case ETestbedMode::Sdf: load_mesh(); break;
case ETestbedMode::Image: load_image(); break;
case ETestbedMode::Volume:load_volume(); break;
default: throw std::runtime_error{"Invalid testbed mode."};
}
m_training_data_available = true;
}
void Testbed::clear_training_data() {
m_training_data_available = false;
m_nerf.training.dataset.images_data.free_memory();
m_nerf.training.dataset.rays_data.free_memory();
}
json Testbed::load_network_config(const fs::path& network_config_path) {
if (!network_config_path.empty()) {
m_network_config_path = network_config_path;
}
tlog::info() << "Loading network config from: " << network_config_path;
if (network_config_path.empty() || !network_config_path.exists()) {
throw std::runtime_error{std::string{"Network config \""} + network_config_path.str() + "\" does not exist."};
}
json result;
if (equals_case_insensitive(network_config_path.extension(), "json")) {
std::ifstream f{network_config_path.str()};
result = json::parse(f, nullptr, true, true);
result = merge_parent_network_config(result, network_config_path);
} else if (equals_case_insensitive(network_config_path.extension(), "msgpack")) {
std::ifstream f{network_config_path.str(), std::ios::in | std::ios::binary};
result = json::from_msgpack(f);
// we assume parent pointers are already resolved in snapshots.
}
return result;
}
void Testbed::reload_network_from_file(const std::string& network_config_path) {
if (!network_config_path.empty()) {
m_network_config_path = network_config_path;
}
m_network_config = load_network_config(m_network_config_path);
reset_network();
}
void Testbed::reload_network_from_json(const json& json, const std::string& config_base_path) {
// config_base_path is needed so that if the passed in json uses the 'parent' feature, we know where to look...
// be sure to use a filename, or if a directory, end with a trailing slash
m_network_config = merge_parent_network_config(json, config_base_path);
reset_network();
}
void Testbed::handle_file(const std::string& file) {
if (ends_with(file, ".msgpack")) {
load_snapshot(file);
}
else if (ends_with(file, ".json")) {
reload_network_from_file(file);
} else if (ends_with(file, ".obj")) {
m_data_path = file;
m_testbed_mode = ETestbedMode::Sdf;
load_mesh();
} else if (ends_with(file, ".exr") || ends_with(file, ".bin")) {
m_data_path = file;
m_testbed_mode = ETestbedMode::Image;
try {
load_image();
} catch (std::runtime_error& e) {
tlog::error() << "Failed to open image: " << e.what();
return;
}
} else if (ends_with(file, ".nvdb")) {
m_data_path = file;
m_testbed_mode = ETestbedMode::Volume;
try {
load_volume();
} catch (std::runtime_error& e) {
tlog::error() << "Failed to open volume: " << e.what();
return;
}
} else {
tlog::error() << "Tried to open unknown file type: " << file;
}
}
void Testbed::reset_accumulation() {
m_windowless_render_surface.reset_accumulation();
for (auto& tex : m_render_surfaces) {
tex.reset_accumulation();
}
}
void Testbed::set_visualized_dim(int dim) {
m_visualized_dimension = dim;
reset_accumulation();
}
void Testbed::translate_camera(const Vector3f& rel) {
m_camera.col(3) += m_camera.block<3,3>(0,0) * rel * m_bounding_radius;
reset_accumulation();
}
void Testbed::set_nerf_camera_matrix(const Matrix<float, 3, 4>& cam) {
m_camera = m_nerf.training.dataset.nerf_matrix_to_ngp(cam);
}
Vector3f Testbed::look_at() const {
return view_pos() + view_dir() * m_scale;
}
void Testbed::set_look_at(const Vector3f& pos) {
m_camera.col(3) += pos - look_at();
}
void Testbed::set_scale(float scale) {
auto prev_look_at = look_at();
m_camera.col(3) = (view_pos() - prev_look_at) * (scale / m_scale) + prev_look_at;
m_scale = scale;
}
void Testbed::set_view_dir(const Vector3f& dir) {
auto old_look_at = look_at();
m_camera.col(0) = dir.cross(m_up_dir).normalized();
m_camera.col(1) = dir.cross(m_camera.col(0)).normalized();
m_camera.col(2) = dir.normalized();
set_look_at(old_look_at);
}
void Testbed::set_camera_to_training_view(int trainview) {
auto old_look_at = look_at();
m_camera = m_smoothed_camera = m_nerf.training.dataset.xforms[trainview].start;
m_relative_focal_length = m_nerf.training.dataset.metadata[trainview].focal_length / (float)m_nerf.training.image_resolution[m_fov_axis];
m_scale = std::max((old_look_at - view_pos()).dot(view_dir()), 0.1f);
m_nerf.render_with_camera_distortion = true;
m_nerf.render_distortion = m_nerf.training.dataset.metadata[trainview].camera_distortion;
m_screen_center = Vector2f::Constant(1.0f) - m_nerf.training.dataset.metadata[0].principal_point;
}
void Testbed::reset_camera() {
m_fov_axis = 1;
set_fov(50.625f);
m_zoom = 1.f;
m_screen_center = Vector2f::Constant(0.5f);
m_scale = 1.5f;
m_camera <<
1.0f, 0.0f, 0.0f, 0.5f,
0.0f, -1.0f, 0.0f, 0.5f,
0.0f, 0.0f, -1.0f, 0.5f;
m_camera.col(3) -= m_scale * view_dir();
m_smoothed_camera = m_camera;
m_up_dir = {0.0f, 1.0f, 0.0f};
m_sun_dir = Vector3f::Ones().normalized();
reset_accumulation();
}
void Testbed::set_train(bool mtrain) {
if (m_train && !mtrain && m_max_level_rand_training) {
set_max_level(1.f);
}
m_train = mtrain;
}
std::string get_filename_in_data_path_with_suffix(fs::path data_path, fs::path network_config_path, const char* suffix) {
// use the network config name along with the data path to build a filename with the requested suffix & extension
std::string default_name = network_config_path.basename();
if (default_name == "") default_name = "base";
if (data_path.empty())
return default_name + std::string(suffix);
if (data_path.is_directory())
return (data_path / (default_name + std::string{suffix})).str();
else
return data_path.stem().str() + "_" + default_name + std::string(suffix);
}
void Testbed::compute_and_save_marching_cubes_mesh(const char* filename, Vector3i res3d , BoundingBox aabb, float thresh, bool unwrap_it) {
if (aabb.is_empty()) {
aabb = m_testbed_mode == ETestbedMode::Nerf ? m_render_aabb : m_aabb;
}
marching_cubes(res3d, aabb, thresh);
save_mesh(m_mesh.verts, m_mesh.vert_normals, m_mesh.vert_colors, m_mesh.indices, filename, unwrap_it, m_nerf.training.dataset.scale, m_nerf.training.dataset.offset);
}
inline float linear_to_db(float x) {
return -10.f*logf(x)/logf(10.f);
}
void Testbed::dump_parameters_as_images() {
size_t non_layer_params_width = 2048;
size_t layer_params = 0;
for (auto size : m_network->layer_sizes()) {
layer_params += size.first * size.second;
}
size_t non_layer_params = m_network->n_params() - layer_params;
float* params = m_trainer->params();
std::vector<float> params_cpu(layer_params + next_multiple(non_layer_params, non_layer_params_width), 0.0f);
CUDA_CHECK_THROW(cudaMemcpy(params_cpu.data(), params, m_network->n_params() * sizeof(float), cudaMemcpyDeviceToHost));
size_t offset = 0;
size_t layer_id = 0;
for (auto size : m_network->layer_sizes()) {
std::string filename = std::string{"layer-"} + std::to_string(layer_id) + ".exr";
save_exr(params_cpu.data() + offset, size.second, size.first, 1, 1, filename.c_str());
offset += size.first * size.second;
++layer_id;
}
std::string filename = "non-layer.exr";
save_exr(params_cpu.data() + offset, non_layer_params_width, non_layer_params / non_layer_params_width, 1, 1, filename.c_str());
}
#ifdef NGP_GUI
bool imgui_colored_button(const char *name, float hue) {
ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f));
bool rv = ImGui::Button(name);
ImGui::PopStyleColor(3);
return rv;
}
void Testbed::imgui() {
m_picture_in_picture_res = 0;
if (int read = ImGui::Begin("Camera Path", 0, ImGuiWindowFlags_NoScrollbar)) {
static char path_filename_buf[128] = "";
if (path_filename_buf[0] == '\0') {
snprintf(path_filename_buf, sizeof(path_filename_buf), "%s", get_filename_in_data_path_with_suffix(m_data_path, m_network_config_path, "_cam.json").c_str());
}
if (m_camera_path.imgui(path_filename_buf, m_frame_milliseconds, m_camera, m_slice_plane_z, m_scale, fov(), m_dof, m_bounding_radius,
!m_nerf.training.dataset.xforms.empty() ? m_nerf.training.dataset.xforms[0].start : Matrix<float, 3, 4>::Identity())) {
if (m_camera_path.m_update_cam_from_path) {
set_camera_from_time(m_camera_path.m_playtime);
if (read>1) m_smoothed_camera=m_camera;
reset_accumulation();
} else {
m_pip_render_surface->reset_accumulation();
}
}
if (!m_camera_path.m_keyframes.empty()) {
float w = ImGui::GetContentRegionAvail().x;
m_picture_in_picture_res = (float)std::min((int(w)+31)&(~31),1920/4);
if (m_camera_path.m_update_cam_from_path)
ImGui::Image((ImTextureID)(size_t)m_render_textures.front()->texture(), ImVec2(w,w*9.f/16.f));
else
ImGui::Image((ImTextureID)(size_t)m_pip_render_texture->texture(), ImVec2(w,w*9.f/16.f));
}
}
ImGui::End();
ImGui::Begin("instant-ngp v" NGP_VERSION);
size_t n_bytes = tcnn::total_n_bytes_allocated() + g_total_n_bytes_allocated;
ImGui::Text("Frame: %.3f ms (%.1f FPS); Mem: %s", m_gui_elapsed_ms, 1000.0f / m_gui_elapsed_ms, bytes_to_string(n_bytes).c_str());
bool accum_reset = false;
if (!m_training_data_available) {
ImGui::BeginDisabled();
}
if (ImGui::CollapsingHeader("Training", m_training_data_available ? ImGuiTreeNodeFlags_DefaultOpen : 0)) {
if (imgui_colored_button(m_train ? "Stop training" : "Start training", 0.4)) {
set_train(!m_train);
}
ImGui::SameLine();
ImGui::Checkbox("Train encoding", &m_train_encoding);
ImGui::SameLine();
ImGui::Checkbox("Train network", &m_train_network);
ImGui::SameLine();
ImGui::Checkbox("Random levels", &m_max_level_rand_training);
if (m_testbed_mode == ETestbedMode::Nerf) {
ImGui::Checkbox("Train envmap", &m_nerf.training.train_envmap);
ImGui::SameLine();
ImGui::Checkbox("Train extrinsics", &m_nerf.training.optimize_extrinsics);
ImGui::SameLine();
ImGui::Checkbox("Train exposure", &m_nerf.training.optimize_exposure);
ImGui::SameLine();
ImGui::Checkbox("Train distortion", &m_nerf.training.optimize_distortion);
}
if (imgui_colored_button("Reset training", 0.f)) {
reload_network_from_file("");
}
ImGui::SameLine();
ImGui::DragInt("Seed", (int*)&m_seed, 1.0f, 0, std::numeric_limits<int>::max());
if (m_train) {
ImGui::Text("%s: %dms, Training: %dms", m_testbed_mode == ETestbedMode::Nerf ? "Grid" : "Datagen", (int)m_training_prep_milliseconds, (int)m_training_milliseconds);
} else {
ImGui::Text("Training paused");
}
if (m_testbed_mode == ETestbedMode::Nerf) {
ImGui::Text("Rays per batch: %d, Batch size: %d/%d", m_nerf.training.counters_rgb.rays_per_batch, m_nerf.training.counters_rgb.measured_batch_size, m_nerf.training.counters_rgb.measured_batch_size_before_compaction);
}
ImGui::Text("Steps: %d, Loss: %0.6f (%0.2f dB)", m_training_step, m_loss_scalar, linear_to_db(m_loss_scalar));
ImGui::PlotLines("loss graph", m_loss_graph, std::min(m_loss_graph_samples, 256u), (m_loss_graph_samples < 256u) ? 0 : (m_loss_graph_samples & 255u), 0, FLT_MAX, FLT_MAX, ImVec2(0, 50.f));
if (m_testbed_mode == ETestbedMode::Nerf && ImGui::TreeNode("NeRF training options")) {
ImGui::Checkbox("Random bg color", &m_nerf.training.random_bg_color);
ImGui::SameLine();
ImGui::Checkbox("Snap to pixel centers", &m_nerf.training.snap_to_pixel_centers);
ImGui::SliderFloat("Near distance", &m_nerf.training.near_distance, 0.0f, 1.0f);
accum_reset |= ImGui::Checkbox("Linear colors", &m_nerf.training.linear_colors);
ImGui::Combo("Loss", (int*)&m_nerf.training.loss_type, LossTypeStr);
ImGui::Combo("RGB activation", (int*)&m_nerf.rgb_activation, NerfActivationStr);
ImGui::Combo("Density activation", (int*)&m_nerf.density_activation, NerfActivationStr);
ImGui::SliderFloat("Cone angle", &m_nerf.cone_angle_constant, 0.0f, 1.0f/128.0f);
// Importance sampling options, but still related to training
ImGui::Checkbox("Sample focal plane ~error", &m_nerf.training.sample_focal_plane_proportional_to_error);
ImGui::SameLine();
ImGui::Checkbox("Sample focal plane ~sharpness", &m_nerf.training.include_sharpness_in_error);
ImGui::Checkbox("Sample image ~error", &m_nerf.training.sample_image_proportional_to_error);
ImGui::Text("%dx%d error res w/ %d steps between updates", m_nerf.training.error_map.resolution.x(), m_nerf.training.error_map.resolution.y(), m_nerf.training.n_steps_between_error_map_updates);
ImGui::Checkbox("Display error overlay", &m_nerf.training.render_error_overlay);
if (m_nerf.training.render_error_overlay) {
ImGui::SliderFloat("Error overlay brightness", &m_nerf.training.error_overlay_brightness, 0.f, 1.f);
}
ImGui::SliderFloat("Density grid decay", &m_nerf.training.density_grid_decay, 0.f, 1.f,"%.4f");
ImGui::SliderFloat("Extrinsic L2 reg.", &m_nerf.training.extrinsic_l2_reg, 1e-8f, 0.1f, "%.6f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat);
ImGui::SliderFloat("Intrinsic L2 reg.", &m_nerf.training.intrinsic_l2_reg, 1e-8f, 0.1f, "%.6f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat);
ImGui::SliderFloat("Exposure L2 reg.", &m_nerf.training.exposure_l2_reg, 1e-8f, 0.1f, "%.6f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat);
ImGui::TreePop();
}
if (m_testbed_mode == ETestbedMode::Sdf && ImGui::TreeNode("SDF training options")) {
accum_reset |= ImGui::Checkbox("Use octree for acceleration", &m_sdf.use_triangle_octree);
accum_reset |= ImGui::Combo("Mesh SDF mode", (int*)&m_sdf.mesh_sdf_mode, MeshSdfModeStr);
accum_reset |= ImGui::SliderFloat("Surface offset scale", &m_sdf.training.surface_offset_scale, 0.125f, 1024.0f, "%.4f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat);
if (ImGui::Checkbox("Calculate IoU", &m_sdf.calculate_iou_online)) {
m_sdf.iou_decay = 0;
}
ImGui::SameLine();
ImGui::Text("%0.6f", m_sdf.iou);
ImGui::TreePop();
}
if (m_testbed_mode == ETestbedMode::Image && ImGui::TreeNode("Image training options")) {
ImGui::Combo("Training coords", (int*)&m_image.random_mode, RandomModeStr);
ImGui::TreePop();
}
if (m_testbed_mode == ETestbedMode::Volume && ImGui::CollapsingHeader("Volume training options")) {
accum_reset |= ImGui::SliderFloat("Albedo", &m_volume.albedo, 0.f, 1.f);
accum_reset |= ImGui::SliderFloat("Scattering", &m_volume.scattering, -2.f, 2.f);
accum_reset |= ImGui::SliderFloat("Distance Scale", &m_volume.inv_distance_scale, 1.f, 100.f, "%.3g", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat);
ImGui::TreePop();
}
}
if (!m_training_data_available) {
ImGui::EndDisabled();
}
if (ImGui::CollapsingHeader("Rendering", ImGuiTreeNodeFlags_DefaultOpen)) {
ImGui::Checkbox("Render", &m_render);
ImGui::SameLine();
ImGui::Text(": %dms", (int)m_frame_milliseconds);
ImGui::Checkbox("Dynamic resolution", &m_dynamic_res);
ImGui::SameLine();
const auto& render_tex = m_render_surfaces.front();
ImGui::Text("%dx%d at %d spp", render_tex.resolution().x(), render_tex.resolution().y(), render_tex.spp());
ImGui::SliderInt("Max spp", &m_max_spp, 0, 1024, "%d", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat );
if (!m_dynamic_res) {
ImGui::SliderInt("Fixed resolution factor", &m_fixed_res_factor, 8, 64);
}
if (m_testbed_mode == ETestbedMode::Nerf && m_nerf_network->n_extra_dims() == 3) {
Vector3f light_dir = m_nerf.light_dir.normalized();
if (ImGui::TreeNodeEx("Light Dir (Polar)", ImGuiTreeNodeFlags_DefaultOpen)) {
float phi = atan2f(m_nerf.light_dir.x(), m_nerf.light_dir.z());
float theta = asinf(m_nerf.light_dir.y());
bool spin = ImGui::SliderFloat("Light Dir Theta", &theta, -PI() / 2.0f, PI() / 2.0f);
spin |= ImGui::SliderFloat("Light Dir Phi", &phi, -PI(), PI());
if (spin) {
float sin_phi, cos_phi;
sincosf(phi, &sin_phi, &cos_phi);
float cos_theta=cosf(theta);
m_nerf.light_dir = {sin_phi * cos_theta,sinf(theta),cos_phi * cos_theta};
accum_reset = true;
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Light Dir (Cartesian)")) {
accum_reset |= ImGui::SliderFloat("Light Dir X", ((float*)(&m_nerf.light_dir)) + 0, -1.0f, 1.0f);
accum_reset |= ImGui::SliderFloat("Light Dir Y", ((float*)(&m_nerf.light_dir)) + 1, -1.0f, 1.0f);
accum_reset |= ImGui::SliderFloat("Light Dir Z", ((float*)(&m_nerf.light_dir)) + 2, -1.0f, 1.0f);
ImGui::TreePop();
}
}
accum_reset |= ImGui::Combo("Render mode", (int*)&m_render_mode, RenderModeStr);
accum_reset |= ImGui::Combo("Color space", (int*)&m_color_space, ColorSpaceStr);
accum_reset |= ImGui::Combo("Tonemap curve", (int*)&m_tonemap_curve, TonemapCurveStr);
accum_reset |= ImGui::ColorEdit4("Background", &m_background_color[0]);
if (ImGui::SliderFloat("Exposure", &m_exposure, -5.f, 5.f)) {
set_exposure(m_exposure);
}
accum_reset |= ImGui::Checkbox("Snap to pixel centers", &m_snap_to_pixel_centers);
float max_diam = (m_aabb.max-m_aabb.min).maxCoeff();
float render_diam = (m_render_aabb.max-m_render_aabb.min).maxCoeff();
float old_render_diam = render_diam;
if (ImGui::SliderFloat("Crop size", &render_diam, 0.1f, max_diam, "%.3f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat)) {
accum_reset = true;
if (old_render_diam > 0.f && render_diam > 0.f) {
const Vector3f center = (m_render_aabb.max + m_render_aabb.min) * 0.5f;
float scale = render_diam / old_render_diam;
m_render_aabb.max = ((m_render_aabb.max-center) * scale + center).cwiseMin(m_aabb.max);
m_render_aabb.min = ((m_render_aabb.min-center) * scale + center).cwiseMax(m_aabb.min);
}
}
if (ImGui::TreeNode("Crop aabb")) {
accum_reset |= ImGui::SliderFloat("Min x", ((float*)&m_render_aabb.min)+0, m_aabb.min.x(), m_render_aabb.max.x(), "%.3f");
accum_reset |= ImGui::SliderFloat("Min y", ((float*)&m_render_aabb.min)+1, m_aabb.min.y(), m_render_aabb.max.y(), "%.3f");
accum_reset |= ImGui::SliderFloat("Min z", ((float*)&m_render_aabb.min)+2, m_aabb.min.z(), m_render_aabb.max.z(), "%.3f");
ImGui::Separator();
accum_reset |= ImGui::SliderFloat("Max x", ((float*)&m_render_aabb.max)+0, m_render_aabb.min.x(), m_aabb.max.x(), "%.3f");
accum_reset |= ImGui::SliderFloat("Max y", ((float*)&m_render_aabb.max)+1, m_render_aabb.min.y(), m_aabb.max.y(), "%.3f");
accum_reset |= ImGui::SliderFloat("Max z", ((float*)&m_render_aabb.max)+2, m_render_aabb.min.z(), m_aabb.max.z(), "%.3f");
ImGui::TreePop();
}
if (m_testbed_mode == ETestbedMode::Nerf && ImGui::TreeNode("NeRF rendering options")) {
accum_reset |= ImGui::Checkbox("Apply lens distortion", &m_nerf.render_with_camera_distortion);
if (m_nerf.render_with_camera_distortion) {
accum_reset |= ImGui::Combo("Distortion mode", (int*)&m_nerf.render_distortion.mode, "None\0Iterative\0F-Theta\0");
if (m_nerf.render_distortion.mode == ECameraDistortionMode::Iterative) {
accum_reset |= ImGui::InputFloat("k1", &m_nerf.render_distortion.params[0], 0.f, 0.f, "%.5f");
accum_reset |= ImGui::InputFloat("k2", &m_nerf.render_distortion.params[1], 0.f, 0.f, "%.5f");
accum_reset |= ImGui::InputFloat("p1", &m_nerf.render_distortion.params[2], 0.f, 0.f, "%.5f");
accum_reset |= ImGui::InputFloat("p2", &m_nerf.render_distortion.params[3], 0.f, 0.f, "%.5f");
}
else if (m_nerf.render_distortion.mode == ECameraDistortionMode::FTheta) {
accum_reset |= ImGui::InputFloat("width", &m_nerf.render_distortion.params[5], 0.f, 0.f, "%.0f");
accum_reset |= ImGui::InputFloat("height", &m_nerf.render_distortion.params[6], 0.f, 0.f, "%.0f");
accum_reset |= ImGui::InputFloat("f_theta p0", &m_nerf.render_distortion.params[0], 0.f, 0.f, "%.5f");
accum_reset |= ImGui::InputFloat("f_theta p1", &m_nerf.render_distortion.params[1], 0.f, 0.f, "%.5f");
accum_reset |= ImGui::InputFloat("f_theta p2", &m_nerf.render_distortion.params[2], 0.f, 0.f, "%.5f");
accum_reset |= ImGui::InputFloat("f_theta p3", &m_nerf.render_distortion.params[3], 0.f, 0.f, "%.5f");
accum_reset |= ImGui::InputFloat("f_theta p4", &m_nerf.render_distortion.params[4], 0.f, 0.f, "%.5f");
}
}
ImGui::TreePop();
}
if (m_testbed_mode == ETestbedMode::Sdf && ImGui::TreeNode("SDF rendering options")) {
accum_reset |= ImGui::Checkbox("Analytic normals", &m_sdf.analytic_normals);
accum_reset |= ImGui::SliderFloat("Normals epsilon", &m_sdf.fd_normals_epsilon, 0.00001f, 0.1f, "%.6g", ImGuiSliderFlags_Logarithmic);
accum_reset |= ImGui::SliderFloat("Maximum distance", &m_sdf.maximum_distance, 0.00001f, 0.1f, "%.6g", ImGuiSliderFlags_Logarithmic);
accum_reset |= ImGui::SliderFloat("Shadow sharpness", &m_sdf.shadow_sharpness, 0.1f, 2048.0f, "%.6g", ImGuiSliderFlags_Logarithmic);
accum_reset |= ImGui::SliderFloat("Inflate (offset the zero set)", &m_sdf.zero_offset, -0.25f, 0.25f);
accum_reset |= ImGui::SliderFloat("Distance scale", &m_sdf.distance_scale, 0.25f, 1.f);
ImGui::TreePop();
}
if (ImGui::TreeNode("Debug visualization")) {
ImGui::Checkbox("Visualize unit cube", &m_visualize_unit_cube);
if (m_testbed_mode == ETestbedMode::Nerf) {
ImGui::SameLine();
ImGui::Checkbox("Visualize cameras", &m_nerf.visualize_cameras);
accum_reset |= ImGui::SliderInt("Show acceleration", &m_nerf.show_accel, -1, 7);
}
if (!m_single_view) {
ImGui::BeginDisabled();
}
if (ImGui::SliderInt("Visualized dimension", &m_visualized_dimension, -1, (int)network_width(m_visualized_layer)-1)) {
set_visualized_dim(m_visualized_dimension);
}
if (!m_single_view) {
ImGui::EndDisabled();
}
if (ImGui::SliderInt("Visualized layer", &m_visualized_layer, 0, (int)network_num_forward_activations()-1)) {
set_visualized_layer(m_visualized_layer);
}
if (ImGui::Checkbox("Single view", &m_single_view)) {
if (!m_single_view) {
set_visualized_dim(-1);
}
accum_reset = true;
}
if (m_testbed_mode == ETestbedMode::Nerf) {
if (ImGui::SliderInt("Training view", &m_nerf.training.view, 0, (int)m_nerf.training.dataset.n_images-1)) {
set_camera_to_training_view(m_nerf.training.view);
accum_reset = true;
}
ImGui::PlotLines("Training view error", m_nerf.training.error_map.pmf_img_cpu.data(), m_nerf.training.error_map.pmf_img_cpu.size(), 0, nullptr, 0.0f, FLT_MAX, ImVec2(0, 60.f));
if (m_nerf.training.optimize_exposure) {
std::vector<float> exposures(m_nerf.training.dataset.n_images);
for (uint32_t i = 0; i < m_nerf.training.dataset.n_images; ++i) {
exposures[i] = m_nerf.training.cam_exposure[i].variable().x();
}
ImGui::PlotLines("Training view exposures", exposures.data(), exposures.size(), 0, nullptr, FLT_MAX, FLT_MAX, ImVec2(0, 60.f));
}
}
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Camera", ImGuiTreeNodeFlags_DefaultOpen)) {
accum_reset |= ImGui::SliderFloat("Depth of field", &m_dof, 0.0f, 0.1f);
float local_fov = fov();
if (ImGui::SliderFloat("Field of view", &local_fov, 0.0f, 120.0f)) {
set_fov(local_fov);
accum_reset = true;
}
accum_reset |= ImGui::SliderFloat("Zoom", &m_zoom, 1.f, 10.f);
if (m_testbed_mode == ETestbedMode::Sdf) {
accum_reset |= ImGui::Checkbox("Floor", &m_floor_enable);
ImGui::SameLine();
}
ImGui::Checkbox("First person controls", &m_fps_camera);
ImGui::SameLine();
ImGui::Checkbox("Smooth camera motion", &m_camera_smoothing);
ImGui::SameLine();
ImGui::Checkbox("Autofocus", &m_autofocus);
if (ImGui::TreeNode("Advanced camera settings")) {
accum_reset |= ImGui::SliderFloat2("Screen center", &m_screen_center.x(), 0.f, 1.f);
accum_reset |= ImGui::SliderFloat("Slice / Focus depth", &m_slice_plane_z, -m_bounding_radius, m_bounding_radius);
char buf[2048];
Vector3f v = view_dir();
Vector3f p = look_at();
Vector3f s = m_sun_dir;
Vector3f u = m_up_dir;
Array4f b = m_background_color;
snprintf(buf, sizeof(buf),
"testbed.background_color = [%0.3f, %0.3f, %0.3f, %0.3f]\n"
"testbed.exposure = %0.3f\n"
"testbed.sun_dir = [%0.3f,%0.3f,%0.3f]\n"
"testbed.up_dir = [%0.3f,%0.3f,%0.3f]\n"
"testbed.view_dir = [%0.3f,%0.3f,%0.3f]\n"
"testbed.look_at = [%0.3f,%0.3f,%0.3f]\n"
"testbed.scale = %0.3f\n"
"testbed.fov,testbed.dof,testbed.slice_plane_z = %0.3f,%0.3f,%0.3f\n"
"testbed.autofocus_target = [%0.3f,%0.3f,%0.3f]\n"
"testbed.autofocus = %s\n\n"
, b.x(), b.y(), b.z(), b.w()
, m_exposure
, s.x(), s.y(), s.z()
, u.x(), u.y(), u.z()
, v.x(), v.y(), v.z()
, p.x(), p.y(), p.z()
, scale()
, fov(), m_dof, m_slice_plane_z
, m_autofocus_target.x(), m_autofocus_target.y(), m_autofocus_target.z()
, m_autofocus ? "True" : "False"
);
if (m_testbed_mode == ETestbedMode::Sdf) {
size_t n = strlen(buf);
snprintf(buf+n, sizeof(buf)-n,
"testbed.sdf.shadow_sharpness = %0.3f\n"
"testbed.sdf.analytic_normals = %s\n"
"testbed.sdf.use_triangle_octree = %s\n\n"
"testbed.sdf.brdf.metallic = %0.3f\n"
"testbed.sdf.brdf.subsurface = %0.3f\n"
"testbed.sdf.brdf.specular = %0.3f\n"
"testbed.sdf.brdf.roughness = %0.3f\n"
"testbed.sdf.brdf.sheen = %0.3f\n"
"testbed.sdf.brdf.clearcoat = %0.3f\n"
"testbed.sdf.brdf.clearcoat_gloss = %0.3f\n"
"testbed.sdf.brdf.basecolor = [%0.3f,%0.3f,%0.3f]\n\n"
, m_sdf.shadow_sharpness
, m_sdf.analytic_normals ? "True" : "False"
, m_sdf.use_triangle_octree ? "True" : "False"
, m_sdf.brdf.metallic
, m_sdf.brdf.subsurface
, m_sdf.brdf.specular
, m_sdf.brdf.roughness
, m_sdf.brdf.sheen
, m_sdf.brdf.clearcoat
, m_sdf.brdf.clearcoat_gloss
, m_sdf.brdf.basecolor.x()
, m_sdf.brdf.basecolor.y()
, m_sdf.brdf.basecolor.z()
);
}
ImGui::InputTextMultiline("Params", buf, sizeof(buf));
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Snapshot")) {
static char snapshot_filename_buf[128] = "";
if (snapshot_filename_buf[0] == '\0') {
snprintf(snapshot_filename_buf, sizeof(snapshot_filename_buf), "%s", get_filename_in_data_path_with_suffix(m_data_path, m_network_config_path, ".msgpack").c_str());
}
ImGui::Text("Snapshot");
ImGui::SameLine();
if (ImGui::Button("Save")) {
save_snapshot(snapshot_filename_buf, m_include_optimizer_state_in_snapshot);
}
ImGui::SameLine();
static std::string snapshot_load_error_string = "";
if (ImGui::Button("Load")) {
try {
load_snapshot(snapshot_filename_buf);
} catch (std::exception& e) {
ImGui::OpenPopup("Snapshot load error");
snapshot_load_error_string = std::string{"Failed to load snapshot: "} + e.what();
}
}
ImGui::SameLine();
if (ImGui::Button("Dump parameters as images")) {
dump_parameters_as_images();
}
if (ImGui::BeginPopupModal("Snapshot load error", NULL, ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::Text("%s", snapshot_load_error_string.c_str());
if (ImGui::Button("OK", ImVec2(120, 0))) {
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::SameLine();
ImGui::Checkbox("w/ Optimizer State", &m_include_optimizer_state_in_snapshot);
ImGui::InputText("File", snapshot_filename_buf, sizeof(snapshot_filename_buf));
}
if (m_testbed_mode == ETestbedMode::Nerf || m_testbed_mode == ETestbedMode::Sdf) {
if (ImGui::CollapsingHeader("Marching Cubes Mesh Output")) {
BoundingBox aabb = (m_testbed_mode==ETestbedMode::Nerf) ? m_render_aabb : m_aabb;
auto res3d = get_marching_cubes_res(m_mesh.res, aabb);
if (imgui_colored_button("Mesh it!", 0.4f)) {
marching_cubes(res3d, aabb, m_mesh.thresh);
m_nerf.render_with_camera_distortion = false;
}
if (m_mesh.indices.size()>0) {
ImGui::SameLine();
if (imgui_colored_button("Clear Mesh", 0.f)) {
m_mesh.clear();
}
}
ImGui::SameLine();
static bool flip_y_and_z_axes = false;
if (imgui_colored_button("Save density PNG",-0.4f)) {
char fname[128];
snprintf(fname, sizeof(fname), "density_slices_%dx%dx%d.png", res3d.x(), res3d.y(), res3d.z());
GPUMemory<float> density = get_density_on_grid(res3d, aabb);
save_density_grid_to_png(density, (m_data_path / fname).str().c_str(), res3d, m_mesh.thresh, flip_y_and_z_axes);
}
if (m_testbed_mode == ETestbedMode::Nerf) {
ImGui::SameLine();
if (imgui_colored_button("Save RGBA PNG sequence", 0.2f)) {
auto effective_view_dir = flip_y_and_z_axes ? Vector3f{0.0f, 1.0f, 0.0f} : Vector3f{0.0f, 0.0f, 1.0f};
GPUMemory<Array4f> rgba = get_rgba_on_grid(res3d, effective_view_dir);
auto dir = m_data_path / "rgba_slices";
if (!dir.exists()) {
fs::create_directory(dir);
}
save_rgba_grid_to_png_sequence(rgba, dir.str().c_str(), res3d, flip_y_and_z_axes);
}
}
ImGui::SameLine();
ImGui::Checkbox("Swap Y&Z", &flip_y_and_z_axes);
static char obj_filename_buf[128] = "";
ImGui::SliderInt("Res:", &m_mesh.res, 16, 2048, "%d", ImGuiSliderFlags_Logarithmic);
ImGui::SameLine();
ImGui::Text("%dx%dx%d", res3d.x(), res3d.y(), res3d.z());
if (obj_filename_buf[0] == '\0') {
snprintf(obj_filename_buf, sizeof(obj_filename_buf), "%s", get_filename_in_data_path_with_suffix(m_data_path, m_network_config_path, ".obj").c_str());
}
float thresh_range = (m_testbed_mode == ETestbedMode::Sdf) ? 0.5f : 10.f;
ImGui::SliderFloat("MC density threshold",&m_mesh.thresh, -thresh_range, thresh_range);
ImGui::Combo("Mesh render mode", (int*)&m_mesh_render_mode, "Off\0Vertex Colors\0Vertex Normals\0Face IDs\0");
ImGui::Checkbox("Unwrap mesh", &m_mesh.unwrap);
if (uint32_t tricount = m_mesh.indices.size()/3) {
ImGui::InputText("##OBJFile", obj_filename_buf, sizeof(obj_filename_buf));
if (ImGui::Button("Save it!")) {
save_mesh(m_mesh.verts, m_mesh.vert_normals, m_mesh.vert_colors, m_mesh.indices, obj_filename_buf, m_mesh.unwrap, m_nerf.training.dataset.scale, m_nerf.training.dataset.offset);
}
ImGui::SameLine();
ImGui::Text("Mesh has %d triangles\n", tricount);
ImGui::Checkbox("Optimize mesh", &m_mesh.optimize_mesh);
ImGui::SliderFloat("Laplacian smoothing", &m_mesh.smooth_amount, 0.f, 2048.f);
ImGui::SliderFloat("Density push", &m_mesh.density_amount, 0.f, 128.f);
ImGui::SliderFloat("Inflate", &m_mesh.inflate_amount, 0.f, 128.f);
}
}
}
if (m_testbed_mode == ETestbedMode::Sdf) {
if (ImGui::CollapsingHeader("BRDF parameters")) {
accum_reset |= ImGui::ColorEdit3("Base color", (float*)&m_sdf.brdf.basecolor );
accum_reset |= ImGui::SliderFloat("Roughness", &m_sdf.brdf.roughness, 0.f, 1.f);
accum_reset |= ImGui::SliderFloat("Specular", &m_sdf.brdf.specular, 0.f, 1.f);
accum_reset |= ImGui::SliderFloat("Metallic", &m_sdf.brdf.metallic, 0.f, 1.f);
ImGui::Separator();
accum_reset |= ImGui::SliderFloat("Subsurface", &m_sdf.brdf.subsurface, 0.f, 1.f);
accum_reset |= ImGui::SliderFloat("Sheen", &m_sdf.brdf.sheen, 0.f, 1.f);
accum_reset |= ImGui::SliderFloat("Clearcoat", &m_sdf.brdf.clearcoat, 0.f, 1.f);
accum_reset |= ImGui::SliderFloat("Clearcoat gloss", &m_sdf.brdf.clearcoat_gloss, 0.f, 1.f);
}
m_sdf.brdf.ambientcolor = (m_background_color * m_background_color).head<3>();
}
if (ImGui::CollapsingHeader("Histograms of trainable encoding parameters")) {
ImGui::Checkbox("Gather histograms", &m_gather_histograms);
static float minlevel = 0.f;
static float maxlevel = 1.f;
if (ImGui::SliderFloat("Max level", &maxlevel, 0.f, 1.f))
set_max_level(maxlevel);
if (ImGui::SliderFloat("##Min level", &minlevel, 0.f, 1.f))
set_min_level(minlevel);
ImGui::SameLine();
ImGui::Text("%0.1f%% values snapped to 0", m_quant_percent);
float f[32];
for (int i = 0; i < m_num_levels; ++i) {
f[i] = m_level_stats[i].mean();
}
ImGui::PlotHistogram("Means", f, m_num_levels, 0, "means", FLT_MAX, FLT_MAX, ImVec2(0, 60.f));
for (int i = 0; i < m_num_levels; ++i) {
f[i] = m_level_stats[i].sigma();
}
ImGui::PlotHistogram("Sigma", f, m_num_levels, 0, "sigma", FLT_MAX, FLT_MAX, ImVec2(0, 60.f));
for (int i = 0; i < m_num_levels; ++i) {
f[i] = m_level_stats[i].fraczero() * 100.f;
}
ImGui::PlotHistogram("% zero", f, m_num_levels, 0, "% zero", FLT_MAX, FLT_MAX, ImVec2(0, 60.f));
ImGui::Separator();
ImGui::SliderInt("Show details for level", &m_histo_level, 0, m_num_levels - 1);
if (m_histo_level < m_num_levels) {
LevelStats& s = m_level_stats[m_histo_level];
static bool excludezero = false;
if (excludezero)
m_histo[128] = 0.f;
ImGui::PlotHistogram("Values histogram", m_histo, 257, 0, "", FLT_MAX, FLT_MAX, ImVec2(0, 120.f));
ImGui::SliderFloat("Histogram horizontal scale", &m_histo_scale, 0.01f, 2.f);
ImGui::Checkbox("Exclude 'zero' from histogram", &excludezero);
ImGui::Text("Range: %0.5f - %0.5f", s.min, s.max);
ImGui::Text("Mean: %0.5f Sigma: %0.5f", s.mean(), s.sigma());
ImGui::Text("Num Zero: %d (%0.1f%%)", s.numzero, s.fraczero() * 100.f);
}
}
if (accum_reset) {
reset_accumulation();
}
if (ImGui::Button("Go to python REPL")) {
m_want_repl = true;
}
ImGui::End();
}
void Testbed::visualize_nerf_cameras(const Matrix<float, 4, 4>& world2proj) {
ImDrawList* list = ImGui::GetForegroundDrawList();
for (int i=0; i < m_nerf.training.n_images_for_training; ++i) {
float aspect = float(m_nerf.training.dataset.image_resolution.x())/float(m_nerf.training.dataset.image_resolution.y());
visualize_nerf_camera(world2proj, m_nerf.training.dataset.xforms[i].start, aspect, 0x40ffff40);
visualize_nerf_camera(world2proj, m_nerf.training.dataset.xforms[i].end, aspect, 0x40ffff40);
visualize_nerf_camera(world2proj, m_nerf.training.transforms[i].start, aspect, 0x80ffffff);
add_debug_line(world2proj, list, m_nerf.training.dataset.xforms[i].start.col(3), m_nerf.training.transforms[i].start.col(3), 0xffff40ff); // 1% loss change offset
// Visualize near distance
add_debug_line(world2proj, list, m_nerf.training.transforms[i].start.col(3), m_nerf.training.transforms[i].start.col(3) + m_nerf.training.transforms[i].start.col(2) * m_nerf.training.near_distance, 0x20ffffff);
}
}
void Testbed::draw_visualizations(const Matrix<float, 3, 4>& camera_matrix) {
// Visualize 3D cameras for SDF or NeRF use cases
if (m_testbed_mode != ETestbedMode::Image) {
Matrix<float, 4, 4> world2view, view2world, view2proj, world2proj;
view2world.setIdentity();
view2world.block<3,4>(0,0) = camera_matrix;
auto focal = calc_focal_length(Vector2i::Ones(), m_fov_axis, m_zoom);
float zscale = 1.0f / focal[m_fov_axis];
float xyscale = (float)m_window_res[m_fov_axis];
Vector2f screen_center = render_screen_center();
view2proj <<
xyscale, 0, (float)m_window_res.x()*screen_center.x()*zscale, 0,
0, xyscale, (float)m_window_res.y()*screen_center.y()*zscale, 0,
0, 0, 1, 0,
0, 0, zscale, 0;
world2view = view2world.inverse();
world2proj = view2proj * world2view;
// Visualize NeRF training poses
if (m_testbed_mode == ETestbedMode::Nerf) {
if (m_nerf.visualize_cameras) {
visualize_nerf_cameras(world2proj);
}
}
if (m_visualize_unit_cube) {
visualize_unit_cube(world2proj);
}
float aspect = (float)m_window_res.x() / (float)m_window_res.y();
if (m_camera_path.imgui_viz(view2proj, world2proj, world2view, focal, aspect)) {
m_pip_render_surface->reset_accumulation();
}
}
}
void drop_callback(GLFWwindow* window, int count, const char** paths) {
Testbed* testbed = (Testbed*)glfwGetWindowUserPointer(window);
if (testbed) {
for (int i = 0; i < count; i++) {
testbed->handle_file(paths[i]);
}
}
}
void glfw_error_callback(int error, const char* description) {
tlog::error() << "GLFW error #" << error << ": " << description;
}
bool Testbed::keyboard_event() {
if (ImGui::GetIO().WantCaptureKeyboard) {
return false;
}
for (int idx = 0; idx < std::min((int)ERenderMode::NumRenderModes, 10); ++idx) {
char c[] = { "1234567890" };
if (ImGui::IsKeyPressed(c[idx])) {
m_render_mode = (ERenderMode)idx;
reset_accumulation();
}
}
bool shift = ImGui::GetIO().KeyMods & ImGuiKeyModFlags_Shift;
if (ImGui::IsKeyPressed('Z')) {
m_camera_path.m_gizmo_op = ImGuizmo::TRANSLATE;
}
if (ImGui::IsKeyPressed('X')) {
m_camera_path.m_gizmo_op = ImGuizmo::ROTATE;
}
if (ImGui::IsKeyPressed('E'))
set_exposure(m_exposure + (shift ? -0.5f : 0.5f));
if (ImGui::IsKeyPressed('R')) {
if (shift) {
reset_camera();
} else {
reload_network_from_file("");
}
}
if (ImGui::IsKeyPressed('O')) {
m_nerf.training.render_error_overlay=!m_nerf.training.render_error_overlay;
}
if (ImGui::IsKeyPressed('G')) {
m_render_ground_truth = !m_render_ground_truth;
reset_accumulation();
if (m_render_ground_truth) {
m_nerf.training.view=find_best_training_view(m_nerf.training.view);
}
}
if (ImGui::IsKeyPressed('.')) {
if (m_single_view) {
if (m_visualized_dimension == m_network->width(m_visualized_layer)-1 && m_visualized_layer < m_network->num_forward_activations()-1) {
set_visualized_layer(std::max(0, std::min((int)m_network->num_forward_activations()-1, m_visualized_layer+1)));
set_visualized_dim(0);
} else {
set_visualized_dim(std::max(-1, std::min((int)m_network->width(m_visualized_layer)-1, m_visualized_dimension+1)));
}
} else {
set_visualized_layer(std::max(0, std::min((int)m_network->num_forward_activations()-1, m_visualized_layer+1)));
}
}
if (ImGui::IsKeyPressed(',')) {
if (m_single_view) {
if (m_visualized_dimension == 0 && m_visualized_layer > 0) {
set_visualized_layer(std::max(0, std::min((int)m_network->num_forward_activations()-1, m_visualized_layer-1)));
set_visualized_dim(m_network->width(m_visualized_layer)-1);
} else {
set_visualized_dim(std::max(-1, std::min((int)m_network->width(m_visualized_layer)-1, m_visualized_dimension-1)));
}
} else {
set_visualized_layer(std::max(0, std::min((int)m_network->num_forward_activations()-1, m_visualized_layer-1)));
}
}