-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmicrodisplacement.cpp
1718 lines (1453 loc) · 58.9 KB
/
microdisplacement.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
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: Copyright (c) 2022-2023 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_access.hpp>
#undef GLFW_INCLUDE_VULKAN
#include <imgui/imgui_helper.h>
#include <nvh/cameracontrol.hpp>
#include <nvh/fileoperations.hpp>
#include <nvh/misc.hpp>
#include <nvvk/appwindowprofiler_vk.hpp>
#include "vk_nv_micromesh_prototypes.h"
#include "renderer_vk.hpp"
#include "scene_vk.hpp"
#include "common.h"
#include "common_barymap.h"
#include "common_micromesh_compressed.h"
bool g_enableMicromeshRTExtensions = true;
bool g_verbose = false;
uint32_t g_numThreads = 0;
static_assert(MAX_BASE_SUBDIV < MAX_BARYMAP_LEVELS, "MAX_BARYMAP_LEVELS must allow for MAX_BASE_SUBDIV");
namespace microdisp {
int const SAMPLE_SIZE_WIDTH(1024);
int const SAMPLE_SIZE_HEIGHT(1024);
void setupContextRequirements(nvvk::ContextCreateInfo& contextInfo)
{
static VkPhysicalDeviceMeshShaderFeaturesNV meshFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_NV};
static VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR execPropertiesFeatures = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR};
static VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV baryFeatures = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_NV};
static VkPhysicalDeviceShaderClockFeaturesKHR clockFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR};
static VkPhysicalDeviceAccelerationStructureFeaturesKHR accFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR};
static VkPhysicalDeviceRayQueryFeaturesKHR rayQueryFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR};
static VkPhysicalDeviceRayTracingPipelineFeaturesKHR rayPipelineFeatures = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR};
static VkPhysicalDeviceShaderFloat16Int8FeaturesKHR f16i8Features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR};
static VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT imageAtom64Features = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT};
static VkPhysicalDeviceShaderAtomicFloatFeaturesEXT floatFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT};
static VkPhysicalDeviceOpacityMicromapFeaturesEXT mmOpacityFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT};
static VkPhysicalDeviceDisplacementMicromapFeaturesNV mmDisplacementFeatures = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISPLACEMENT_MICROMAP_FEATURES_NV};
contextInfo.apiMajor = 1;
contextInfo.apiMinor = 3;
contextInfo.addInstanceExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
#if defined(_DEBUG) && 0
// enable debugPrintf
contextInfo.addDeviceExtension(VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME, false);
static VkValidationFeaturesEXT validationInfo = {VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT};
static VkValidationFeatureEnableEXT enabledFeatures[] = {VK_VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT};
validationInfo.enabledValidationFeatureCount = NV_ARRAY_SIZE(enabledFeatures);
validationInfo.pEnabledValidationFeatures = enabledFeatures;
contextInfo.instanceCreateInfoExt = &validationInfo;
#ifdef _WIN32
_putenv_s("DEBUG_PRINTF_TO_STDOUT", "1");
#else
putenv("DEBUG_PRINTF_TO_STDOUT=1");
#endif
#endif // _DEBUG
contextInfo.addDeviceExtension(VK_KHR_SHADER_CLOCK_EXTENSION_NAME, false, &clockFeatures);
contextInfo.addDeviceExtension(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME, false);
contextInfo.addDeviceExtension(VK_NV_MESH_SHADER_EXTENSION_NAME, false, &meshFeatures);
contextInfo.addDeviceExtension(VK_NV_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, false, &baryFeatures);
contextInfo.addDeviceExtension(VK_NV_FILL_RECTANGLE_EXTENSION_NAME, false);
contextInfo.addDeviceExtension(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME, false);
contextInfo.addDeviceExtension(VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME, false);
contextInfo.addDeviceExtension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME, false);
contextInfo.addDeviceExtension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME, false, &accFeatures);
contextInfo.addDeviceExtension(VK_KHR_RAY_QUERY_EXTENSION_NAME, false, &rayQueryFeatures);
contextInfo.addDeviceExtension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME, false, &rayPipelineFeatures);
contextInfo.addDeviceExtension(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, false, &execPropertiesFeatures);
contextInfo.addDeviceExtension(VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME, false);
contextInfo.addDeviceExtension(VK_EXT_SHADER_IMAGE_ATOMIC_INT64_EXTENSION_NAME, false, &imageAtom64Features);
contextInfo.addDeviceExtension(VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME, false);
contextInfo.addDeviceExtension(VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME, false, &floatFeatures);
contextInfo.addDeviceExtension(VK_EXT_OPACITY_MICROMAP_EXTENSION_NAME, true, &mmOpacityFeatures);
contextInfo.addDeviceExtension(VK_NV_DISPLACEMENT_MICROMAP_EXTENSION_NAME, true, &mmDisplacementFeatures);
}
class Frustum
{
public:
enum
{
PLANE_NEAR,
PLANE_FAR,
PLANE_LEFT,
PLANE_RIGHT,
PLANE_TOP,
PLANE_BOTTOM,
NUM_PLANES
};
static inline void init(glm::vec4 planes[NUM_PLANES], const glm::mat4& viewProj)
{
const float* clip = glm::value_ptr(viewProj);
planes[PLANE_RIGHT][0] = clip[3] - clip[0];
planes[PLANE_RIGHT][1] = clip[7] - clip[4];
planes[PLANE_RIGHT][2] = clip[11] - clip[8];
planes[PLANE_RIGHT][3] = clip[15] - clip[12];
planes[PLANE_LEFT][0] = clip[3] + clip[0];
planes[PLANE_LEFT][1] = clip[7] + clip[4];
planes[PLANE_LEFT][2] = clip[11] + clip[8];
planes[PLANE_LEFT][3] = clip[15] + clip[12];
planes[PLANE_BOTTOM][0] = clip[3] + clip[1];
planes[PLANE_BOTTOM][1] = clip[7] + clip[5];
planes[PLANE_BOTTOM][2] = clip[11] + clip[9];
planes[PLANE_BOTTOM][3] = clip[15] + clip[13];
planes[PLANE_TOP][0] = clip[3] - clip[1];
planes[PLANE_TOP][1] = clip[7] - clip[5];
planes[PLANE_TOP][2] = clip[11] - clip[9];
planes[PLANE_TOP][3] = clip[15] - clip[13];
planes[PLANE_FAR][0] = clip[3] - clip[2];
planes[PLANE_FAR][1] = clip[7] - clip[6];
planes[PLANE_FAR][2] = clip[11] - clip[10];
planes[PLANE_FAR][3] = clip[15] - clip[14];
planes[PLANE_NEAR][0] = clip[3] + clip[2];
planes[PLANE_NEAR][1] = clip[7] + clip[6];
planes[PLANE_NEAR][2] = clip[11] + clip[10];
planes[PLANE_NEAR][3] = clip[15] + clip[14];
for(int i = 0; i < NUM_PLANES; i++)
{
float length = sqrtf(planes[i][0] * planes[i][0] + planes[i][1] * planes[i][1] + planes[i][2] * planes[i][2]);
float magnitude = 1.0f / length;
for(int n = 0; n < 4; n++)
{
planes[i][n] *= magnitude;
}
}
}
};
// used for loading viewpoint files and material filter files
class SimpleParameterFile
{
public:
// loads a text file and stores the tokens in a vector per line and
// a vector of lines
// everything after a # gets ignored
SimpleParameterFile(std::string fileName)
{
std::ifstream f;
f.open(fileName);
if(!f)
return;
std::string lineOfFile;
while(getline(f, lineOfFile))
{
if(lineOfFile.length() == 0)
continue;
ParameterLine pLine;
std::stringstream ss(lineOfFile);
std::string token;
while(getline(ss, token, ' '))
{
if(token.length() == 0)
continue;
if(token[0] == '#')
{
// ignore rest of this line
break;
}
Parameter p;
p.strValue = token;
pLine.parameter.push_back(p);
}
if(pLine.parameter.size() > 0)
{
line.push_back(pLine);
}
}
f.close();
}
struct Parameter
{
// the string of the token
std::string strValue;
// returns true on success of storing the token as an int to toFill
bool toInt(int& toFill)
{
bool success = true;
try
{
toFill = std::stoi(strValue);
}
catch(...)
{
success = false;
}
return success;
}
// returns true on success of storing the token as a float to toFill
bool toFloat(float& toFill)
{
bool success = true;
try
{
toFill = std::stof(strValue);
}
catch(...)
{
success = false;
}
return success;
}
};
struct ParameterLine
{
std::vector<Parameter> parameter;
};
std::vector<ParameterLine> line;
};
class Sample : public nvvk::AppWindowProfilerVK
{
enum LodType
{
LOD_PRECOMPUTED_SPHERE,
LOD_DYNAMIC_TRIANGLE,
};
enum NormalType
{
NORMAL_FACET,
NORMAL_VERTEX,
NORMAL_TEXTURE,
NORMAL_MICROVERTEX,
};
enum GuiEnums
{
GUI_VIEWPOINT,
GUI_RENDERER,
GUI_SUPERSAMPLE,
GUI_SURFACEVIS,
GUI_LODTYPE,
GUI_DECODERTYPE,
GUI_LAYOUT,
GUI_FORMAT,
GUI_MODEL,
GUI_MODEL_OVERLAY,
GUI_NORMALS,
};
public:
struct Tweak
{
// shader / shading related
bool useStats = false;
bool showReflectionLine = false;
bool showReflectionBand = false;
bool hbaoFullRes = false;
float hbaoRadius = 0.05f;
bool colorize = false;
bool fp16displacementMath = false;
NormalType normalType = NORMAL_FACET;
float lodAreaScale = 1.0f;
LodType lodType = LOD_PRECOMPUTED_SPHERE;
bool useLod = false;
bool usePrimitiveCulling = false;
float displacementScale = 1.0f;
int surfaceVisualization = SURFACEVIS_SHADING;
bool useOcclusionCulling = false;
RendererVK::DecoderType decoderType = RendererVK::DECODER_BASETRI_MIP;
// render / scene setup
int renderer = 0;
int viewPoint = 0;
int supersample = 2;
float fov = 45.0f;
uint32_t objectFrom = 0;
uint32_t objectNum = ~0u;
uint32_t gridCopies = 1;
uint32_t gridAxis = 5;
float gridSpacing = 1.05f;
float renderScale = 1.0f;
float renderBias = 0.0f;
float rotateModelSpeed = 0.0f;
vec2 rotateModelDistance = vec2(0.4f, 0.1f);
uint32_t maxVisibleBits = 20;
static constexpr float minFov = 1.0f, maxFov = 130.0f;
};
struct ViewPoint
{
std::string name;
glm::mat4 mat;
float sceneScale;
float fov;
};
bool m_useUI = true;
#ifdef _DEBUG
bool m_advancedUI = true;
#else
bool m_advancedUI = false;
#endif
ImGuiH::Registry m_ui;
double m_uiTime = 0;
Tweak m_tweak;
Tweak m_lastTweak;
bool m_lastVsync;
size_t m_lastFbo = 0;
SceneVK m_scene;
std::string m_rendererName;
std::vector<unsigned int> m_renderersSorted;
uint32_t m_rendererType;
std::string m_rendererShaderPrepend;
std::string m_rendererLastShaderPrepend;
RendererVK* NV_RESTRICT m_renderer = nullptr;
ResourcesVK m_resources;
RenderList m_renderList;
FrameConfig m_frameConfig;
SceneData m_sceneUbo;
SceneData m_sceneUboLast;
std::string m_viewpointFilename;
std::vector<ViewPoint> m_viewPoints;
std::string m_modelFilenameLo;
glm::vec3 m_modelUpVector = glm::vec3(0, 1, 0);
int m_frames = 0;
double m_lastFrameTime = 0;
double m_statsCpuTime = 0;
double m_statsGpuTime = 0;
double m_statsRayTime = 0;
double m_statsRstTime = 0;
double m_statsRdrTime = 0;
double m_statsTskTime = 0;
double m_statsDrwTime = 0;
ShaderStats m_stats;
nvh::CameraControl m_control;
bool m_cameraParseSuccess = true;
bool setRendererFromName(const std::string& name);
bool initScene(const char* filenameLo);
bool initFramebuffers(int width, int height);
void initRenderer(int type);
void updateGrid(bool gpu = true)
{
m_scene.updateGrid(m_resources, m_tweak.gridCopies, m_tweak.gridAxis, m_tweak.gridSpacing, gpu);
}
void updateLow() { m_scene.updateLow(m_resources); }
bool initCore();
void postInitScene();
void deinitRenderer();
void saveViewpoint();
void loadViewpoints();
void setViewpoint();
void setupConfigParameters();
std::string getShaderPrepend();
template <typename T>
bool tweakChanged(const T& val) const
{
size_t offset = size_t(&val) - size_t(&m_tweak);
return memcmp(&val, reinterpret_cast<const uint8_t*>(&m_lastTweak) + offset, sizeof(T)) != 0;
}
template <typename T>
bool tweakChangedNonZero(const T& val) const
{
size_t offset = size_t(&val) - size_t(&m_tweak);
const T* lastVal = reinterpret_cast<const T*>(reinterpret_cast<const uint8_t*>(&m_lastTweak) + offset);
bool state = (val != 0) != (*lastVal != 0);
return state;
}
template <typename T>
bool tweakChangedPositive(const T& val) const
{
size_t offset = size_t(&val) - size_t(&m_tweak);
const T* lastVal = reinterpret_cast<const T*>(reinterpret_cast<const uint8_t*>(&m_lastTweak) + offset);
bool state = (val >= 0) != (*lastVal >= 0);
return state;
}
Sample()
: AppWindowProfilerVK(false)
{
setupConfigParameters();
setupContextRequirements(m_contextInfo);
// we need to ignore errors regarding storageInputOutput16
// due to an ovesight in the spec task shaders output and mesh shader input would have to adhere to this feature,
// but they are treated different compared to vertex shader input/outputs.
m_context.ignoreDebugMessage(0x6e224e9);
m_context.ignoreDebugMessage(0x715035dd);
#if defined(NDEBUG)
setVsync(false);
#endif
}
public:
void processUI(int width, int height, double time);
bool validateConfig() override;
bool begin() override;
void think(double time) override;
void resize(int width, int height) override;
void postBenchmarkAdvance() override;
void end() override;
// return true to prevent m_window updates
bool mouse_pos(int x, int y) override
{
if(!m_useUI)
return false;
return ImGuiH::mouse_pos(x, y);
}
bool mouse_button(int button, int action) override
{
if(!m_useUI)
return false;
return ImGuiH::mouse_button(button, action);
}
bool mouse_wheel(int wheel) override
{
if(!m_useUI)
return false;
return ImGuiH::mouse_wheel(wheel);
}
bool key_char(int key) override
{
if(!m_useUI)
return false;
return ImGuiH::key_char(key);
}
bool key_button(int button, int action, int mods) override
{
if(!m_useUI)
return false;
return ImGuiH::key_button(button, action, mods);
}
};
std::string Sample::getShaderPrepend()
{
std::string prepend;
prepend += nvh::stringFormat("#define USE_PRIMITIVE_CULLING %d\n", m_tweak.usePrimitiveCulling ? 1 : 0);
prepend += nvh::stringFormat("#define USE_OCCLUSION_CULLING %d\n", m_tweak.useOcclusionCulling ? 1 : 0);
prepend += nvh::stringFormat("#define USE_TRI_LOD %d\n", m_tweak.lodType == LOD_DYNAMIC_TRIANGLE ? 1 : 0);
prepend += nvh::stringFormat("#define USE_STATS %d\n", m_tweak.useStats ? 1 : 0);
prepend += nvh::stringFormat("#define USE_FACET_SHADING %d\n", m_tweak.normalType == NORMAL_FACET ? 1 : 0);
prepend += nvh::stringFormat("#define USE_FP16_DISPLACEMENT_MATH %d\n", m_tweak.fp16displacementMath ? 1 : 0);
prepend += nvh::stringFormat("#define SURFACEVIS %d\n", m_tweak.surfaceVisualization);
LOGI("new shader setup\n");
#ifdef _DEBUG
printf(prepend.c_str());
#endif
return prepend;
}
bool Sample::initScene(const char* filenameLo)
{
m_scene = SceneVK();
if(!filenameLo)
{
// Nothing to load
return true;
}
bool status = m_scene.load(filenameLo);
if(status)
{
if(m_scene.meshSetLo)
{
LOGI("lo-res mesh: %s\n", filenameLo);
LOGI("vertices: %9d\n", uint32_t(m_scene.meshSetLo->attributes.positions.size()));
LOGI("primitives: %9d\n", uint32_t(m_scene.meshSetLo->indices.size() / 3));
LOGI("materials: %9d\n", int32_t(m_scene.meshSetLo->materials.size()));
LOGI("instances: %9d\n", int32_t(m_scene.meshSetLo->meshInstances.size()));
LOGI("bboxdim: %f, %f, %f\n", m_scene.meshSetLo->bbox.diagonal().x, m_scene.meshSetLo->bbox.diagonal().y,
m_scene.meshSetLo->bbox.diagonal().z);
}
LOGI("\n");
}
else
{
LOGE("\ncould not load model (%s)\n", filenameLo);
}
return status;
}
bool Sample::initFramebuffers(int width, int height)
{
return m_resources.initFramebuffer(width, height, m_tweak.supersample, getVsync());
}
void Sample::postInitScene()
{
m_scene.init(m_resources);
updateGrid(false);
updateLow();
m_sceneUbo = {};
m_frameConfig.sceneUbo = &m_sceneUbo;
m_frameConfig.sceneUboLast = &m_sceneUboLast;
m_control.m_sceneUp = m_modelUpVector;
// Handle the case where we have no hi-res mesh properly
MeshBBox bbox = m_scene.meshSetLo->bbox;
m_control.m_sceneOrbit = glm::vec3((bbox.maxs + bbox.mins)) * 0.5f;
m_control.m_sceneDimension = glm::length((bbox.maxs - bbox.mins));
m_control.m_viewMatrix = glm::lookAt(m_control.m_sceneOrbit - (-glm::vec3(1, 1, 1) * m_control.m_sceneDimension * 0.5f),
m_control.m_sceneOrbit, m_modelUpVector);
m_sceneUbo.wLightPos = glm::vec4((bbox.maxs + bbox.mins) * 0.5f + m_control.m_sceneDimension, 1.0);
loadViewpoints();
if(m_useUI)
{
m_ui.enumReset(GUI_VIEWPOINT);
for(auto it = m_viewPoints.begin(); it != m_viewPoints.end(); it++)
{
m_ui.enumAdd(GUI_VIEWPOINT, int(it - m_viewPoints.begin()), it->name.c_str());
}
if(m_viewPoints.empty())
{
m_ui.enumAdd(GUI_VIEWPOINT, 0, "default");
}
m_ui.enumReset(GUI_NORMALS);
m_ui.enumAdd(GUI_NORMALS, NORMAL_FACET, "facet");
m_ui.enumAdd(GUI_NORMALS, NORMAL_VERTEX, "base-vertex");
if(m_scene.meshSetLo->textures.size() > 1)
{
m_ui.enumAdd(GUI_NORMALS, NORMAL_TEXTURE, "texture");
}
if(m_scene.barySet.displacements.size() && m_scene.barySet.shadings.size() == m_scene.barySet.displacements.size())
{
m_ui.enumAdd(GUI_NORMALS, NORMAL_MICROVERTEX, "micro-vertex");
}
m_ui.enumReset(GUI_DECODERTYPE);
if(m_scene.barySet.supportsCompressedMips())
{
m_ui.enumAdd(GUI_DECODERTYPE, RendererVK::DECODER_BASETRI_MIP, "base w. mip");
}
m_ui.enumAdd(GUI_DECODERTYPE, RendererVK::DECODER_MICROTRI, "micro");
if(m_context.hasDeviceExtension(VK_NV_DISPLACEMENT_MICROMAP_EXTENSION_NAME))
{
m_ui.enumAdd(GUI_DECODERTYPE, RendererVK::DECODER_MICROTRI_INTRINSIC, "micro (intrinsic)");
}
{
const RendererVK::Registry& registry = RendererVK::getRegistry();
m_ui.enumReset(GUI_RENDERER);
for(size_t i = 0; i < m_renderersSorted.size(); i++)
{
auto rendererType = registry[m_renderersSorted[i]];
if(rendererType->supportsCompressed() == m_scene.hasCompressedDisplacement)
{
m_ui.enumAdd(GUI_RENDERER, int(i), registry[m_renderersSorted[i]]->name());
}
}
}
}
if(!m_scene.barySet.supportsCompressedMips() && m_tweak.decoderType == RendererVK::DECODER_BASETRI_MIP)
{
// if not supported but set, then revert to MICROTRI decoder, preferably the intrinsic version
m_tweak.decoderType = m_context.hasDeviceExtension(VK_NV_DISPLACEMENT_MICROMAP_EXTENSION_NAME) ?
RendererVK::DECODER_MICROTRI_INTRINSIC :
RendererVK::DECODER_MICROTRI;
}
if(!m_context.hasDeviceExtension(VK_NV_DISPLACEMENT_MICROMAP_EXTENSION_NAME) && m_tweak.decoderType == RendererVK::DECODER_MICROTRI_INTRINSIC)
{
// if intrinsics not supported use fallback
m_tweak.decoderType = RendererVK::DECODER_MICROTRI;
}
setViewpoint();
if(m_scene.hasCompressedDisplacement)
{
setRendererFromName("compressed ms");
}
else if(m_scene.hasUncompressedDisplacement)
{
setRendererFromName("uncompressed ms");
}
}
void Sample::deinitRenderer()
{
if(m_renderer)
{
m_resources.synchronize("sync deinitRenderer");
m_renderer->deinit();
delete m_renderer;
m_renderer = nullptr;
}
}
void Sample::initRenderer(int typesort)
{
if(!(m_scene.meshSetLo))
return;
int type = m_renderersSorted[typesort % m_renderersSorted.size()];
m_rendererType = type;
deinitRenderer();
{
RenderList::Config config;
m_renderList.setup(&m_scene, &m_stats, config);
}
{
RendererVK::Config config;
config.useLod = m_tweak.useLod;
config.numThreads = g_numThreads;
config.useOcclusionHiz = m_tweak.useOcclusionCulling;
config.decoderType = m_tweak.decoderType;
config.maxVisibleBits = m_tweak.maxVisibleBits;
config.useNormalMap = m_tweak.normalType == NORMAL_TEXTURE;
config.useMicroVertexNormals = m_tweak.normalType == NORMAL_MICROVERTEX;
LOGI("renderer: %s\n", RendererVK::getRegistry()[type]->name());
m_renderer = RendererVK::getRegistry()[type]->create(m_resources);
if(!m_renderer->init(m_renderList, config))
{
LOGE("renderer init failed\n");
exit(-1);
}
}
}
void Sample::loadViewpoints()
{
m_viewPoints.clear();
if(m_viewpointFilename.empty())
return;
SimpleParameterFile vpParameters(m_viewpointFilename);
for(SimpleParameterFile::ParameterLine line : vpParameters.line)
{
// name + 16 for the matrix + optional scale + optional fov
if(line.parameter.size() >= 17 && line.parameter.size() <= 19)
{
bool lineIsOK = true;
ViewPoint vp;
vp.name = line.parameter[0].strValue;
// read matrix
float* mat_array = glm::value_ptr(vp.mat);
for(auto i = 0; i < 16; ++i)
{
bool valueIsFloat = line.parameter[1 + i].toFloat(mat_array[i]);
lineIsOK = lineIsOK & valueIsFloat;
}
// optionally scene scale
if(line.parameter.size() == 18)
{
lineIsOK = lineIsOK & line.parameter[17].toFloat(vp.sceneScale);
}
else
{
vp.sceneScale = 1.0f;
}
// optionally real scale
if(line.parameter.size() == 19)
{
lineIsOK = lineIsOK & line.parameter[18].toFloat(vp.fov);
}
else
{
vp.fov = 0;
}
// only save if all parameters were read correctly
if(lineIsOK)
{
m_viewPoints.push_back(vp);
}
}
}
}
void Sample::setViewpoint()
{
if(m_viewPoints.empty())
{
m_tweak.viewPoint = 0;
return;
}
m_tweak.viewPoint = std::min(std::max(m_tweak.viewPoint, 0), int(m_viewPoints.size() - 1));
m_control.m_viewMatrix = m_viewPoints[m_tweak.viewPoint].mat;
if(m_viewPoints[m_tweak.viewPoint].fov)
{
m_tweak.fov = m_viewPoints[m_tweak.viewPoint].fov;
}
}
bool Sample::initCore()
{
m_context.ignoreDebugMessage(0xa7bb8db6); // not a bug: complains about StorageInputOutput16
//m_context.ignoreDebugMessage(0x6bbb14); // not a bug: complains about InconsistentSpirv during optimization
//m_context.ignoreDebugMessage(0x23e43bb7); // not a bug: complains about InputNotProduced for pervertexNV variables - see https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/3194
LOGI("num threads: %u\n", g_numThreads);
std::vector<std::string> shaderSearchPaths;
std::string path = NVPSystem::exePath();
shaderSearchPaths.push_back(NVPSystem::exePath());
shaderSearchPaths.push_back(std::string("GLSL_" PROJECT_NAME));
shaderSearchPaths.push_back(NVPSystem::exePath() + std::string("GLSL_" PROJECT_NAME));
shaderSearchPaths.push_back(NVPSystem::exePath() + std::string(PROJECT_RELDIRECTORY));
m_resources.m_hbaoFullRes = m_tweak.hbaoFullRes;
bool validated = initScene(m_modelFilenameLo.empty() ? nullptr : m_modelFilenameLo.c_str());
validated = validated && m_resources.init(&m_context, &m_swapChain, shaderSearchPaths);
validated = validated
&& m_resources.initFramebuffer(m_windowState.m_swapSize[0], m_windowState.m_swapSize[1],
m_tweak.supersample, getVsync());
m_resources.m_shaderManager.m_prepend = getShaderPrepend();
if(!validated)
{
return false;
}
if(m_scene.meshSetLo)
{
postInitScene();
// postInitScene may change some flags
m_resources.m_shaderManager.m_prepend = getShaderPrepend();
}
return true;
}
bool Sample::begin()
{
m_profilerPrint = false;
m_timeInTitle = true;
m_renderer = nullptr;
if(m_context.hasDeviceExtension(VK_EXT_OPACITY_MICROMAP_EXTENSION_NAME))
{
load_VK_EXT_opacity_micromap_prototypes(m_context.m_device, vkGetDeviceProcAddr);
}
// ImGUI must come first
ImGuiH::Init(m_windowState.m_winSize[0], m_windowState.m_winSize[1], this, ImGuiH::FONT_MONOSPACED_SCALED);
ResourcesVK::initImGui(m_context);
const RendererVK::Registry& registry = RendererVK::getRegistry();
{
// setup renderer list
for(size_t i = 0; i < registry.size(); i++)
{
if(registry[i]->isAvailable(&m_context))
{
uint sortkey = uint(i);
sortkey |= registry[i]->priority() << 16;
m_renderersSorted.push_back(sortkey);
}
}
if(m_renderersSorted.empty())
{
LOGE("No renderers available\n");
return false;
}
std::sort(m_renderersSorted.begin(), m_renderersSorted.end());
for(size_t i = 0; i < m_renderersSorted.size(); i++)
{
m_renderersSorted[i] &= 0xFFFF;
LOGI("renderer %d: %s\n", uint32_t(i), registry[m_renderersSorted[i]]->name());
}
}
bool validated = initCore();
if(!validated)
{
return false;
}
if(!setRendererFromName(m_rendererName))
{
return false;
}
// setup UI
if(m_useUI)
{
auto& imgui_io = ImGui::GetIO();
m_ui.enumAdd(GUI_MODEL, MODEL_LO, "Base");
m_ui.enumAdd(GUI_MODEL, MODEL_DISPLACED, "Displaced");
m_ui.enumAdd(GUI_MODEL, NUM_MODELTYPES, "None");
m_ui.enumAdd(GUI_MODEL_OVERLAY, MODEL_LO, "Base");
m_ui.enumAdd(GUI_MODEL_OVERLAY, MODEL_DISPLACED, "Displaced");
m_ui.enumAdd(GUI_MODEL_OVERLAY, MODEL_SHELL, "Shell");
m_ui.enumAdd(GUI_MODEL_OVERLAY, NUM_MODELTYPES, "None");
m_ui.enumAdd(GUI_LAYOUT, (int32_t)bary::ValueLayout::eTriangleUmajor, "U-MAJOR");
m_ui.enumAdd(GUI_LAYOUT, (int32_t)bary::ValueLayout::eTriangleBirdCurve, "BIRD_CURVE");
m_ui.enumAdd(GUI_FORMAT, (int32_t)(bary::Format::eR8_unorm), "8_UNORM");
m_ui.enumAdd(GUI_FORMAT, (int32_t)(bary::Format::eR16_unorm), "16_UNORM");
m_ui.enumAdd(GUI_FORMAT, (int32_t)(bary::Format::eR11_unorm_pack16), "11_UNORM_PACK16");
m_ui.enumAdd(GUI_FORMAT, (int32_t)(bary::Format::eR32_sfloat), "32_SFLOAT");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_SHADING, "Default Shading");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_ANISOTROPY, "Anisotropy");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_BASETRI, "Base Triangle index");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_MICROTRI, "Global microtriangle index (raster)");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_LOCALTRI, "Local microtriangle index (raster)");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_FORMAT, "Encoding Format (raster compressed)");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_VALUERANGE, "Value Range (raster)");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_BASESUBDIV, "Base Subdiv (raster)");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_LODBIAS, "Dynamic LoD Bias (raster)");
m_ui.enumAdd(GUI_SURFACEVIS, SURFACEVIS_LODSUBDIV, "Dynamic LoD Base Subdiv (raster)");
m_ui.enumAdd(GUI_LODTYPE, LOD_PRECOMPUTED_SPHERE, "precomp. sphere");
m_ui.enumAdd(GUI_LODTYPE, LOD_DYNAMIC_TRIANGLE, "dynamic triangle");
}
m_resources.updatedShaders();
initRenderer(m_tweak.renderer);
m_lastTweak = m_tweak;
m_lastVsync = getVsync();
m_lastFbo = m_resources.m_fboChangeID;
return validated;
}
void Sample::end()
{
#if !_DEBUG
exit(0);
#endif
if(!m_resources.m_device)
return;
deinitRenderer();
m_scene.deinit(m_resources);
m_resources.deinit();
ResourcesVK::deinitImGui(m_context);
}
void Sample::processUI(int width, int height, double time)
{
// Update imgui configuration
auto& imgui_io = ImGui::GetIO();
imgui_io.DeltaTime = static_cast<float>(time - m_uiTime);
imgui_io.DisplaySize = ImVec2(static_cast<float>(width), static_cast<float>(height));
m_uiTime = time;
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(5, 5), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(ImGuiH::dpiScaled(310), SAMPLE_SIZE_HEIGHT - 16), ImGuiCond_FirstUseEver);
ImVec4 advancedColor = {70.0f / 255.0f, 58.0f / 255.0f, 89.0f / 255.0f, 0.8f};
if(ImGui::Begin("NVIDIA " PROJECT_NAME))
{
ImGui::PushItemWidth(ImGuiH::dpiScaled(130));
ImGui::Checkbox("enable advanced UI options", &m_advancedUI);
bool earlyOut = !(m_scene.meshSetLo);
if(ImGui::CollapsingHeader("LOAD", ImGuiTreeNodeFlags_DefaultOpen))
{
bool doLoadFiles = false;
if(ImGui::Button("DISPLACED MODEL"))
{
std::string fileNameLo = NVPWindow::openFileDialog("Pick lo-res model with displacement (mandatory)",
"Supported (glTF 2.0)|*.gltf;*.glb;*.csf;"
"|All|*.*");
if(!fileNameLo.empty())
{
m_modelFilenameLo = fileNameLo;
m_viewpointFilename = std::string();
doLoadFiles = true;
}
}
ImGui::SameLine();
if(ImGui::Button("CFG FILE"))
{
std::string newFileName = openFileDialog("Config File", "cfg|*.cfg");
if(!newFileName.empty())
{
m_modelFilenameLo = std::string();
m_viewpointFilename = std::string();
parseConfigFile(newFileName.c_str());
if(!m_modelFilenameLo.empty())
{
doLoadFiles = true;
}
}
}