-
Notifications
You must be signed in to change notification settings - Fork 63
/
gpu_device.cpp
3552 lines (2776 loc) · 148 KB
/
gpu_device.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
#include "graphics/gpu_device.hpp"
#include "graphics/command_buffer.hpp"
#include "graphics/spirv_parser.hpp"
#include "foundation/memory.hpp"
#include "foundation/hash_map.hpp"
#include "foundation/process.hpp"
#include "foundation/file.hpp"
template<class T>
constexpr const T& raptor_min( const T& a, const T& b ) {
return ( a < b ) ? a : b;
}
template<class T>
constexpr const T& raptor_max( const T& a, const T& b ) {
return ( a < b ) ? b : a;
}
#define VMA_MAX raptor_max
#define VMA_MIN raptor_min
#define VMA_USE_STL_CONTAINERS 0
#define VMA_USE_STL_VECTOR 0
#define VMA_USE_STL_UNORDERED_MAP 0
#define VMA_USE_STL_LIST 0
#if defined (_MSC_VER)
#pragma warning (disable: 4127)
#pragma warning (disable: 4189)
#pragma warning (disable: 4191)
#pragma warning (disable: 4296)
#pragma warning (disable: 4324)
#pragma warning (disable: 4355)
#pragma warning (disable: 4365)
#pragma warning (disable: 4625)
#pragma warning (disable: 4626)
#pragma warning (disable: 4668)
#pragma warning (disable: 5026)
#pragma warning (disable: 5027)
#endif // _MSC_VER
//#define VMA_DEBUG_LOG rprintret
#define VMA_IMPLEMENTATION
#include "external/vk_mem_alloc.h"
// SDL and Vulkan headers
#include <SDL.h>
#include <SDL_vulkan.h>
namespace raptor {
static void check_result( VkResult result );
#define check( result ) RASSERTM( result == VK_SUCCESS, "Vulkan assert code %u", result )
// Device implementation //////////////////////////////////////////////////
// Methods //////////////////////////////////////////////////////////////////////
// Enable this to add debugging capabilities.
// https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VK_EXT_debug_utils.html
#define VULKAN_DEBUG_REPORT
//#define VULKAN_SYNCHRONIZATION_VALIDATION
static const char* s_requested_extensions[] = {
VK_KHR_SURFACE_EXTENSION_NAME,
// Platform specific extension
#ifdef VK_USE_PLATFORM_WIN32_KHR
VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_MACOS_MVK)
VK_MVK_MACOS_SURFACE_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_XCB_KHR)
VK_KHR_XCB_SURFACE_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
VK_KHR_ANDROID_SURFACE_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_XLIB_KHR)
VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_XCB_KHR)
VK_KHR_XCB_SURFACE_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_MIR_KHR || VK_USE_PLATFORM_DISPLAY_KHR)
VK_KHR_DISPLAY_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
VK_KHR_ANDROID_SURFACE_EXTENSION_NAME,
#elif defined(VK_USE_PLATFORM_IOS_MVK)
VK_MVK_IOS_SURFACE_EXTENSION_NAME,
#endif // VK_USE_PLATFORM_WIN32_KHR
#if defined (VULKAN_DEBUG_REPORT)
VK_EXT_DEBUG_REPORT_EXTENSION_NAME,
VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
#endif // VULKAN_DEBUG_REPORT
};
static const char* s_requested_layers[] = {
#if defined (VULKAN_DEBUG_REPORT)
"VK_LAYER_KHRONOS_validation",
//"VK_LAYER_LUNARG_core_validation",
//"VK_LAYER_LUNARG_image",
//"VK_LAYER_LUNARG_parameter_validation",
//"VK_LAYER_LUNARG_object_tracker"
#else
"",
#endif // VULKAN_DEBUG_REPORT
};
#ifdef VULKAN_DEBUG_REPORT
static VkBool32 debug_utils_callback( VkDebugUtilsMessageSeverityFlagBitsEXT severity,
VkDebugUtilsMessageTypeFlagsEXT types,
const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
void* user_data ) {
bool triggerBreak = severity & ( VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT );
if ( triggerBreak ) {
// __debugbreak();
}
rprint( " MessageID: %s %i\nMessage: %s\n\n", callback_data->pMessageIdName, callback_data->messageIdNumber, callback_data->pMessage );
return VK_FALSE;
}
// GPU Timestamps ///////////////////////////////////////////////////
VkDebugUtilsMessengerCreateInfoEXT create_debug_utils_messenger_info() {
VkDebugUtilsMessengerCreateInfoEXT creation_info = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT };
creation_info.pfnUserCallback = debug_utils_callback;
creation_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
creation_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT;
return creation_info;
}
#endif // VULKAN_DEBUG_REPORT
static SDL_Window* sdl_window;
PFN_vkSetDebugUtilsObjectNameEXT pfnSetDebugUtilsObjectNameEXT;
PFN_vkCmdBeginDebugUtilsLabelEXT pfnCmdBeginDebugUtilsLabelEXT;
PFN_vkCmdEndDebugUtilsLabelEXT pfnCmdEndDebugUtilsLabelEXT;
static raptor::FlatHashMap<u64, VkRenderPass> render_pass_cache;
static CommandBufferManager command_buffer_ring;
static const u32 k_bindless_texture_binding = 10;
static const u32 k_max_bindless_resources = 1024;
bool GpuDevice::get_family_queue( VkPhysicalDevice physical_device ) {
u32 queue_family_count = 0;
vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &queue_family_count, nullptr );
VkQueueFamilyProperties* queue_families = ( VkQueueFamilyProperties* )ralloca( sizeof( VkQueueFamilyProperties ) * queue_family_count, allocator );
vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &queue_family_count, queue_families );
u32 family_index = 0;
VkBool32 surface_supported;
for ( ; family_index < queue_family_count; ++family_index ) {
VkQueueFamilyProperties queue_family = queue_families[ family_index ];
if ( queue_family.queueCount > 0 && queue_family.queueFlags & ( VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT ) ) {
vkGetPhysicalDeviceSurfaceSupportKHR( physical_device, family_index, vulkan_window_surface, &surface_supported);
if ( surface_supported ) {
vulkan_main_queue_family = family_index;
break;
}
}
}
rfree( queue_families, allocator );
return surface_supported;
}
void GpuDevice::init( const DeviceCreation& creation ) {
rprint( "Gpu Device init\n" );
// 1. Perform common code
allocator = creation.allocator;
temporary_allocator = creation.temporary_allocator;
string_buffer.init( 1024 * 1024, creation.allocator );
//////// Init Vulkan instance.
VkResult result;
vulkan_allocation_callbacks = nullptr;
VkApplicationInfo application_info = { VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr, "Raptor Graphics Device", 1, "Raptor", 1, VK_MAKE_VERSION( 1, 2, 0 ) };
VkInstanceCreateInfo create_info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, nullptr, 0, &application_info,
#if defined(VULKAN_DEBUG_REPORT)
ArraySize( s_requested_layers ), s_requested_layers,
#else
0, nullptr,
#endif
ArraySize( s_requested_extensions ), s_requested_extensions };
#if defined(VULKAN_DEBUG_REPORT)
const VkDebugUtilsMessengerCreateInfoEXT debug_create_info = create_debug_utils_messenger_info();
#if defined(VULKAN_SYNCHRONIZATION_VALIDATION)
const VkValidationFeatureEnableEXT featuresRequested[] = { VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT, VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT/*, VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT*/ };
VkValidationFeaturesEXT features = {};
features.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT;
features.pNext = &debug_create_info;
features.enabledValidationFeatureCount = _countof( featuresRequested );
features.pEnabledValidationFeatures = featuresRequested;
create_info.pNext = &features;
#else
create_info.pNext = &debug_create_info;
#endif // VULKAN_SYNCHRONIZATION_VALIDATION
#endif // VULKAN_DEBUG_REPORT
//// Create Vulkan Instance
result = vkCreateInstance( &create_info, vulkan_allocation_callbacks, &vulkan_instance );
check( result );
swapchain_width = creation.width;
swapchain_height = creation.height;
StackAllocator* temp_allocator = creation.temporary_allocator;
sizet initial_temp_allocator_marker = temp_allocator->get_marker();
//// Choose extensions
#ifdef VULKAN_DEBUG_REPORT
{
u32 num_instance_extensions;
vkEnumerateInstanceExtensionProperties( nullptr, &num_instance_extensions, nullptr );
VkExtensionProperties* extensions = ( VkExtensionProperties* )ralloca( sizeof( VkExtensionProperties ) * num_instance_extensions, temp_allocator );
vkEnumerateInstanceExtensionProperties( nullptr, &num_instance_extensions, extensions );
for ( size_t i = 0; i < num_instance_extensions; i++ ) {
if ( !strcmp( extensions[ i ].extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME ) ) {
debug_utils_extension_present = true;
continue;
}
}
if ( !debug_utils_extension_present ) {
rprint( "Extension %s for debugging non present.", VK_EXT_DEBUG_UTILS_EXTENSION_NAME );
} else {
// Create new debug utils callback
PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT = ( PFN_vkCreateDebugUtilsMessengerEXT )vkGetInstanceProcAddr( vulkan_instance, "vkCreateDebugUtilsMessengerEXT" );
VkDebugUtilsMessengerCreateInfoEXT debug_messenger_create_info = create_debug_utils_messenger_info();
vkCreateDebugUtilsMessengerEXT( vulkan_instance, &debug_messenger_create_info, vulkan_allocation_callbacks, &vulkan_debug_utils_messenger );
}
}
#endif
//////// Choose physical device
u32 num_physical_device;
result = vkEnumeratePhysicalDevices( vulkan_instance, &num_physical_device, NULL );
check( result );
VkPhysicalDevice* gpus = ( VkPhysicalDevice* )ralloca( sizeof( VkPhysicalDevice ) * num_physical_device, temp_allocator );
result = vkEnumeratePhysicalDevices( vulkan_instance, &num_physical_device, gpus );
check( result );
//////// Create drawable surface
// Create surface
SDL_Window* window = ( SDL_Window* )creation.window;
if ( SDL_Vulkan_CreateSurface( window, vulkan_instance, &vulkan_window_surface ) == SDL_FALSE ) {
rprint( "Failed to create Vulkan surface.\n" );
}
sdl_window = window;
VkPhysicalDevice discrete_gpu = VK_NULL_HANDLE;
VkPhysicalDevice integrated_gpu = VK_NULL_HANDLE;
for ( u32 i = 0; i < num_physical_device; ++i ) {
VkPhysicalDevice physical_device = gpus[ i ];
vkGetPhysicalDeviceProperties( physical_device, &vulkan_physical_properties );
if ( vulkan_physical_properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU ) {
if ( get_family_queue( physical_device ) ) {
// NOTE(marco): prefer discrete GPU over integrated one, stop at first discrete GPU that has
// present capabilities
discrete_gpu = physical_device;
break;
}
continue;
}
if ( vulkan_physical_properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU ) {
if ( get_family_queue( physical_device ) ) {
integrated_gpu = physical_device;
}
continue;
}
}
if ( discrete_gpu != VK_NULL_HANDLE ) {
vulkan_physical_device = discrete_gpu;
} else if ( integrated_gpu != VK_NULL_HANDLE ) {
vulkan_physical_device = integrated_gpu;
} else {
RASSERTM( false, "Suitable GPU device not found!" );
return;
}
temp_allocator->free_marker( initial_temp_allocator_marker );
{
initial_temp_allocator_marker = temp_allocator->get_marker();
u32 device_extension_count = 0;
vkEnumerateDeviceExtensionProperties( vulkan_physical_device, nullptr, &device_extension_count, nullptr );
VkExtensionProperties* extensions = ( VkExtensionProperties* )ralloca( sizeof( VkExtensionProperties ) * device_extension_count, temp_allocator );
vkEnumerateDeviceExtensionProperties( vulkan_physical_device, nullptr, &device_extension_count, extensions );
for ( size_t i = 0; i < device_extension_count; i++ ) {
if ( !strcmp( extensions[ i ].extensionName, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME ) ) {
dynamic_rendering_extension_present = true;
continue;
}
}
temp_allocator->free_marker( initial_temp_allocator_marker );
}
vkGetPhysicalDeviceProperties( vulkan_physical_device, &vulkan_physical_properties );
gpu_timestamp_frequency = vulkan_physical_properties.limits.timestampPeriod / ( 1000 * 1000 );
rprint( "GPU Used: %s\n", vulkan_physical_properties.deviceName );
ubo_alignment = vulkan_physical_properties.limits.minUniformBufferOffsetAlignment;
ssbo_alignemnt = vulkan_physical_properties.limits.minStorageBufferOffsetAlignment;
// [TAG: BINDLESS]
// Query bindless extension, called Descriptor Indexing (https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VK_EXT_descriptor_indexing.html)
VkPhysicalDeviceDescriptorIndexingFeatures indexing_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES, nullptr };
VkPhysicalDeviceFeatures2 device_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &indexing_features };
vkGetPhysicalDeviceFeatures2( vulkan_physical_device, &device_features );
// For the feature to be correctly working, we need both the possibility to partially bind a descriptor,
// as some entries in the bindless array will be empty, and SpirV runtime descriptors.
bindless_supported = indexing_features.descriptorBindingPartiallyBound && indexing_features.runtimeDescriptorArray;
// TODO: remove when finished with bindless
//bindless_supported = false;
//////// Create logical device
u32 queue_family_count = 0;
vkGetPhysicalDeviceQueueFamilyProperties( vulkan_physical_device, &queue_family_count, nullptr );
VkQueueFamilyProperties* queue_families = ( VkQueueFamilyProperties* )ralloca( sizeof( VkQueueFamilyProperties ) * queue_family_count, temp_allocator );
vkGetPhysicalDeviceQueueFamilyProperties( vulkan_physical_device, &queue_family_count, queue_families );
u32 main_queue_index = u32_max, transfer_queue_index = u32_max, compute_queue_index = u32_max, present_queue_index = u32_max;
for ( u32 fi = 0; fi < queue_family_count; ++fi) {
VkQueueFamilyProperties queue_family = queue_families[ fi ];
if ( queue_family.queueCount == 0 ) {
continue;
}
#if defined(_DEBUG)
rprint( "Family %u, flags %u queue count %u\n", fi, queue_family.queueFlags, queue_family.queueCount );
#endif // DEBUG
// Search for main queue that should be able to do all work (graphics, compute and transfer)
if ( (queue_family.queueFlags & ( VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT )) == ( VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT ) ) {
main_queue_index = fi;
}
// Search for transfer queue
if ( ( queue_family.queueFlags & VK_QUEUE_COMPUTE_BIT ) == 0 && (queue_family.queueFlags & VK_QUEUE_TRANSFER_BIT) ) {
transfer_queue_index = fi;
}
}
// Cache family indices
vulkan_main_queue_family = main_queue_index;
vulkan_transfer_queue_family = transfer_queue_index;
Array<const char*> device_extensions;
device_extensions.init( allocator, 2 );
device_extensions.push( VK_KHR_SWAPCHAIN_EXTENSION_NAME );
if ( dynamic_rendering_extension_present ) {
device_extensions.push( VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME );
}
const float queue_priority[] = { 1.0f };
VkDeviceQueueCreateInfo queue_info[ 2 ] = {};
VkDeviceQueueCreateInfo& main_queue = queue_info[ 0 ];
main_queue.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
main_queue.queueFamilyIndex = main_queue_index;
main_queue.queueCount = 1;
main_queue.pQueuePriorities = queue_priority;
if ( vulkan_transfer_queue_family < queue_family_count ) {
VkDeviceQueueCreateInfo& transfer_queue_info = queue_info[ 1 ];
transfer_queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
transfer_queue_info.queueFamilyIndex = transfer_queue_index;
transfer_queue_info.queueCount = 1;
transfer_queue_info.pQueuePriorities = queue_priority;
}
// Enable all features: just pass the physical features 2 struct.
VkPhysicalDeviceFeatures2 physical_features2 { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 };
VkPhysicalDeviceDynamicRenderingFeaturesKHR dynamic_rendering_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR };
if ( dynamic_rendering_extension_present ) {
physical_features2.pNext = &dynamic_rendering_features;
}
vkGetPhysicalDeviceFeatures2( vulkan_physical_device, &physical_features2 );
VkDeviceCreateInfo device_create_info { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
device_create_info.queueCreateInfoCount = vulkan_transfer_queue_family < queue_family_count ? 2 : 1;
device_create_info.pQueueCreateInfos = queue_info;
device_create_info.enabledExtensionCount = device_extensions.size;
device_create_info.ppEnabledExtensionNames = device_extensions.data;
device_create_info.pNext = &physical_features2;
// [TAG: BINDLESS]
// We also add the bindless needed feature on the device creation.
if ( bindless_supported ) {
indexing_features.descriptorBindingPartiallyBound = VK_TRUE;
indexing_features.runtimeDescriptorArray = VK_TRUE;
// TODO(marco): more generic chaining
if ( dynamic_rendering_extension_present ) {
dynamic_rendering_features.pNext = &indexing_features;
} else {
physical_features2.pNext = &indexing_features;
}
}
result = vkCreateDevice( vulkan_physical_device, &device_create_info, vulkan_allocation_callbacks, &vulkan_device );
check( result );
device_extensions.shutdown();
// Get the function pointers to Debug Utils functions.
if ( debug_utils_extension_present ) {
pfnSetDebugUtilsObjectNameEXT = ( PFN_vkSetDebugUtilsObjectNameEXT )vkGetDeviceProcAddr( vulkan_device, "vkSetDebugUtilsObjectNameEXT" );
pfnCmdBeginDebugUtilsLabelEXT = ( PFN_vkCmdBeginDebugUtilsLabelEXT )vkGetDeviceProcAddr( vulkan_device, "vkCmdBeginDebugUtilsLabelEXT" );
pfnCmdEndDebugUtilsLabelEXT = ( PFN_vkCmdEndDebugUtilsLabelEXT )vkGetDeviceProcAddr( vulkan_device, "vkCmdEndDebugUtilsLabelEXT" );
}
if ( dynamic_rendering_extension_present ) {
cmd_begin_rendering = ( PFN_vkCmdBeginRenderingKHR )vkGetDeviceProcAddr( vulkan_device, "vkCmdBeginRenderingKHR" );
cmd_end_rendering = (PFN_vkCmdEndRenderingKHR)vkGetDeviceProcAddr( vulkan_device, "vkCmdEndRenderingKHR" );
}
// Get main queue
vkGetDeviceQueue( vulkan_device, main_queue_index, 0, &vulkan_main_queue );
// Get transfer queue if present
if ( vulkan_transfer_queue_family < queue_family_count ) {
vkGetDeviceQueue( vulkan_device, transfer_queue_index, 0, &vulkan_transfer_queue );
}
// Create Framebuffers
int window_width, window_height;
SDL_GetWindowSize( window, &window_width, &window_height );
//// Select Surface Format
//const TextureFormat::Enum swapchain_formats[] = { TextureFormat::B8G8R8A8_UNORM, TextureFormat::R8G8B8A8_UNORM, TextureFormat::B8G8R8X8_UNORM, TextureFormat::B8G8R8X8_UNORM };
const VkFormat surface_image_formats[] = { VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM };
const VkColorSpaceKHR surface_color_space = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
u32 supported_count;
vkGetPhysicalDeviceSurfaceFormatsKHR( vulkan_physical_device, vulkan_window_surface, &supported_count, NULL );
VkSurfaceFormatKHR* supported_formats = ( VkSurfaceFormatKHR* )ralloca( sizeof( VkSurfaceFormatKHR ) * supported_count, temp_allocator );
vkGetPhysicalDeviceSurfaceFormatsKHR( vulkan_physical_device, vulkan_window_surface, &supported_count, supported_formats );
// Cache render pass output
swapchain_output.reset();
//// Check for supported formats
bool format_found = false;
const u32 surface_format_count = ArraySize( surface_image_formats );
for ( int i = 0; i < surface_format_count; i++ ) {
for ( u32 j = 0; j < supported_count; j++ ) {
if ( supported_formats[ j ].format == surface_image_formats[ i ] && supported_formats[ j ].colorSpace == surface_color_space ) {
vulkan_surface_format = supported_formats[ j ];
format_found = true;
break;
}
}
if ( format_found )
break;
}
swapchain_output.depth( VK_FORMAT_D32_SFLOAT, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL );
swapchain_output.set_depth_stencil_operations( RenderPassOperation::Clear, RenderPassOperation::Clear );
// Default to the first format supported.
if ( !format_found ) {
vulkan_surface_format = supported_formats[ 0 ];
RASSERT( false );
}
// Final use of temp allocator, free all temporary memory created here.
temp_allocator->free_marker( initial_temp_allocator_marker );
swapchain_output.color( vulkan_surface_format.format, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, RenderPassOperation::Clear );
set_present_mode( present_mode );
//////// Create VMA Allocator
VmaAllocatorCreateInfo allocatorInfo = {};
allocatorInfo.physicalDevice = vulkan_physical_device;
allocatorInfo.device = vulkan_device;
allocatorInfo.instance = vulkan_instance;
result = vmaCreateAllocator( &allocatorInfo, &vma_allocator );
check( result );
//////// Create Descriptor Pools
static const u32 k_global_pool_elements = 128;
VkDescriptorPoolSize pool_sizes[] =
{
{ VK_DESCRIPTOR_TYPE_SAMPLER, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, k_global_pool_elements },
{ VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, k_global_pool_elements}
};
VkDescriptorPoolCreateInfo pool_info = {};
pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
pool_info.maxSets = k_descriptor_sets_pool_size;
pool_info.poolSizeCount = ( u32 )ArraySize( pool_sizes );
pool_info.pPoolSizes = pool_sizes;
result = vkCreateDescriptorPool( vulkan_device, &pool_info, vulkan_allocation_callbacks, &vulkan_descriptor_pool );
check( result );
// [TAG: BINDLESS]
// Create the Descriptor Pool used by bindless, that needs update after bind flag.
if ( bindless_supported ) {
VkDescriptorPoolSize pool_sizes_bindless[] =
{
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, k_max_bindless_resources },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, k_max_bindless_resources },
};
// Update after bind is needed here, for each binding and in the descriptor set layout creation.
pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT;
pool_info.maxSets = k_max_bindless_resources * ArraySize( pool_sizes_bindless );
pool_info.poolSizeCount = ( u32 )ArraySize( pool_sizes_bindless );
pool_info.pPoolSizes = pool_sizes_bindless;
result = vkCreateDescriptorPool( vulkan_device, &pool_info, vulkan_allocation_callbacks, &vulkan_bindless_descriptor_pool);
check( result );
}
// Create timestamp query pool used for GPU timings.
VkQueryPoolCreateInfo vqpci{ VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, nullptr, 0, VK_QUERY_TYPE_TIMESTAMP, creation.gpu_time_queries_per_frame * 2u * k_max_frames, 0 };
vkCreateQueryPool( vulkan_device, &vqpci, vulkan_allocation_callbacks, &vulkan_timestamp_query_pool );
//// Init pools
buffers.init( allocator, k_buffers_pool_size, sizeof( Buffer ) );
textures.init( allocator, k_textures_pool_size, sizeof( Texture ) );
render_passes.init( allocator, k_render_passes_pool_size, sizeof( RenderPass ) );
framebuffers.init( allocator, 256, sizeof( RenderPass ) );
descriptor_set_layouts.init( allocator, k_descriptor_set_layouts_pool_size, sizeof( DescriptorSetLayout ) );
pipelines.init( allocator, k_pipelines_pool_size, sizeof( Pipeline ) );
shaders.init( allocator, k_shaders_pool_size, sizeof( ShaderState ) );
descriptor_sets.init( allocator, k_descriptor_sets_pool_size, sizeof( DescriptorSet ) );
samplers.init( allocator, k_samplers_pool_size, sizeof( Sampler ) );
//command_buffers.init( allocator, 128, sizeof( CommandBuffer ) );
// Init render frame informations. This includes fences, semaphores, command buffers, ...
// TODO: memory - allocate memory of all Device render frame stuff
u8* memory = rallocam( sizeof( GPUTimestampManager ) + sizeof( CommandBuffer* ) * 128, allocator );
VkSemaphoreCreateInfo semaphore_info{ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
vkCreateSemaphore( vulkan_device, &semaphore_info, vulkan_allocation_callbacks, &vulkan_image_acquired_semaphore );
for ( size_t i = 0; i < k_max_swapchain_images; i++ ) {
vkCreateSemaphore( vulkan_device, &semaphore_info, vulkan_allocation_callbacks, &vulkan_render_complete_semaphore[ i ] );
VkFenceCreateInfo fenceInfo{ VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
vkCreateFence( vulkan_device, &fenceInfo, vulkan_allocation_callbacks, &vulkan_command_buffer_executed_fence[ i ] );
}
gpu_timestamp_manager = ( GPUTimestampManager* )( memory );
gpu_timestamp_manager->init( allocator, creation.gpu_time_queries_per_frame, k_max_frames );
command_buffer_ring.init( this, creation.num_threads );
// Allocate queued command buffers array
queued_command_buffers = ( CommandBuffer** )( gpu_timestamp_manager + 1 );
CommandBuffer** correctly_allocated_buffer = ( CommandBuffer** )( memory + sizeof( GPUTimestampManager ) );
RASSERTM( queued_command_buffers == correctly_allocated_buffer, "Wrong calculations for queued command buffers arrays. Should be %p, but it is %p.", correctly_allocated_buffer, queued_command_buffers );
vulkan_image_index = 0;
current_frame = 1;
previous_frame = 0;
absolute_frame = 0;
timestamps_enabled = false;
resource_deletion_queue.init( allocator, 16 );
descriptor_set_updates.init( allocator, 16 );
texture_to_update_bindless.init( allocator, 16 );
// Init render pass cache
render_pass_cache.init( allocator, 16 );
//////// Create swapchain
create_swapchain();
//
// Init primitive resources
//
SamplerCreation sc{};
sc.set_address_mode_uvw( VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE )
.set_min_mag_mip( VK_FILTER_LINEAR, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_LINEAR ).set_name( "Sampler Default" );
default_sampler = create_sampler( sc );
u32 fullscreen_size = 3 * 3 * sizeof( float );
BufferCreation fullscreen_vb_creation = { VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, ResourceUsageType::Immutable, fullscreen_size, 1, 0, nullptr, "Fullscreen_vb" };
fullscreen_vertex_buffer = create_buffer( fullscreen_vb_creation );
// Init Dummy resources
TextureCreation dummy_texture_creation = { nullptr, 1, 1, 1, 1, 0, VK_FORMAT_R8_UINT, TextureType::Texture2D };
dummy_texture = create_texture( dummy_texture_creation );
BufferCreation dummy_constant_buffer_creation = { VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, ResourceUsageType::Immutable, 16, 0, 0, nullptr, "Dummy_cb" };
dummy_constant_buffer = create_buffer( dummy_constant_buffer_creation );
// Get binaries path
#if defined(_MSC_VER)
char* vulkan_env = string_buffer.reserve( 512 );
ExpandEnvironmentStringsA( "%VULKAN_SDK%", vulkan_env, 512 );
char* compiler_path = string_buffer.append_use_f( "%s\\Bin\\", vulkan_env );
#else
char* vulkan_env = getenv ("VULKAN_SDK");
char* compiler_path = string_buffer.append_use_f( "%s/bin/", vulkan_env );
#endif
strcpy( vulkan_binaries_path, compiler_path );
string_buffer.clear();
// [TAG: BINDLESS]
// Bindless resources creation
if ( bindless_supported ) {
DescriptorSetLayoutCreation bindless_layout_creation;
bindless_layout_creation.reset().add_binding( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, k_bindless_texture_binding, k_max_bindless_resources, "BindlessTextures" )
.add_binding( VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, k_bindless_texture_binding + 1, k_max_bindless_resources, "BindlessImages" ).set_set_index( 0 )
.set_name( "BindlessLayout" );
bindless_layout_creation.bindless = true;
bindless_descriptor_set_layout = create_descriptor_set_layout( bindless_layout_creation );
DescriptorSetCreation bindless_set_creation;
bindless_set_creation.reset().set_layout( bindless_descriptor_set_layout );// .texture( dummy_texture, 0 ).texture( dummy_texture, 1 );
bindless_descriptor_set = create_descriptor_set( bindless_set_creation );
DescriptorSet* bindless_set = access_descriptor_set( bindless_descriptor_set );
vulkan_bindless_descriptor_set_cached = bindless_set->vk_descriptor_set;
}
// Dynamic buffer handling
// TODO:
dynamic_per_frame_size = 1024 * 1024 * 10;
BufferCreation bc;
bc.set( VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, ResourceUsageType::Immutable, dynamic_per_frame_size * k_max_frames ).set_name( "Dynamic_Persistent_Buffer" );
dynamic_buffer = create_buffer( bc );
MapBufferParameters cb_map = { dynamic_buffer, 0, 0 };
dynamic_mapped_memory = ( u8* )map_buffer( cb_map );
}
void GpuDevice::shutdown() {
vkDeviceWaitIdle( vulkan_device );
command_buffer_ring.shutdown();
for ( size_t i = 0; i < k_max_swapchain_images; i++ ) {
vkDestroySemaphore( vulkan_device, vulkan_render_complete_semaphore[ i ], vulkan_allocation_callbacks );
vkDestroyFence( vulkan_device, vulkan_command_buffer_executed_fence[ i ], vulkan_allocation_callbacks );
}
vkDestroySemaphore( vulkan_device, vulkan_image_acquired_semaphore, vulkan_allocation_callbacks );
gpu_timestamp_manager->shutdown();
MapBufferParameters cb_map = { dynamic_buffer, 0, 0 };
unmap_buffer( cb_map );
// Memory: this contains allocations for gpu timestamp memory, queued command buffers and render frames.
rfree( gpu_timestamp_manager, allocator );
destroy_descriptor_set_layout( bindless_descriptor_set_layout );
destroy_descriptor_set( bindless_descriptor_set );
destroy_buffer( fullscreen_vertex_buffer );
destroy_buffer( dynamic_buffer );
destroy_render_pass( swapchain_render_pass );
destroy_texture( dummy_texture );
destroy_buffer( dummy_constant_buffer );
destroy_sampler( default_sampler );
// Destroy all pending resources.
for ( u32 i = 0; i < resource_deletion_queue.size; i++ ) {
ResourceUpdate& resource_deletion = resource_deletion_queue[ i ];
// Skip just freed resources.
if ( resource_deletion.current_frame == -1 )
continue;
switch ( resource_deletion.type ) {
case ResourceUpdateType::Buffer:
{
destroy_buffer_instant( resource_deletion.handle );
break;
}
case ResourceUpdateType::Pipeline:
{
destroy_pipeline_instant( resource_deletion.handle );
break;
}
case ResourceUpdateType::RenderPass:
{
destroy_render_pass_instant( resource_deletion.handle );
break;
}
case ResourceUpdateType::DescriptorSet:
{
destroy_descriptor_set_instant( resource_deletion.handle );
break;
}
case ResourceUpdateType::DescriptorSetLayout:
{
destroy_descriptor_set_layout_instant( resource_deletion.handle );
break;
}
case ResourceUpdateType::Sampler:
{
destroy_sampler_instant( resource_deletion.handle );
break;
}
case ResourceUpdateType::ShaderState:
{
destroy_shader_state_instant( resource_deletion.handle );
break;
}
case ResourceUpdateType::Texture:
{
destroy_texture_instant( resource_deletion.handle );
break;
}
case ResourceUpdateType::Framebuffer:
{
destroy_framebuffer_instant( resource_deletion.handle );
break;
}
default:
{
RASSERTM( false, "Cannot process resource type %u\n", resource_deletion.type );
break;
}
}
}
// Destroy render passes from the cache.
// Swapchain vkRenderPass is also present.
if ( !dynamic_rendering_extension_present ) {
FlatHashMapIterator it = render_pass_cache.iterator_begin();
while ( it.is_valid() ) {
VkRenderPass vk_render_pass = render_pass_cache.get( it );
vkDestroyRenderPass( vulkan_device, vk_render_pass, vulkan_allocation_callbacks );
render_pass_cache.iterator_advance( it );
}
}
render_pass_cache.shutdown();
// Destroy swapchain
destroy_swapchain();
vkDestroySurfaceKHR( vulkan_instance, vulkan_window_surface, vulkan_allocation_callbacks );
vmaDestroyAllocator( vma_allocator );
texture_to_update_bindless.shutdown();
resource_deletion_queue.shutdown();
descriptor_set_updates.shutdown();
//command_buffers.shutdown();
pipelines.shutdown();
buffers.shutdown();
shaders.shutdown();
textures.shutdown();
samplers.shutdown();
descriptor_set_layouts.shutdown();
descriptor_sets.shutdown();
render_passes.shutdown();
framebuffers.shutdown();
#ifdef VULKAN_DEBUG_REPORT
// Remove the debug report callback
auto vkDestroyDebugUtilsMessengerEXT = ( PFN_vkDestroyDebugUtilsMessengerEXT )vkGetInstanceProcAddr( vulkan_instance, "vkDestroyDebugUtilsMessengerEXT" );
vkDestroyDebugUtilsMessengerEXT( vulkan_instance, vulkan_debug_utils_messenger, vulkan_allocation_callbacks );
#endif // IMGUI_VULKAN_DEBUG_REPORT
// [TAG: BINDLESS]
if ( bindless_supported ) {
vkDestroyDescriptorPool( vulkan_device, vulkan_bindless_descriptor_pool, vulkan_allocation_callbacks );
}
vkDestroyDescriptorPool( vulkan_device, vulkan_descriptor_pool, vulkan_allocation_callbacks );
vkDestroyQueryPool( vulkan_device, vulkan_timestamp_query_pool, vulkan_allocation_callbacks );
vkDestroyDevice( vulkan_device, vulkan_allocation_callbacks );
vkDestroyInstance( vulkan_instance, vulkan_allocation_callbacks );
string_buffer.shutdown();
rprint( "Gpu Device shutdown\n" );
}
// Resource Creation ////////////////////////////////////////////////////////////
static void vulkan_create_texture( GpuDevice& gpu, const TextureCreation& creation, TextureHandle handle, Texture* texture ) {
texture->width = creation.width;
texture->height = creation.height;
texture->depth = creation.depth;
texture->mipmaps = creation.mipmaps;
texture->type = creation.type;
texture->name = creation.name;
texture->vk_format = creation.format;
texture->sampler = nullptr;
texture->flags = creation.flags;
texture->handle = handle;
//// Create the image
VkImageCreateInfo image_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
image_info.format = texture->vk_format;
image_info.flags = 0;
image_info.imageType = to_vk_image_type( creation.type );
image_info.extent.width = creation.width;
image_info.extent.height = creation.height;
image_info.extent.depth = creation.depth;
image_info.mipLevels = creation.mipmaps;
image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
const bool is_render_target = ( creation.flags & TextureFlags::RenderTarget_mask ) == TextureFlags::RenderTarget_mask;
const bool is_compute_used = ( creation.flags & TextureFlags::Compute_mask ) == TextureFlags::Compute_mask;
// Default to always readable from shader.
image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
image_info.usage |= is_compute_used ? VK_IMAGE_USAGE_STORAGE_BIT : 0;
if ( TextureFormat::has_depth_or_stencil( creation.format ) ) {
// Depth/Stencil textures are normally textures you render into.
image_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
} else {
image_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; // TODO
image_info.usage |= is_render_target ? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT : 0;
}
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VmaAllocationCreateInfo memory_info{};
memory_info.usage = VMA_MEMORY_USAGE_GPU_ONLY;
if ( creation.alias.index == k_invalid_texture.index ) {
check( vmaCreateImage( gpu.vma_allocator, &image_info, &memory_info,
&texture->vk_image, &texture->vma_allocation, nullptr ) );
#if defined (_DEBUG)
vmaSetAllocationName( gpu.vma_allocator, texture->vma_allocation, creation.name );
#endif // _DEBUG
} else {
Texture* alias_texture = gpu.access_texture( creation.alias );
RASSERT( alias_texture != nullptr );
texture->vma_allocation = 0;
check( vmaCreateAliasingImage( gpu.vma_allocator, alias_texture->vma_allocation, &image_info, &texture->vk_image ) );
}
gpu.set_resource_name( VK_OBJECT_TYPE_IMAGE, ( u64 )texture->vk_image, creation.name );
//// Create the image view
VkImageViewCreateInfo info = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
info.image = texture->vk_image;
info.viewType = to_vk_image_view_type( creation.type );
info.format = image_info.format;
if ( TextureFormat::has_depth_or_stencil( creation.format ) ) {
info.subresourceRange.aspectMask = TextureFormat::has_depth( creation.format ) ? VK_IMAGE_ASPECT_DEPTH_BIT : 0;
// TODO:gs
//info.subresourceRange.aspectMask |= TextureFormat::has_stencil( creation.format ) ? VK_IMAGE_ASPECT_STENCIL_BIT : 0;
} else {
info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
}
info.subresourceRange.levelCount = creation.mipmaps;
info.subresourceRange.layerCount = 1;
check( vkCreateImageView( gpu.vulkan_device, &info, gpu.vulkan_allocation_callbacks, &texture->vk_image_view ) );
gpu.set_resource_name( VK_OBJECT_TYPE_IMAGE_VIEW, ( u64 )texture->vk_image_view, creation.name );
texture->vk_image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
// Add deferred bindless update.
if ( gpu.bindless_supported ) {
ResourceUpdate resource_update{ ResourceUpdateType::Texture, texture->handle.index, gpu.current_frame, 0 };
gpu.texture_to_update_bindless.push( resource_update );
}
}
static void upload_texture_data( Texture* texture, void* upload_data, GpuDevice& gpu ) {
// Create stating buffer
VkBufferCreateInfo buffer_info{ VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
u32 image_size = texture->width * texture->height * 4;
buffer_info.size = image_size;
VmaAllocationCreateInfo memory_info{};
memory_info.flags = VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT;
memory_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
VmaAllocationInfo allocation_info{};
VkBuffer staging_buffer;
VmaAllocation staging_allocation;
( vmaCreateBuffer( gpu.vma_allocator, &buffer_info, &memory_info,
&staging_buffer, &staging_allocation, &allocation_info ) );
// Copy buffer_data
void* destination_data;
vmaMapMemory( gpu.vma_allocator, staging_allocation, &destination_data );
memcpy( destination_data, upload_data, static_cast< size_t >( image_size ) );
vmaUnmapMemory( gpu.vma_allocator, staging_allocation );
// Execute command buffer
VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// TODO: threading
CommandBuffer* command_buffer = gpu.get_command_buffer( false, 0 );
vkBeginCommandBuffer( command_buffer->vk_command_buffer, &beginInfo );
VkBufferImageCopy region = {};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = { texture->width, texture->height, texture->depth };
// Copy from the staging buffer to the image
util_add_image_barrier( command_buffer->vk_command_buffer, texture->vk_image, RESOURCE_STATE_UNDEFINED, RESOURCE_STATE_COPY_DEST, 0, 1, false );
vkCmdCopyBufferToImage( command_buffer->vk_command_buffer, staging_buffer, texture->vk_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion );
// Prepare first mip to create lower mipmaps
if ( texture->mipmaps > 1 ) {
util_add_image_barrier( command_buffer->vk_command_buffer, texture->vk_image, RESOURCE_STATE_COPY_DEST, RESOURCE_STATE_COPY_SOURCE, 0, 1, false );
}
i32 w = texture->width;
i32 h = texture->height;
for ( int mip_index = 1; mip_index < texture->mipmaps; ++mip_index ) {
util_add_image_barrier( command_buffer->vk_command_buffer, texture->vk_image, RESOURCE_STATE_UNDEFINED, RESOURCE_STATE_COPY_DEST, mip_index, 1, false );
VkImageBlit blit_region{ };
blit_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit_region.srcSubresource.mipLevel = mip_index - 1;
blit_region.srcSubresource.baseArrayLayer = 0;
blit_region.srcSubresource.layerCount = 1;
blit_region.srcOffsets[ 0 ] = { 0, 0, 0 };