-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathVulkanLaunchpad.cpp
2145 lines (1882 loc) · 96.1 KB
/
VulkanLaunchpad.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) 2023 TU Wien, Institute of Visual Computing & Human-Centered Technology.
* Created by Johannes Unterguggenberger ([email protected], https://johannesugb.github.io).
*/
#include "VulkanLaunchpad.h"
#include <vulkan/vulkan.hpp>
#ifdef VKL_HAS_VMA
#define VMA_IMPLEMENTATION
#include <vma/vk_mem_alloc.h>
#endif
#include <unordered_map>
#include <map>
#include <deque>
#include <variant>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tinyobjloader/tiny_obj_loader.h>
//#define USE_SHADERC
#define USE_GLSLANG
// Always use GLI, since the manual implementation of DDS loading does not currently work.
#define USE_GLI
#ifdef USE_SHADERC
#include <shaderc/shaderc.hpp>
#endif
#ifdef USE_GLSLANG
#include <glslang/Include/glslang_c_interface.h>
#endif
#include <fstream>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#ifdef USE_GLI
#include <gli/load.hpp> // load DDS, KTX or KMG textures from files or memory.
#include <gli/core/flip.hpp>
#include <gli/convert.hpp> // convert a texture from a format to another
#include <gli/copy.hpp> // copy a texture or subset of a texture to another texture
#include <gli/duplicate.hpp> // duplicate the data of a texture, allocating a new texture storage
#include <gli/format.hpp> // list of the supported formats
#include <gli/generate_mipmaps.hpp> // generating the mipmaps of a texture
#include <gli/make_texture.hpp> // helper functions to create generic texture
#include <gli/texture2d.hpp>
#endif
vk::Instance mInstance = {};
vk::SurfaceKHR mSurface = {};
vk::PhysicalDevice mPhysicalDevice = {};
vk::Device mDevice = {};
vk::DispatchLoaderStatic mDispatchLoader = {};
vk::Queue mQueue = {};
VklSwapchainConfig mSwapchainConfig = {};
std::vector<std::vector<vk::ClearValue>> mClearValues;
#ifdef VKL_HAS_VMA
VmaAllocator mVmaAllocator = {};
bool vklHasVmaAllocator() { return VmaAllocator{} != mVmaAllocator; }
#endif
bool mFrameworkInitialized = false;
vk::DispatchLoaderDynamic mDynamicDispatch;
vk::ResultValueType<VULKAN_HPP_NAMESPACE::DebugUtilsMessengerEXT>::type mDebugUtilsMessenger;
std::vector<std::vector<vk::ImageView>> mSwapchainImageViews; //< Will be the length of #swapchain images
vk::PipelineStageFlags mSrcStages0;
vk::AccessFlags mSrcAccess0;
vk::PipelineStageFlags mDstStages0;
vk::AccessFlags mDstAccess0;
vk::UniqueRenderPass mRenderpass;
std::vector<vk::UniqueFramebuffer> mFramebuffers; //< Will be the length of #swapchain images
bool mHasDepthAttachments = false;
constexpr int CONCURRENT_FRAMES = 1;
std::array<vk::UniqueSemaphore, CONCURRENT_FRAMES> mImageAvailableSemaphores;
std::array<vk::UniqueSemaphore, CONCURRENT_FRAMES> mRenderFinishedSemaphores;
std::array<vk::UniqueFence, CONCURRENT_FRAMES> mSyncHostWithDeviceFence;
std::vector<int> mImagesInFlightFenceIndices;
int64_t mFrameId;
int mFrameInFlightIndex;
uint32_t mCurrentSwapChainImageIndex;
vk::UniqueCommandPool mCommandPool;
#ifdef VKL_HAS_VMA
std::unordered_map<VkBuffer, std::variant<vk::UniqueDeviceMemory, VmaAllocation>> mHostCoherentBuffersWithBackingMemory;
std::unordered_map<VkBuffer, std::variant<vk::UniqueDeviceMemory, VmaAllocation>> mDeviceLocalBuffersWithBackingMemory;
std::unordered_map<VkImage, std::variant<vk::UniqueDeviceMemory, VmaAllocation>> mImagesWithBackingMemory;
#else
std::unordered_map<VkBuffer, vk::UniqueDeviceMemory> mHostCoherentBuffersWithBackingMemory;
std::unordered_map<VkBuffer, vk::UniqueDeviceMemory> mDeviceLocalBuffersWithBackingMemory;
std::unordered_map<VkImage, vk::UniqueDeviceMemory> mImagesWithBackingMemory;
#endif
std::deque<vk::UniqueCommandBuffer> mSingleUseCommandBuffers;
std::unordered_map<VkPipeline, std::tuple<vk::UniqueDescriptorSetLayout, vk::UniquePipelineLayout>> mPipelineLayouts;
vk::Pipeline mBasicPipeline;
GLFWwindow* mCallbackWindow = nullptr;
GLFWkeyfun mPreviousKeyCallback = nullptr;
int mKeyForShaderHotReloading = 0;
int mModKeysForShaderHotReloading = 0;
std::unordered_map<VkPipeline, std::tuple<VklGraphicsPipelineConfig, std::string, std::string, bool>> mUserKnownPipelines;
std::unordered_map<VkPipeline, VkPipeline> mPipelineSurrogates;
std::deque<std::tuple<int64_t, VkPipeline>> mPipelineGraveyard;
// TODO: Implement this MAKEFOURCC in a sane way instead of just copying definitions.
enum class byte : unsigned char {};
#ifndef _BYTE_DEFINED
#define _BYTE_DEFINED
typedef byte BYTE;
#endif // !_BYTE_DEFINED
#ifndef _DWORD_DEFINED
#define _DWORD_DEFINED
typedef unsigned long DWORD;
#endif // !_DWORD_DEFINED
#define MAKEFOURCC(ch0, ch1, ch2, ch3) \
((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \
((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 ))
#define FOURCC_DXT1 MAKEFOURCC('D', 'X', 'T', '1')
#define FOURCC_DXT3 MAKEFOURCC('D', 'X', 'T', '3')
#define FOURCC_DXT5 MAKEFOURCC('D', 'X', 'T', '5')
// Debug utils messenger callback:
VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtilsMessengerCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT message_severity,
VkDebugUtilsMessageTypeFlagsEXT message_type,
const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
void* user_data);
std::string mSpaceForToString;
const char* to_string(VkResult result)
{
switch (result) {
case VK_SUCCESS: return "VK_SUCCESS";
case VK_NOT_READY: return "VK_NOT_READY";
case VK_TIMEOUT: return "VK_TIMEOUT";
case VK_EVENT_SET: return "VK_EVENT_SET";
case VK_EVENT_RESET: return "VK_EVENT_RESET";
case VK_INCOMPLETE: return "VK_INCOMPLETE";
case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY";
case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED";
case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST";
case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED";
case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT";
case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT";
case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT";
case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER";
case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS";
case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED";
case VK_ERROR_FRAGMENTED_POOL: return "VK_ERROR_FRAGMENTED_POOL";
case VK_ERROR_UNKNOWN: return "VK_ERROR_UNKNOWN";
case VK_ERROR_OUT_OF_POOL_MEMORY: return "VK_ERROR_OUT_OF_POOL_MEMORY";
case VK_ERROR_INVALID_EXTERNAL_HANDLE: return "VK_ERROR_INVALID_EXTERNAL_HANDLE";
case VK_ERROR_FRAGMENTATION: return "VK_ERROR_FRAGMENTATION";
case VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS: return "VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS";
case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR";
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR";
case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR";
case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
case VK_ERROR_VALIDATION_FAILED_EXT: return "VK_ERROR_VALIDATION_FAILED_EXT";
case VK_ERROR_INVALID_SHADER_NV: return "VK_ERROR_INVALID_SHADER_NV";
case VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT: return "VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT";
case VK_ERROR_NOT_PERMITTED_EXT: return "VK_ERROR_NOT_PERMITTED_EXT";
case VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT: return "VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT";
case VK_THREAD_IDLE_KHR: return "VK_THREAD_IDLE_KHR";
case VK_THREAD_DONE_KHR: return "VK_THREAD_DONE_KHR";
case VK_OPERATION_DEFERRED_KHR: return "VK_OPERATION_DEFERRED_KHR";
case VK_OPERATION_NOT_DEFERRED_KHR: return "VK_OPERATION_NOT_DEFERRED_KHR";
case VK_PIPELINE_COMPILE_REQUIRED_EXT: return "VK_PIPELINE_COMPILE_REQUIRED_EXT";
default:
mSpaceForToString = std::to_string(result);
return mSpaceForToString.c_str();
}
}
#ifdef USE_SHADERC
std::string to_string(shaderc_shader_kind kind)
{
switch (kind) {
case shaderc_vertex_shader: return "shaderc_vertex_shader";
case shaderc_fragment_shader: return "shaderc_fragment_shader";
case shaderc_compute_shader: return "shaderc_compute_shader";
case shaderc_geometry_shader: return "shaderc_geometry_shader";
case shaderc_tess_control_shader: return "shaderc_tess_control_shader";
case shaderc_tess_evaluation_shader: return "shaderc_tess_evaluation_shader";
case shaderc_glsl_infer_from_source: return "shaderc_glsl_infer_from_source";
case shaderc_glsl_default_vertex_shader: return "shaderc_glsl_default_vertex_shader";
case shaderc_glsl_default_fragment_shader: return "shaderc_glsl_default_fragment_shader";
case shaderc_glsl_default_compute_shader: return "shaderc_glsl_default_compute_shader";
case shaderc_glsl_default_geometry_shader: return "shaderc_glsl_default_geometry_shader";
case shaderc_glsl_default_tess_control_shader: return "shaderc_glsl_default_tess_control_shader";
case shaderc_glsl_default_tess_evaluation_shader: return "shaderc_glsl_default_tess_evaluation_shader";
case shaderc_spirv_assembly: return "shaderc_spirv_assembly";
case shaderc_raygen_shader: return "shaderc_raygen_shader";
case shaderc_anyhit_shader: return "shaderc_anyhit_shader";
case shaderc_closesthit_shader: return "shaderc_closesthit_shader";
case shaderc_miss_shader: return "shaderc_miss_shader";
case shaderc_intersection_shader: return "shaderc_intersection_shader";
case shaderc_callable_shader: return "shaderc_callable_shader";
case shaderc_glsl_default_raygen_shader: return "shaderc_glsl_default_raygen_shader";
case shaderc_glsl_default_anyhit_shader: return "shaderc_glsl_default_anyhit_shader";
case shaderc_glsl_default_closesthit_shader: return "shaderc_glsl_default_closesthit_shader";
case shaderc_glsl_default_miss_shader: return "shaderc_glsl_default_miss_shader";
case shaderc_glsl_default_intersection_shader: return "shaderc_glsl_default_intersection_shader";
case shaderc_glsl_default_callable_shader: return "shaderc_glsl_default_callable_shader";
case shaderc_task_shader: return "shaderc_task_shader";
case shaderc_mesh_shader: return "shaderc_mesh_shader";
case shaderc_glsl_default_task_shader: return "shaderc_glsl_default_task_shader";
case shaderc_glsl_default_mesh_shader: return "shaderc_glsl_default_mesh_shader";
default: return std::to_string(kind);
}
}
#endif
#ifdef USE_GLSLANG
std::string to_string(glslang_stage_t stage)
{
switch (stage) {
case GLSLANG_STAGE_VERTEX: return "GLSLANG_STAGE_VERTEX";
case GLSLANG_STAGE_TESSCONTROL: return "GLSLANG_STAGE_TESSCONTROL";
case GLSLANG_STAGE_TESSEVALUATION: return "GLSLANG_STAGE_TESSEVALUATION";
case GLSLANG_STAGE_GEOMETRY: return "GLSLANG_STAGE_GEOMETRY";
case GLSLANG_STAGE_FRAGMENT: return "GLSLANG_STAGE_FRAGMENT";
case GLSLANG_STAGE_COMPUTE: return "GLSLANG_STAGE_COMPUTE";
case GLSLANG_STAGE_RAYGEN_NV: return "GLSLANG_STAGE_RAYGEN_NV";
case GLSLANG_STAGE_INTERSECT_NV: return "GLSLANG_STAGE_INTERSECT_NV";
case GLSLANG_STAGE_ANYHIT_NV: return "GLSLANG_STAGE_ANYHIT_NV";
case GLSLANG_STAGE_CLOSESTHIT_NV: return "GLSLANG_STAGE_CLOSESTHIT_NV";
case GLSLANG_STAGE_MISS_NV: return "GLSLANG_STAGE_MISS_NV";
case GLSLANG_STAGE_CALLABLE_NV: return "GLSLANG_STAGE_CALLABLE_NV";
case GLSLANG_STAGE_TASK_NV: return "GLSLANG_STAGE_TASK_NV";
case GLSLANG_STAGE_MESH_NV: return "GLSLANG_STAGE_MESH_NV";
default: return std::to_string(stage);
}
}
glslang_resource_t get_default_resource() {
glslang_resource_t r = {
/* .MaxLights = */ 32,
/* .MaxClipPlanes = */ 6,
/* .MaxTextureUnits = */ 32,
/* .MaxTextureCoords = */ 32,
/* .MaxVertexAttribs = */ 64,
/* .MaxVertexUniformComponents = */ 4096,
/* .MaxVaryingFloats = */ 64,
/* .MaxVertexTextureImageUnits = */ 32,
/* .MaxCombinedTextureImageUnits = */ 80,
/* .MaxTextureImageUnits = */ 32,
/* .MaxFragmentUniformComponents = */ 4096,
/* .MaxDrawBuffers = */ 32,
/* .MaxVertexUniformVectors = */ 128,
/* .MaxVaryingVectors = */ 8,
/* .MaxFragmentUniformVectors = */ 16,
/* .MaxVertexOutputVectors = */ 16,
/* .MaxFragmentInputVectors = */ 15,
/* .MinProgramTexelOffset = */ -8,
/* .MaxProgramTexelOffset = */ 7,
/* .MaxClipDistances = */ 8,
/* .MaxComputeWorkGroupCountX = */ 65535,
/* .MaxComputeWorkGroupCountY = */ 65535,
/* .MaxComputeWorkGroupCountZ = */ 65535,
/* .MaxComputeWorkGroupSizeX = */ 1024,
/* .MaxComputeWorkGroupSizeY = */ 1024,
/* .MaxComputeWorkGroupSizeZ = */ 64,
/* .MaxComputeUniformComponents = */ 1024,
/* .MaxComputeTextureImageUnits = */ 16,
/* .MaxComputeImageUniforms = */ 8,
/* .MaxComputeAtomicCounters = */ 8,
/* .MaxComputeAtomicCounterBuffers = */ 1,
/* .MaxVaryingComponents = */ 60,
/* .MaxVertexOutputComponents = */ 64,
/* .MaxGeometryInputComponents = */ 64,
/* .MaxGeometryOutputComponents = */ 128,
/* .MaxFragmentInputComponents = */ 128,
/* .MaxImageUnits = */ 8,
/* .MaxCombinedImageUnitsAndFragmentOutputs = */ 8,
/* .MaxCombinedShaderOutputResources = */ 8,
/* .MaxImageSamples = */ 0,
/* .MaxVertexImageUniforms = */ 0,
/* .MaxTessControlImageUniforms = */ 0,
/* .MaxTessEvaluationImageUniforms = */ 0,
/* .MaxGeometryImageUniforms = */ 0,
/* .MaxFragmentImageUniforms = */ 8,
/* .MaxCombinedImageUniforms = */ 8,
/* .MaxGeometryTextureImageUnits = */ 16,
/* .MaxGeometryOutputVertices = */ 256,
/* .MaxGeometryTotalOutputComponents = */ 1024,
/* .MaxGeometryUniformComponents = */ 1024,
/* .MaxGeometryVaryingComponents = */ 64,
/* .MaxTessControlInputComponents = */ 128,
/* .MaxTessControlOutputComponents = */ 128,
/* .MaxTessControlTextureImageUnits = */ 16,
/* .MaxTessControlUniformComponents = */ 1024,
/* .MaxTessControlTotalOutputComponents = */ 4096,
/* .MaxTessEvaluationInputComponents = */ 128,
/* .MaxTessEvaluationOutputComponents = */ 128,
/* .MaxTessEvaluationTextureImageUnits = */ 16,
/* .MaxTessEvaluationUniformComponents = */ 1024,
/* .MaxTessPatchComponents = */ 120,
/* .MaxPatchVertices = */ 32,
/* .MaxTessGenLevel = */ 64,
/* .MaxViewports = */ 16,
/* .MaxVertexAtomicCounters = */ 0,
/* .MaxTessControlAtomicCounters = */ 0,
/* .MaxTessEvaluationAtomicCounters = */ 0,
/* .MaxGeometryAtomicCounters = */ 0,
/* .MaxFragmentAtomicCounters = */ 8,
/* .MaxCombinedAtomicCounters = */ 8,
/* .MaxAtomicCounterBindings = */ 1,
/* .MaxVertexAtomicCounterBuffers = */ 0,
/* .MaxTessControlAtomicCounterBuffers = */ 0,
/* .MaxTessEvaluationAtomicCounterBuffers = */ 0,
/* .MaxGeometryAtomicCounterBuffers = */ 0,
/* .MaxFragmentAtomicCounterBuffers = */ 1,
/* .MaxCombinedAtomicCounterBuffers = */ 1,
/* .MaxAtomicCounterBufferSize = */ 16384,
/* .MaxTransformFeedbackBuffers = */ 4,
/* .MaxTransformFeedbackInterleavedComponents = */ 64,
/* .MaxCullDistances = */ 8,
/* .MaxCombinedClipAndCullDistances = */ 8,
/* .MaxSamples = */ 4,
/* .maxMeshOutputVerticesNV = */ 256,
/* .maxMeshOutputPrimitivesNV = */ 512,
/* .maxMeshWorkGroupSizeX_NV = */ 32,
/* .maxMeshWorkGroupSizeY_NV = */ 1,
/* .maxMeshWorkGroupSizeZ_NV = */ 1,
/* .maxTaskWorkGroupSizeX_NV = */ 32,
/* .maxTaskWorkGroupSizeY_NV = */ 1,
/* .maxTaskWorkGroupSizeZ_NV = */ 1,
/* .maxMeshViewCountNV = */ 4,
/* .maxMeshOutputVerticesEXT = */ 256,
/* .maxMeshOutputPrimitivesEXT = */ 256,
/* .maxMeshWorkGroupSizeX_EXT = */ 128,
/* .maxMeshWorkGroupSizeY_EXT = */ 128,
/* .maxMeshWorkGroupSizeZ_EXT = */ 128,
/* .maxTaskWorkGroupSizeX_EXT = */ 128,
/* .maxTaskWorkGroupSizeY_EXT = */ 128,
/* .maxTaskWorkGroupSizeZ_EXT = */ 128,
/* .maxMeshViewCountEXT = */ 4,
/* .maxDualSourceDrawBuffersEXT = */ 1,
/* .limits = */ {
/* .nonInductiveForLoops = */ 1,
/* .whileLoops = */ 1,
/* .doWhileLoops = */ 1,
/* .generalUniformIndexing = */ 1,
/* .generalAttributeMatrixVectorIndexing = */ 1,
/* .generalVaryingIndexing = */ 1,
/* .generalSamplerIndexing = */ 1,
/* .generalVariableIndexing = */ 1,
/* .generalConstantMatrixVectorIndexing = */ 1,
}
};
return r;
}
#endif
// Compiles a shader to a SPIR-V binary. Returns the binary as a vector of 32-bit words.
std::vector<uint32_t> compileShaderSourceToSpirv(const std::string& shaderSource, const std::string& inputFilename
#ifdef USE_SHADERC
, shaderc_shader_kind shaderKind
#endif
#ifdef USE_GLSLANG
, glslang_stage_t shaderStage
#endif
)
{
#ifdef USE_SHADERC
// This code is borrowed from the shaderc example: https://github.com/google/shaderc/blob/main/examples/online-compile/main.cc
shaderc::Compiler compiler;
shaderc::CompileOptions options;
shaderc::SpvCompilationResult module = compiler.CompileGlslToSpv(shaderSource, shaderKind, inputFilename.c_str(), options);
if (module.GetCompilationStatus() != shaderc_compilation_status_success) {
std::cout << "\nERROR: Failed to compile shader[" << inputFilename << " of kind[" << to_string(shaderKind) << "]\n"
<< "\n Reason(s)[\n" << module.GetErrorMessage() << "\n ]" << std::endl;
throw std::runtime_error("Failed to compile shader " + inputFilename);
}
return { module.cbegin(), module.cend() };
#else
std::vector<uint32_t> resultingSpirv;
#ifdef USE_GLSLANG
const char* shaderCode = shaderSource.c_str();
static const auto defaultResources = get_default_resource();
glslang_input_t input = {};
input.language = GLSLANG_SOURCE_GLSL;
input.stage = shaderStage;
input.client = GLSLANG_CLIENT_VULKAN;
// Looks like Vulkan 1.1 is fine even though we're linking against a Vulkan 1.2 SDK:
input.client_version = GLSLANG_TARGET_VULKAN_1_1;
input.target_language = GLSLANG_TARGET_SPV;
// SPIR-V 1.5 has been released on September 13th, 2019 to accompany the launch of Vulkan 1.2
// However, Vulkan 1.1 requires Spir-V 1.3, go with 1.3 to match the Vulkan 1.1 target above:
input.target_language_version = GLSLANG_TARGET_SPV_1_3;
input.code = shaderCode;
input.default_version = 100;
input.default_profile = GLSLANG_NO_PROFILE;
input.force_default_version_and_profile = false;
input.forward_compatible = false;
input.messages = GLSLANG_MSG_DEFAULT_BIT;
input.resource = &defaultResources;
glslang_shader_t* shader = glslang_shader_create(&input);
if (!glslang_shader_preprocess(shader, &input))
{
std::cout << "\nERROR: Failed to preprocess shader[" << inputFilename << "] of kind[" << to_string(shaderStage) << "]"
<< "\n Log[" << glslang_shader_get_info_log(shader) << "]"
<< "\n Debug-Log[" << glslang_shader_get_info_debug_log(shader) << "]" << std::endl;
return resultingSpirv;
}
if (!glslang_shader_parse(shader, &input))
{
std::cout << "\nERROR: Failed to parse shader[" << inputFilename << "] of kind[" << to_string(shaderStage) << "]"
<< "\n Log[" << glslang_shader_get_info_log(shader) << "]"
<< "\n Debug-Log[" << glslang_shader_get_info_debug_log(shader) << "]" << std::endl;
return resultingSpirv;
}
glslang_program_t* program = glslang_program_create();
glslang_program_add_shader(program, shader);
if (!glslang_program_link(program, GLSLANG_MSG_SPV_RULES_BIT | GLSLANG_MSG_VULKAN_RULES_BIT))
{
std::cout << "\nERROR: Failed to link shader[" << inputFilename << "] of kind[" << to_string(shaderStage) << "]"
<< "\n Log[" << glslang_shader_get_info_log(shader) << "]"
<< "\n Debug-Log[" << glslang_shader_get_info_debug_log(shader) << "]" << std::endl;
return resultingSpirv;
}
glslang_program_SPIRV_generate(program, input.stage);
if (glslang_program_SPIRV_get_messages(program))
{
printf("%s", glslang_program_SPIRV_get_messages(program));
std::cout << "\nINFO: Got messages for shader[" << inputFilename << " of kind[" << to_string(shaderStage) << "]"
<< "\n Message[" << glslang_program_SPIRV_get_messages(program) << "]" << std::endl;
}
auto* spirvDataPtr = glslang_program_SPIRV_get_ptr(program);
const auto spirvNumWords = glslang_program_SPIRV_get_size(program);
resultingSpirv.insert(std::end(resultingSpirv), spirvDataPtr, spirvDataPtr + spirvNumWords);
glslang_program_delete(program);
glslang_shader_delete(shader);
#endif
return resultingSpirv;
#endif
}
// Creates a shader module from the given Spir-V code, returns the created shader module and its create info.
// The entry point is "main" always
std::tuple<vk::ShaderModule, vk::PipelineShaderStageCreateInfo> loadShaderFromSpirvAndCreateShaderModuleAndStageInfo(const uint32_t* spirv, size_t byteSize, const vk::ShaderStageFlagBits shaderStage)
{
auto moduleCreateInfo = vk::ShaderModuleCreateInfo{}
.setCodeSize(byteSize)
.setPCode(spirv);
auto shaderModule = mDevice.createShaderModule(moduleCreateInfo);
auto shaderStageCreateInfo = vk::PipelineShaderStageCreateInfo{}
.setStage(shaderStage)
.setModule(shaderModule)
.setPName("main"); // entry point
return std::make_tuple(shaderModule, shaderStageCreateInfo);
}
std::tuple<vk::ShaderModule, vk::PipelineShaderStageCreateInfo> loadShaderFromMemoryAndCreateShaderModuleAndStageInfo(const std::string& shaderCode, const std::string& shaderName, const vk::ShaderStageFlagBits shaderStage)
{
#ifdef USE_SHADERC
shaderc_shader_kind shadercKind;
switch (shaderStage) {
case vk::ShaderStageFlagBits::eVertex: shadercKind = shaderc_shader_kind::shaderc_vertex_shader; break;
case vk::ShaderStageFlagBits::eTessellationControl: shadercKind = shaderc_shader_kind::shaderc_tess_control_shader; break;
case vk::ShaderStageFlagBits::eTessellationEvaluation: shadercKind = shaderc_shader_kind::shaderc_tess_evaluation_shader; break;
case vk::ShaderStageFlagBits::eGeometry: shadercKind = shaderc_shader_kind::shaderc_geometry_shader; break;
case vk::ShaderStageFlagBits::eFragment: shadercKind = shaderc_shader_kind::shaderc_fragment_shader; break;
case vk::ShaderStageFlagBits::eCompute: shadercKind = shaderc_shader_kind::shaderc_compute_shader; break;
case vk::ShaderStageFlagBits::eRaygenKHR: shadercKind = shaderc_shader_kind::shaderc_raygen_shader; break;
case vk::ShaderStageFlagBits::eAnyHitKHR: shadercKind = shaderc_shader_kind::shaderc_anyhit_shader; break;
case vk::ShaderStageFlagBits::eClosestHitKHR: shadercKind = shaderc_shader_kind::shaderc_closesthit_shader; break;
case vk::ShaderStageFlagBits::eMissKHR: shadercKind = shaderc_shader_kind::shaderc_miss_shader; break;
case vk::ShaderStageFlagBits::eIntersectionKHR: shadercKind = shaderc_shader_kind::shaderc_intersection_shader; break;
case vk::ShaderStageFlagBits::eCallableKHR: shadercKind = shaderc_shader_kind::shaderc_callable_shader; break;
case vk::ShaderStageFlagBits::eTaskNV: shadercKind = shaderc_shader_kind::shaderc_task_shader; break;
case vk::ShaderStageFlagBits::eMeshNV: shadercKind = shaderc_shader_kind::shaderc_mesh_shader; break;
}
auto spirv = compileShaderSourceToSpirv(shaderCode, shaderName, shadercKind);
#endif
#ifdef USE_GLSLANG
glslang_stage_t glslangStage;
switch (shaderStage) {
case vk::ShaderStageFlagBits::eVertex: glslangStage = GLSLANG_STAGE_VERTEX; break;
case vk::ShaderStageFlagBits::eTessellationControl: glslangStage = GLSLANG_STAGE_TESSCONTROL; break;
case vk::ShaderStageFlagBits::eTessellationEvaluation: glslangStage = GLSLANG_STAGE_TESSEVALUATION; break;
case vk::ShaderStageFlagBits::eGeometry: glslangStage = GLSLANG_STAGE_GEOMETRY; break;
case vk::ShaderStageFlagBits::eFragment: glslangStage = GLSLANG_STAGE_FRAGMENT; break;
case vk::ShaderStageFlagBits::eCompute: glslangStage = GLSLANG_STAGE_COMPUTE; break;
case vk::ShaderStageFlagBits::eRaygenKHR: glslangStage = GLSLANG_STAGE_RAYGEN; break;
case vk::ShaderStageFlagBits::eAnyHitKHR: glslangStage = GLSLANG_STAGE_ANYHIT; break;
case vk::ShaderStageFlagBits::eClosestHitKHR: glslangStage = GLSLANG_STAGE_CLOSESTHIT; break;
case vk::ShaderStageFlagBits::eMissKHR: glslangStage = GLSLANG_STAGE_MISS; break;
case vk::ShaderStageFlagBits::eIntersectionKHR: glslangStage = GLSLANG_STAGE_INTERSECT; break;
case vk::ShaderStageFlagBits::eCallableKHR: glslangStage = GLSLANG_STAGE_CALLABLE; break;
case vk::ShaderStageFlagBits::eTaskNV: glslangStage = GLSLANG_STAGE_TASK; break;
case vk::ShaderStageFlagBits::eMeshNV: glslangStage = GLSLANG_STAGE_MESH; break;
}
auto spirv = compileShaderSourceToSpirv(shaderCode, shaderName, glslangStage);
#endif
if (spirv.empty()) {
return std::make_tuple(vk::ShaderModule{ VK_NULL_HANDLE }, vk::PipelineShaderStageCreateInfo{});
}
// | SPIR-V Code | Size must be specified in BYTE => * sizeof WORD | Stage |
return loadShaderFromSpirvAndCreateShaderModuleAndStageInfo(spirv.data(), spirv.size() * sizeof(decltype(spirv)::value_type), shaderStage);
}
std::tuple<vk::ShaderModule, vk::PipelineShaderStageCreateInfo> loadShaderFromFileAndCreateShaderModuleAndStageInfo(const std::string& shader_filename, const vk::ShaderStageFlagBits shaderStage)
{
std::string path = {};
std::ifstream infile(shader_filename);
if (infile.good()) {
path = shader_filename;
VKL_LOG("Loading shader file from path[" << path << "]...");
}
if (path.empty()) { // Fail if shader file could not be found:
VKL_EXIT_WITH_ERROR("Unable to load file[" << shader_filename << "].");
}
std::ifstream ifs(path);
std::string content(
(std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>())
);
return loadShaderFromMemoryAndCreateShaderModuleAndStageInfo(content, path, shaderStage);
}
VkPipeline createGraphicsPipelineInternal(const VklGraphicsPipelineConfig& config, bool loadShadersFromMemoryInstead)
{
if (!loadShadersFromMemoryInstead && !vklFrameworkInitialized()) {
VKL_EXIT_WITH_ERROR("Framework not initialized. Ensure to invoke vklInitFramework beforehand!");
}
// Create the graphics pipeline, describe every state of it
// Get tuples of <vk::ShaderModule, vk::PipelineShaderStageCreateInfo>
auto vertTpl = loadShadersFromMemoryInstead
? loadShaderFromMemoryAndCreateShaderModuleAndStageInfo(config.vertexShaderPath, "vertex shader from memory", vk::ShaderStageFlagBits::eVertex)
: loadShaderFromFileAndCreateShaderModuleAndStageInfo(config.vertexShaderPath, vk::ShaderStageFlagBits::eVertex);
if (!std::get<vk::ShaderModule>(vertTpl)) {
return VK_NULL_HANDLE;
}
auto fragTpl = loadShadersFromMemoryInstead
? loadShaderFromMemoryAndCreateShaderModuleAndStageInfo(config.fragmentShaderPath, "fragment shader from memory", vk::ShaderStageFlagBits::eFragment)
: loadShaderFromFileAndCreateShaderModuleAndStageInfo(config.fragmentShaderPath, vk::ShaderStageFlagBits::eFragment);
if (!std::get<vk::ShaderModule>(fragTpl)) {
mDevice.destroyShaderModule(std::get<vk::ShaderModule>(vertTpl));
return VK_NULL_HANDLE;
}
// Describe the shaders used:
std::array<vk::PipelineShaderStageCreateInfo, 2> shaderStages{ std::get<vk::PipelineShaderStageCreateInfo>(vertTpl), std::get<vk::PipelineShaderStageCreateInfo>(fragTpl) };
// Describe the vertex input, i.e. two vertex input attributes in our case:
std::vector<vk::VertexInputBindingDescription> inputBufferBindings(std::begin(config.vertexInputBuffers), std::end(config.vertexInputBuffers));
std::vector<vk::VertexInputAttributeDescription> inputAttributeDescriptions(std::begin(config.inputAttributeDescriptions), std::end(config.inputAttributeDescriptions));
auto vertexInputState = vk::PipelineVertexInputStateCreateInfo{}
.setVertexBindingDescriptionCount(static_cast<uint32_t>(inputBufferBindings.size())).setPVertexBindingDescriptions(inputBufferBindings.data())
.setVertexAttributeDescriptionCount(static_cast<uint32_t>(inputAttributeDescriptions.size())).setPVertexAttributeDescriptions(inputAttributeDescriptions.data());
// Describe the topology of the vertices
auto inputAssemblyState = vk::PipelineInputAssemblyStateCreateInfo{}.setTopology(vk::PrimitiveTopology::eTriangleList);
// Describe viewport and scissors state
auto viewport = vk::Viewport{}
.setX(0.0f).setY(0.0f)
.setWidth(static_cast<float>(mSwapchainConfig.imageExtent.width)).setHeight(static_cast<float>(mSwapchainConfig.imageExtent.height))
.setMinDepth(0.0f).setMaxDepth(1.0f);
auto scissors = vk::Rect2D{}.setOffset({ 0, 0 }).setExtent(mSwapchainConfig.imageExtent);
auto viewportState = vk::PipelineViewportStateCreateInfo{}
.setViewportCount(1u).setPViewports(&viewport)
.setScissorCount(1u).setPScissors(&scissors);
// Describe the rasterizer state
auto rasterizerState = vk::PipelineRasterizationStateCreateInfo{}
.setPolygonMode(static_cast<vk::PolygonMode>(config.polygonDrawMode))
.setLineWidth(1.0f) // reasons...
.setCullMode(static_cast<vk::CullModeFlags>(config.triangleCullingMode))
.setFrontFace(vk::FrontFace::eCounterClockwise);
// Describe multisampling state
auto multisampleState = vk::PipelineMultisampleStateCreateInfo{}.setRasterizationSamples(vk::SampleCountFlagBits::e1);
// Configure depth/stencil state
auto depthStencilState = vk::PipelineDepthStencilStateCreateInfo{}
.setDepthTestEnable( mHasDepthAttachments ? VK_TRUE : VK_FALSE)
.setDepthWriteEnable(mHasDepthAttachments ? VK_TRUE : VK_FALSE)
.setDepthCompareOp(vk::CompareOp::eLess);
// Configure blending and which color channels are written
auto colorBlendAttachmentState = vk::PipelineColorBlendAttachmentState{}
.setBlendEnable(VK_FALSE)
.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA); // write all color components
if (config.enableAlphaBlending) {
colorBlendAttachmentState
.setBlendEnable(VK_TRUE)
.setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha)
.setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha)
.setColorBlendOp(vk::BlendOp::eAdd)
.setSrcAlphaBlendFactor(vk::BlendFactor::eSrcAlpha)
.setDstAlphaBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha)
.setAlphaBlendOp(vk::BlendOp::eAdd);
}
auto colorBlendState = vk::PipelineColorBlendStateCreateInfo{}.setAttachmentCount(1u).setPAttachments(&colorBlendAttachmentState);
// But again: not so fast! We have to define the LAYOUT of our descriptors first
std::vector<vk::DescriptorSetLayoutBinding> layoutBindings(std::begin(config.descriptorLayout), std::end(config.descriptorLayout));
auto descriptorSetLayout = mDevice.createDescriptorSetLayoutUnique(
vk::DescriptorSetLayoutCreateInfo{}
.setBindingCount(static_cast<uint32_t>(layoutBindings.size()))
.setPBindings(layoutBindings.data())
, nullptr, mDispatchLoader
);
// Continue with configuring our graphics pipeline:
// Create a PIPELINE LAYOUT which describes all RESOURCES that are passed in to our pipeline (Resource Descriptors that we have created above)
auto pipelineLayout = mDevice.createPipelineLayoutUnique(
vk::PipelineLayoutCreateInfo{} // A pipeline's layout describes all resources used by a pipeline or in shaders.
.setSetLayoutCount(1u)
.setPSetLayouts(&descriptorSetLayout.get()) // We don't need the actual descriptors when defining the PIPELINE. The LAYOUT is sufficient at this point.
, nullptr, mDispatchLoader
);
// Put everything together:
auto pipelineCreateInfo = vk::GraphicsPipelineCreateInfo{}
.setStageCount(static_cast<uint32_t>(shaderStages.size())).setPStages(shaderStages.data())
.setPVertexInputState(&vertexInputState)
.setPInputAssemblyState(&inputAssemblyState)
.setPViewportState(&viewportState)
.setPRasterizationState(&rasterizerState)
.setPMultisampleState(&multisampleState)
.setPDepthStencilState(&depthStencilState)
.setPColorBlendState(&colorBlendState)
.setLayout(pipelineLayout.get())
.setRenderPass(mRenderpass.get()).setSubpass(0u); // <--- Which subpass of the given renderpass we are going to use this graphics pipeline for
// FINALLY:
auto graphicsPipeline = mDevice.createGraphicsPipeline(nullptr, pipelineCreateInfo).value;
// Don't need the modules anymore:
mDevice.destroyShaderModule(std::get<vk::ShaderModule>(fragTpl));
mDevice.destroyShaderModule(std::get<vk::ShaderModule>(vertTpl));
auto graphicsPipelineHandle = static_cast<VkPipeline>(graphicsPipeline);
mPipelineLayouts[graphicsPipelineHandle] = std::forward_as_tuple(std::move(descriptorSetLayout), std::move(pipelineLayout));
return graphicsPipelineHandle;
}
VkPipeline vklCreateGraphicsPipeline(const VklGraphicsPipelineConfig& config, bool loadShadersFromMemoryInstead)
{
auto graphicsPipelineHandle = createGraphicsPipelineInternal(config, loadShadersFromMemoryInstead);
if (VK_NULL_HANDLE == graphicsPipelineHandle) {
VKL_EXIT_WITH_ERROR("Failed to create graphics pipeline. Check console output if there were any problems with shader compilation!");
}
// Store for hot reloading, but only those handles, which the user requested explicitly (hence the split of createGraphicsPipelineInternal and vklCreateGraphicsPipeline):
mUserKnownPipelines[graphicsPipelineHandle] = std::make_tuple(config, std::string(config.vertexShaderPath), std::string(config.fragmentShaderPath), loadShadersFromMemoryInstead);
return graphicsPipelineHandle;
}
VkPipeline getGraphicsPipelineOrItsSurrogate(VkPipeline originalPipelineHandle)
{
auto it = mPipelineSurrogates.find(originalPipelineHandle);
if (it != mPipelineSurrogates.end()) {
return it->second; // using the surrogate/updated pipeline
}
return originalPipelineHandle;
}
void destroyGraphicsPipelineInternal(VkPipeline pipeline)
{
mDevice.destroy(vk::Pipeline{ pipeline });
// Also remove it from the graveyard:
mPipelineGraveyard.erase(std::remove_if(
mPipelineGraveyard.begin(),
mPipelineGraveyard.end(),
[pipeline](const std::tuple<int64_t, VkPipeline>& element) {
return std::get<1>(element) == pipeline;
}
), mPipelineGraveyard.end());
// ...and as a surrogate (i.e., "pointed to"):
for(auto it = mPipelineSurrogates.begin(); it != mPipelineSurrogates.end();) {
if (it->second == pipeline) {
it = mPipelineSurrogates.erase(it);
}
else {
++it;
}
}
// but NOT from known pipelines!
}
void vklDestroyGraphicsPipeline(VkPipeline pipeline)
{
if (!vklFrameworkInitialized()) {
VKL_EXIT_WITH_ERROR("Framework not initialized. Ensure to not invoke vklDestroyFramework beforehand!");
}
// Destroy the latest surrogate:
destroyGraphicsPipelineInternal(getGraphicsPipelineOrItsSurrogate(pipeline));
// Remove the ORIGINAL pipeline handle from known pipelines:
auto it = mUserKnownPipelines.find(pipeline);
if (it != mUserKnownPipelines.end()) {
mUserKnownPipelines.erase(it);
}
// ...and potentially also from surrogate list (if it is the "points from" entry):
for(auto it = mPipelineSurrogates.begin(); it != mPipelineSurrogates.end();) {
if (it->first == pipeline) {
it = mPipelineSurrogates.erase(it);
}
else {
++it;
}
}
}
vk::MemoryAllocateInfo vklCreateMemoryAllocateInfo(vk::DeviceSize bufferSize, vk::MemoryRequirements memoryRequirements, vk::MemoryPropertyFlags memoryPropertyFlags) {
auto memoryAllocInfo = vk::MemoryAllocateInfo{}
.setAllocationSize(std::max(bufferSize, memoryRequirements.size))
.setMemoryTypeIndex([&]() {
// Get memory types supported by the physical device:
auto memoryProperties = mPhysicalDevice.getMemoryProperties();
// In search for a suitable memory type INDEX:
int selectedMemIndex = -1;
vk::DeviceSize selectedHeapSize = 0;
for (int i = 0; i < static_cast<int>(memoryProperties.memoryTypeCount); ++i) {
// Is this kind of memory suitable for our buffer?
const auto bitmask = memoryRequirements.memoryTypeBits;
const auto bit = 1 << i;
if (0 == (bitmask & bit)) {
continue; // => nope
}
// Does this kind of memory support our usage requirements?
if ((memoryProperties.memoryTypes[i].propertyFlags & (memoryPropertyFlags)) != vk::MemoryPropertyFlags{}) {
// Would support => now select the one with the largest heap:
const auto heapSize = memoryProperties.memoryHeaps[memoryProperties.memoryTypes[i].heapIndex].size;
if (heapSize > selectedHeapSize) {
// We have a new king:
selectedMemIndex = i;
selectedHeapSize = heapSize;
}
}
}
if (-1 == selectedMemIndex) {
VKL_EXIT_WITH_ERROR(std::string("ERROR: Couldn't find suitable memory of size[") + std::to_string(bufferSize) + "] and requirements[" + std::to_string(memoryRequirements.alignment) + ", " + std::to_string(memoryRequirements.memoryTypeBits) + ", " + std::to_string(memoryRequirements.size) + "]");
}
// all good, we found a suitable memory index:
return static_cast<uint32_t>(selectedMemIndex);
}());
return memoryAllocInfo;
}
VkMemoryAllocateInfo vklCreateMemoryAllocateInfo(VkDeviceSize bufferSize, VkMemoryRequirements memoryRequirements, VkMemoryPropertyFlags memoryPropertyFlags) {
return static_cast<VkMemoryAllocateInfo>(vklCreateMemoryAllocateInfo(static_cast<vk::DeviceSize>(bufferSize), static_cast<vk::MemoryRequirements>(memoryRequirements), static_cast<vk::MemoryPropertyFlags>(memoryPropertyFlags)));
}
VkDeviceMemory vklAllocateMemoryForGivenRequirements(VkDeviceSize bufferSize, VkMemoryRequirements memoryRequirements, VkMemoryPropertyFlags memoryPropertyFlags)
{
const auto memoryAllocInfo = vklCreateMemoryAllocateInfo(bufferSize, memoryRequirements, memoryPropertyFlags);
// Allocate:
VkDeviceMemory memory;
VkResult returnCode = vkAllocateMemory(static_cast<VkDevice>(mDevice), &memoryAllocInfo, NULL, &memory);
if (returnCode == VK_SUCCESS) {
return memory;
}
else {
VKL_EXIT_WITH_ERROR(std::string("Error allocating memory of size [") + std::to_string(bufferSize) + "] and requirements[" + std::to_string(memoryRequirements.alignment) + ", " + std::to_string(memoryRequirements.memoryTypeBits) + ", " + std::to_string(memoryRequirements.size) + "]\n Error Code: " + to_string(returnCode));
}
}
vk::UniqueDeviceMemory vklAllocateMemoryForGivenRequirements(vk::DeviceSize bufferSize, vk::MemoryRequirements memoryRequirements, vk::MemoryPropertyFlags memoryPropertyFlags) {
const auto memoryAllocInfo = vklCreateMemoryAllocateInfo(bufferSize, memoryRequirements, memoryPropertyFlags);
auto allocatedMemory = mDevice.allocateMemoryUnique(memoryAllocInfo, nullptr, mDispatchLoader);
return allocatedMemory;
}
VkBuffer vklCreateHostCoherentBufferWithBackingMemory(VkDeviceSize buffer_size, VkBufferUsageFlags buffer_usage)
{
if (!vklFrameworkInitialized()) {
VKL_EXIT_WITH_ERROR("Framework not initialized. Ensure to invoke vklInitFramework beforehand!");
}
// Describe a new buffer:
auto createInfo = vk::BufferCreateInfo{}
.setSize(static_cast<vk::DeviceSize>(buffer_size))
.setUsage(vk::BufferUsageFlags{ buffer_usage });
#ifdef VKL_HAS_VMA
if (vklHasVmaAllocator()) {
VmaAllocationCreateInfo vmaBufferCreateInfo = {};
vmaBufferCreateInfo.usage = VMA_MEMORY_USAGE_UNKNOWN;
vmaBufferCreateInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
VkBuffer bufferFromVma;
VmaAllocation vmaAllocation;
vmaCreateBuffer(mVmaAllocator, &static_cast<const VkBufferCreateInfo&>(createInfo), &vmaBufferCreateInfo, &bufferFromVma, &vmaAllocation, nullptr);
mHostCoherentBuffersWithBackingMemory[bufferFromVma] = std::move(vmaAllocation);
return bufferFromVma;
}
#endif
auto buffer = mDevice.createBuffer(createInfo);
// Allocate the memory (we want host-coherent memory):
auto memory = vklAllocateMemoryForGivenRequirements(static_cast<vk::DeviceSize>(buffer_size), mDevice.getBufferMemoryRequirements(buffer), vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
// Bind the buffer handle to the memory:
// mDevice.bindBufferMemory(buffer, memory.get(), 0);
mDevice.bindBufferMemory(buffer, memory.get(), 0);
// Remember the assignment:
mHostCoherentBuffersWithBackingMemory[static_cast<VkBuffer>(buffer)] = std::move(memory);
return static_cast<VkBuffer>(buffer);
}
VkBuffer vklCreateDeviceLocalBufferWithBackingMemory(VkDeviceSize buffer_size, VkBufferUsageFlags buffer_usage)
{
if (!vklFrameworkInitialized()) {
VKL_EXIT_WITH_ERROR("Framework not initialized. Ensure to invoke vklInitFramework beforehand!");
}
// Describe a new buffer:
auto createInfo = vk::BufferCreateInfo{}
.setSize(static_cast<vk::DeviceSize>(buffer_size))
.setUsage(vk::BufferUsageFlags{ buffer_usage });
#ifdef VKL_HAS_VMA
if (vklHasVmaAllocator()) {
VmaAllocationCreateInfo vmaBufferCreateInfo = {};
vmaBufferCreateInfo.usage = VMA_MEMORY_USAGE_UNKNOWN;
vmaBufferCreateInfo.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
VkBuffer bufferFromVma;
VmaAllocation vmaAllocation;
vmaCreateBuffer(mVmaAllocator, &static_cast<const VkBufferCreateInfo&>(createInfo), &vmaBufferCreateInfo, &bufferFromVma, &vmaAllocation, nullptr);
mDeviceLocalBuffersWithBackingMemory[bufferFromVma] = std::move(vmaAllocation);
return bufferFromVma;
}
#endif
auto buffer = mDevice.createBuffer(createInfo);
// Allocate the memory (we want device-local memory):
auto memory = vklAllocateMemoryForGivenRequirements(static_cast<vk::DeviceSize>(buffer_size), mDevice.getBufferMemoryRequirements(buffer), vk::MemoryPropertyFlagBits::eDeviceLocal);
// Bind the buffer handle to the memory:
// mDevice.bindBufferMemory(buffer, memory.get(), 0);
mDevice.bindBufferMemory(buffer, memory.get(), 0);
// Remember the assignment:
mDeviceLocalBuffersWithBackingMemory[static_cast<VkBuffer>(buffer)] = std::move(memory);
return static_cast<VkBuffer>(buffer);
}
void vklDestroyHostCoherentBufferAndItsBackingMemory(VkBuffer buffer)
{
if (!vklFrameworkInitialized()) {
VKL_EXIT_WITH_ERROR("Framework not initialized. Ensure to not invoke vklDestroyFramework beforehand!");
}
if (VkBuffer{} == buffer) {
VKL_EXIT_WITH_ERROR("Invalid buffer handle passed to vklDestroyHostCoherentBufferAndItsBackingMemory(...)");
}
bool resourceDestroyed = false;
auto search = mHostCoherentBuffersWithBackingMemory.find(buffer);
if (mHostCoherentBuffersWithBackingMemory.end() != search) {
#ifdef VKL_HAS_VMA
if (vklHasVmaAllocator() && std::holds_alternative<VmaAllocation>(search->second)) {
vmaDestroyBuffer(mVmaAllocator, buffer, std::get<VmaAllocation>(search->second));
resourceDestroyed = true;
}
#endif
mHostCoherentBuffersWithBackingMemory.erase(search);
}
else {
VKL_WARNING("VkDeviceMemory for the given VkBuffer not found. Are you sure that you have created this buffer with vklCreateHostCoherentBufferWithBackingMemory(...)? Are you sure that you haven't already destroyed this VkBuffer?");
}
if (!resourceDestroyed) {
mDevice.destroy(vk::Buffer{ buffer });
}
}
void vklDestroyDeviceLocalBufferAndItsBackingMemory(VkBuffer buffer)
{
if (!vklFrameworkInitialized()) {
VKL_EXIT_WITH_ERROR("Framework not initialized. Ensure to not invoke vklDestroyFramework beforehand!");
}
if (VkBuffer{} == buffer) {
VKL_EXIT_WITH_ERROR("Invalid buffer handle passed to vklDestroyDeviceLocalBufferAndItsBackingMemory(...)");
}
bool resourceDestroyed = false;
auto search = mDeviceLocalBuffersWithBackingMemory.find(buffer);
if (mDeviceLocalBuffersWithBackingMemory.end() != search) {
#ifdef VKL_HAS_VMA
if (vklHasVmaAllocator() && std::holds_alternative<VmaAllocation>(search->second)) {
vmaDestroyBuffer(mVmaAllocator, buffer, std::get<VmaAllocation>(search->second));
resourceDestroyed = true;
}
#endif
mDeviceLocalBuffersWithBackingMemory.erase(search);
}
else {
VKL_WARNING("VkDeviceMemory for the given VkBuffer not found. Are you sure that you have created this buffer with vklCreateDeviceLocalBufferWithBackingMemory(...)? Are you sure that you haven't already destroyed this VkBuffer?");
}
if (!resourceDestroyed) {
mDevice.destroy(vk::Buffer{ buffer });
}
}
void vklCopyDataIntoHostCoherentBuffer(VkBuffer buffer, const void* data_pointer, size_t data_size_in_bytes)
{
vklCopyDataIntoHostCoherentBuffer(buffer, 0, data_pointer, data_size_in_bytes);
}
void vklCopyDataIntoHostCoherentBuffer(VkBuffer buffer, size_t buffer_offset_in_bytes, const void* data_pointer, size_t data_size_in_bytes)
{
if (!vklFrameworkInitialized()) {
VKL_EXIT_WITH_ERROR("Framework not initialized. Ensure to invoke vklInitFramework beforehand!");
}
if (VkBuffer{} == buffer) {
VKL_EXIT_WITH_ERROR("Invalid buffer handle passed to vklCopyDataIntoHostCoherentBuffer(...)");
}
auto search = mHostCoherentBuffersWithBackingMemory.find(buffer);
if (mHostCoherentBuffersWithBackingMemory.end() == search) {
VKL_EXIT_WITH_ERROR("Couldn't find backing memory for the given VkBuffer => Can't copy data. Have you created the buffer via vklCreateHostCoherentBufferWithBackingMemory(...)?");
}
#ifdef VKL_HAS_VMA
if (vklHasVmaAllocator() && std::holds_alternative<VmaAllocation>(search->second)) {
void* mappedData;
auto result = vmaMapMemory(mVmaAllocator, std::get<VmaAllocation>(search->second), &mappedData);
assert(result >= 0);
memcpy(mappedData, data_pointer, data_size_in_bytes);
vmaUnmapMemory(mVmaAllocator, std::get<VmaAllocation>(search->second));
}
else {
uint8_t* mappedMemory = static_cast<uint8_t*>(mDevice.mapMemory(std::get<vk::UniqueDeviceMemory>(search->second).get(), 0, static_cast<vk::DeviceSize>(data_size_in_bytes)));
mappedMemory += buffer_offset_in_bytes;
memcpy(mappedMemory, data_pointer, data_size_in_bytes);
mDevice.unmapMemory(std::get<vk::UniqueDeviceMemory>(search->second).get());
}
#else
uint8_t* mappedMemory = static_cast<uint8_t*>(mDevice.mapMemory(search->second.get(), 0, static_cast<vk::DeviceSize>(data_size_in_bytes)));
mappedMemory += buffer_offset_in_bytes;
memcpy(mappedMemory, data_pointer, data_size_in_bytes);
mDevice.unmapMemory(search->second.get());
#endif
}
/*!
* Create a new host coherent buffer on the GPU, upload the supplied data from the vector, and return the buffer handle.
*
* @param data Pointer to the data to upload to the GPU.
* @param size Size of the data in bytes.
* @param usageFlags Usage flags to use when createing the buffer.
* @return The handle of the newly generated buffer.
*/
VkBuffer vklCreateHostCoherentBufferAndUploadData(const void* data, size_t size, VkBufferUsageFlags usageFlags) {
VkBuffer result {};
result = vklCreateHostCoherentBufferWithBackingMemory(
static_cast<VkDeviceSize>(size),
VK_BUFFER_USAGE_TRANSFER_DST_BIT | usageFlags
);
vklCopyDataIntoHostCoherentBuffer(result, data, size);
return result;