-
-
Notifications
You must be signed in to change notification settings - Fork 516
/
gfx_api_vk.cpp
6036 lines (5362 loc) · 226 KB
/
gfx_api_vk.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
/*
This file is part of Warzone 2100.
Copyright (C) 2017-2022 Warzone 2100 Project
Warzone 2100 is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Warzone 2100 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(WZ_VULKAN_ENABLED)
// General notes for developers:
//
// To maintain compatibility with as many systems as possible:
// 1.) Ensure Vulkan 1.0 compatibility
// 2.) Avoid *requiring* anything outside of the scope of the "Vulkan Portable Subset"
// 3.) All calls to Vulkan APIs should use dynamic dispatch (see the uses of vk::DispatchLoaderDynamic in this file)
// 4.) Test with the Vulkan validation layers enabled (run WZ with --gfxdebug)
//
// #2 means the following things are currently best avoided:
// - Triangle fans
// - Separate stencil reference masks
// - Vulkan Event functionality
// - Texture-specific swizzles
// - Allocation callbacks in object creation functions
//
// When in doubt, consult both:
// - the Vulkan Portability Initiative: https://www.khronos.org/vulkan/portability-initiative
// - MoltenVK limitations: https://github.com/KhronosGroup/MoltenVK/blob/master/Docs/MoltenVK_Runtime_UserGuide.md#known-moltenvk-limitations
//
#include "gfx_api_vk.h"
#include "lib/framework/physfs_ext.h"
#include "lib/framework/wzapp.h"
#include "lib/exceptionhandler/dumpinfo.h"
#include <algorithm>
#include <set>
#include <unordered_set>
#include <map>
#include <limits>
#include <chrono>
#include <thread>
// Fix #define MemoryBarrier coming from winnt.h
#undef MemoryBarrier
#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 9
#pragma GCC diagnostic ignored "-Wdeprecated-copy" // Ignore warnings caused by vulkan.hpp 148
#endif
const uint32_t minSupportedVulkanVersion = VK_API_VERSION_1_0;
#if defined(DEBUG)
// For debug builds, limit to the minimum that should be supported by this backend (which is Vulkan 1.0, see above)
const uint32_t maxRequestableInstanceVulkanVersion = VK_API_VERSION_1_0;
#else
// For regular builds, currently limit to: Vulkan 1.1
const uint32_t maxRequestableInstanceVulkanVersion = (uint32_t)VK_MAKE_VERSION(1, 1, 0);
#endif
const size_t MAX_FRAMES_IN_FLIGHT = 2;
// Vulkan version where extension is promoted to core; extension name
#define VK_NOT_PROMOTED_TO_CORE_YET 0
const std::vector<std::tuple<uint32_t, const char*>> optionalInstanceExtensions = {
{ VK_MAKE_VERSION(1, 1, 0) , VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME }, // used for Vulkan info output
#if defined(VK_KHR_portability_enumeration)
{ VK_NOT_PROMOTED_TO_CORE_YET , VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME}
#endif
};
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
const std::vector<const char*> optionalDeviceExtensions = {
VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,
VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME,
"VK_KHR_portability_subset" // According to VUID-VkDeviceCreateInfo-pProperties-04451, if device supports this extension it *must* be enabled
};
const std::vector<vk::Format> supportedDepthStencilFormats = {
vk::Format::eD32SfloatS8Uint,
vk::Format::eD24UnormS8Uint
};
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
const std::vector<const char*> debugAdditionalExtensions = {
VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
VK_EXT_DEBUG_REPORT_EXTENSION_NAME // old, deprecated extension
};
// See: https://www.khronos.org/registry/vulkan/specs/1.1/html/vkspec.html#fundamentals-validusage-versions
#define VK_VERSION_GREATER_THAN_OR_EQUAL(a, b) \
( ( VK_VERSION_MAJOR(a) > VK_VERSION_MAJOR(b) ) || ( ( VK_VERSION_MAJOR(a) == VK_VERSION_MAJOR(b) ) && ( VK_VERSION_MINOR(a) >= VK_VERSION_MINOR(b) ) ) )
const uint32_t minRequired_DescriptorSetUniformBuffers = 1;
const uint32_t minRequired_DescriptorSetUniformBuffersDynamic = 1;
const uint32_t minRequired_BoundDescriptorSets = 4;
const uint32_t minRequired_Viewports = 1;
const uint32_t minRequired_ColorAttachments = 1;
#if defined(WZ_OS_WIN)
# define _vkl_env_text(x) L##x
# define _vkl_env_text_type std::wstring
void _vk_setenv(const _vkl_env_text_type& name, const _vkl_env_text_type& value)
{
if (SetEnvironmentVariableW(name.c_str(), value.c_str()) == 0)
{
// Failed to set environment variable
DWORD lastError = GetLastError();
debug(LOG_ERROR, "SetEnvironmentVariableW failed with error: %lu", lastError);
}
}
#else
# define _vkl_env_text(x) x
# define _vkl_env_text_type std::string
void _vk_setenv(const _vkl_env_text_type& name, const _vkl_env_text_type& value)
{
# if defined HAVE_SETENV
setenv(name.c_str(), value.c_str(), 1);
# else
# warning "No supported method to set environment variables"
# endif
}
#endif
const std::vector<std::pair<_vkl_env_text_type, _vkl_env_text_type>> vulkan_implicit_layer_environment_variables = {
{_vkl_env_text("DISABLE_VK_LAYER_VALVE_steam_overlay_1"), _vkl_env_text("1")}
, {_vkl_env_text("DISABLE_VK_LAYER_VALVE_steam_fossilize_1"), _vkl_env_text("1")}
, {_vkl_env_text("DISABLE_FPSMON_LAYER"), _vkl_env_text("1")} // avoid crashes caused by this layer
};
#if defined(WZ_DEBUG_GFX_API_LEAKS)
static std::unordered_set<const VkTexture*> debugLiveTextures;
#endif
enum class VulkanBackendInternalTextureType : size_t
{
Invalid = 0,
Texture,
TextureArray,
DepthMap,
RenderedImage
};
// MARK: General helper functions
void SetVKImplicitLayerEnvironmentVariables()
{
for (const auto &it : vulkan_implicit_layer_environment_variables)
{
_vk_setenv(it.first, it.second);
}
}
template <typename VKType, typename F, typename... Args>
std::vector<VKType> GetVectorFromVKFuncWithExplicitInit(F &&func, VKType init, Args &&... args)
{
std::vector<VKType> results;
uint32_t count = 0;
VkResult status;
do {
status = func(args..., &count, nullptr);
if ((status == VK_SUCCESS) && (count > 0))
{
results.resize(count, init);
status = func(args..., &count, results.data());
}
} while (status == VK_INCOMPLETE);
if (status == VK_SUCCESS)
{
ASSERT(count <= results.size(), "Unexpected result: count (%" PRIu32"); results.size (%zu)", count, results.size());
results.resize(count);
}
return results;
}
template <typename VKType, typename F, typename... Args>
std::vector<VKType> GetVectorFromVKFunc(F &&func, Args &&... args)
{
return GetVectorFromVKFuncWithExplicitInit(func, VKType(), args...);
}
static uint32_t findProperties(const vk::PhysicalDeviceMemoryProperties& memprops, const uint32_t& memoryTypeBits, const vk::MemoryPropertyFlagBits& properties, bool *memTypeFound = nullptr)
{
for (uint32_t i = 0; i < memprops.memoryTypeCount; ++i)
{
if ((memoryTypeBits & (1 << i)) &&
((memprops.memoryTypes[i].propertyFlags & properties) == properties))
{
if (memTypeFound)
{
*memTypeFound = true;
}
return i;
}
}
if (memTypeFound)
{
*memTypeFound = false;
}
return -1;
}
[[noreturn]] static void handleUnrecoverableError(const vk::Result& reason)
{
if (reason == vk::Result::eErrorDeviceLost)
{
// FUTURE TODO: Output a bunch more debugging info to the debug log?
}
// Display a message and prompt the user to try a different graphics backend next time
wzPromptToChangeGfxBackendOnFailure("Failed with error: " + vk::to_string(reason));
abort();
}
bool checkFormatSupport(const vk::PhysicalDevice& physicalDevice, vk::Format format, vk::ImageTiling tiling, vk::FormatFeatureFlags features, const vk::DispatchLoaderDynamic& vkDynLoader)
{
vk::FormatProperties props;
physicalDevice.getFormatProperties(format, &props, vkDynLoader);
if (tiling == vk::ImageTiling::eLinear && (props.linearTilingFeatures & features) == features)
{
return true;
}
else if (tiling == vk::ImageTiling::eOptimal && (props.optimalTilingFeatures & features) == features)
{
return true;
}
return false;
}
vk::Format findSupportedFormat(const vk::PhysicalDevice& physicalDevice, const std::vector<vk::Format>& candidates, vk::ImageTiling tiling, vk::FormatFeatureFlags features, const vk::DispatchLoaderDynamic& vkDynLoader) {
for (vk::Format format : candidates)
{
if (checkFormatSupport(physicalDevice, format, tiling, features, vkDynLoader))
{
return format;
}
}
throw std::runtime_error("failed to find supported format!");
}
QueueFamilyIndices findQueueFamilies(const vk::PhysicalDevice &device, const vk::SurfaceKHR &surface, const vk::DispatchLoaderDynamic &vkDynLoader)
{
QueueFamilyIndices indices;
const auto queueFamilies = device.getQueueFamilyProperties(vkDynLoader);
uint32_t i = 0;
for (const auto& queueFamily : queueFamilies)
{
if (queueFamily.queueCount > 0 && (queueFamily.queueFlags & vk::QueueFlagBits::eGraphics))
{
indices.graphicsFamily = i;
}
vk::Bool32 presentSupport = false;
try
{
presentSupport = device.getSurfaceSupportKHR(i, surface, vkDynLoader);
}
catch (const vk::SystemError& e)
{
// getSurfaceSupportKHR failed
debug(LOG_ERROR, "getSurfaceSupportKHR failed: %s", e.what());
}
if (queueFamily.queueCount > 0 && presentSupport)
{
indices.presentFamily = i;
}
if (indices.isComplete())
{
break;
}
i++;
}
return indices;
}
SwapChainSupportDetails querySwapChainSupport(const vk::PhysicalDevice &device, const vk::SurfaceKHR &surface, const vk::DispatchLoaderDynamic &vkDynLoader)
{
SwapChainSupportDetails details;
details.capabilities = device.getSurfaceCapabilitiesKHR(surface, vkDynLoader);
details.formats = device.getSurfaceFormatsKHR(surface, vkDynLoader);
details.presentModes = device.getSurfacePresentModesKHR(surface, vkDynLoader);
return details;
}
std::vector<const char*> findSupportedDeviceExtensions(const vk::PhysicalDevice &device, const std::vector<const char*> &desiredExtensions, const vk::DispatchLoaderDynamic &vkDynLoader)
{
const auto availableExtensions = device.enumerateDeviceExtensionProperties(nullptr, vkDynLoader); // TODO: handle thrown error?
std::unordered_set<std::string> supportedExtensionNames;
for (auto & extension : availableExtensions)
{
supportedExtensionNames.insert(extension.extensionName);
}
std::vector<const char*> foundExtensions;
for (const char* extensionName : desiredExtensions)
{
if(supportedExtensionNames.find(extensionName) != supportedExtensionNames.end())
{
foundExtensions.push_back(extensionName);
}
else
{
debug(LOG_3D, "Vulkan: Did not find device extension: %s", extensionName);
}
}
return foundExtensions;
}
bool checkDeviceExtensionSupport(const vk::PhysicalDevice &device, const std::vector<const char*> &desiredExtensions, const vk::DispatchLoaderDynamic &vkDynLoader)
{
try {
const auto availableExtensions = device.enumerateDeviceExtensionProperties(nullptr, vkDynLoader);
std::unordered_set<std::string> requiredExtensions(desiredExtensions.begin(), desiredExtensions.end());
for (const auto& extension : availableExtensions)
{
requiredExtensions.erase(extension.extensionName);
}
return requiredExtensions.empty();
}
catch (const vk::SystemError& e)
{
debug(LOG_ERROR, "vkEnumerateDeviceExtensionProperties failed with error: %s", e.what());
}
return false;
}
bool VkRoot::getSupportedInstanceExtensions(std::vector<VkExtensionProperties> &output, PFN_vkGetInstanceProcAddr _vkGetInstanceProcAddr)
{
if (!supportedInstanceExtensionProperties.empty())
{
// use cached info
output = supportedInstanceExtensionProperties;
return true;
}
ASSERT_OR_RETURN(false, _vkGetInstanceProcAddr, "_vkGetInstanceProcAddr must be valid");
PFN_vkEnumerateInstanceExtensionProperties _vkEnumerateInstanceExtensionProperties = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(reinterpret_cast<void*>(_vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceExtensionProperties")));
if (!_vkEnumerateInstanceExtensionProperties)
{
debug(LOG_ERROR, "Could not find symbol: vkEnumerateInstanceExtensionProperties\n");
return false;
}
// cache the result in VkRoot instance, to minimize calls to vkEnumerateInstanceExtensionProperties
supportedInstanceExtensionProperties = GetVectorFromVKFunc<VkExtensionProperties>(_vkEnumerateInstanceExtensionProperties, nullptr);
output = supportedInstanceExtensionProperties;
return true;
}
static bool getInstanceLayerProperties(std::vector<VkLayerProperties> &output, PFN_vkGetInstanceProcAddr _vkGetInstanceProcAddr)
{
ASSERT_OR_RETURN(false, _vkGetInstanceProcAddr, "_vkGetInstanceProcAddr must be valid");
PFN_vkEnumerateInstanceLayerProperties _vkEnumerateInstanceLayerProperties = reinterpret_cast<PFN_vkEnumerateInstanceLayerProperties>(reinterpret_cast<void*>(_vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceLayerProperties")));
if (!_vkEnumerateInstanceLayerProperties)
{
debug(LOG_ERROR, "Could not find symbol: vkEnumerateInstanceLayerProperties\n");
return false;
}
output = GetVectorFromVKFunc<VkLayerProperties>(_vkEnumerateInstanceLayerProperties);
return true;
}
vk::SampleCountFlagBits getMaxUsableSampleCount(const vk::PhysicalDeviceProperties &physicalDeviceProperties)
{
VkSampleCountFlags counts = std::min({
static_cast<VkSampleCountFlags>(physicalDeviceProperties.limits.framebufferColorSampleCounts),
static_cast<VkSampleCountFlags>(physicalDeviceProperties.limits.framebufferDepthSampleCounts),
static_cast<VkSampleCountFlags>(physicalDeviceProperties.limits.framebufferStencilSampleCounts)
});
if (counts & VK_SAMPLE_COUNT_64_BIT) { return vk::SampleCountFlagBits::e64; }
if (counts & VK_SAMPLE_COUNT_32_BIT) { return vk::SampleCountFlagBits::e32; }
if (counts & VK_SAMPLE_COUNT_16_BIT) { return vk::SampleCountFlagBits::e16; }
if (counts & VK_SAMPLE_COUNT_8_BIT) { return vk::SampleCountFlagBits::e8; }
if (counts & VK_SAMPLE_COUNT_4_BIT) { return vk::SampleCountFlagBits::e4; }
if (counts & VK_SAMPLE_COUNT_2_BIT) { return vk::SampleCountFlagBits::e2; }
return vk::SampleCountFlagBits::e1;
}
vk::Format findDepthStencilFormat(const vk::PhysicalDevice& physicalDevice, const vk::DispatchLoaderDynamic& vkDynLoader)
{
return findSupportedFormat(
physicalDevice,
supportedDepthStencilFormats,
vk::ImageTiling::eOptimal,
vk::FormatFeatureFlags{vk::FormatFeatureFlagBits::eDepthStencilAttachment},
vkDynLoader
);
}
vk::Format findDepthBufferFormat(const vk::PhysicalDevice& physicalDevice, const vk::DispatchLoaderDynamic& vkDynLoader)
{
std::vector<vk::Format> depthFormats = { vk::Format::eD32SfloatS8Uint, vk::Format::eD32Sfloat, vk::Format::eD24UnormS8Uint };
return findSupportedFormat(
physicalDevice,
depthFormats,
vk::ImageTiling::eOptimal,
vk::FormatFeatureFlags{vk::FormatFeatureFlagBits::eDepthStencilAttachment | vk::FormatFeatureFlagBits::eSampledImage},
vkDynLoader
);
}
bool checkValidationLayerSupport(PFN_vkGetInstanceProcAddr _vkGetInstanceProcAddr)
{
std::vector<VkLayerProperties> availableLayers;
if (!getInstanceLayerProperties(availableLayers, _vkGetInstanceProcAddr))
{
// getInstanceLayerProperties failed
return false;
}
for (const char* layerName : validationLayers)
{
bool layerFound = false;
for (const auto& layerProperties : availableLayers)
{
if (strcmp(layerName, layerProperties.layerName) == 0)
{
layerFound = true;
break;
}
}
if (!layerFound)
{
return false;
}
}
return true;
}
bool VkRoot::findSupportedInstanceExtensions(std::vector<const char*> extensionsToFind, std::vector<const char*> &output, PFN_vkGetInstanceProcAddr _vkGetInstanceProcAddr)
{
std::vector<VkExtensionProperties> supportedExtensions;
if (!getSupportedInstanceExtensions(supportedExtensions, _vkGetInstanceProcAddr))
{
// Failed to get supported extensions
return false;
}
std::unordered_set<std::string> supportedExtensionNames;
for (auto & extension : supportedExtensions)
{
supportedExtensionNames.insert(extension.extensionName);
}
std::vector<const char*> foundExtensions;
for (const char* extensionName : extensionsToFind)
{
if(supportedExtensionNames.find(extensionName) != supportedExtensionNames.end())
{
foundExtensions.push_back(extensionName);
}
else
{
debug(LOG_3D, "Vulkan: Did not find extension: %s", extensionName);
}
}
output = foundExtensions;
return true;
}
// MARK: BlockBufferAllocator
BlockBufferAllocator::BlockBufferAllocator(VmaAllocator allocator, uint32_t minimumBlockSize, const vk::BufferUsageFlags& usageFlags, const VmaAllocationCreateInfo& allocInfo, bool autoMap /* = false */)
: allocator(allocator), minimumBlockSize(minimumBlockSize), usageFlags(usageFlags), allocInfo(allocInfo), autoMap(autoMap)
{ }
BlockBufferAllocator::BlockBufferAllocator(VmaAllocator allocator, uint32_t minimumBlockSize, const vk::BufferUsageFlags& usageFlags, const VmaMemoryUsage usage, bool autoMap /* = false */)
: allocator(allocator), minimumBlockSize(minimumBlockSize), usageFlags(usageFlags), autoMap(autoMap)
{
VmaAllocationCreateInfo tmpAllocInfo = { };
tmpAllocInfo.usage = usage;
allocInfo = tmpAllocInfo;
}
BlockBufferAllocator::~BlockBufferAllocator()
{
if (autoMap)
{
unmapAutomappedMemory();
}
for (auto& block : blocks)
{
ASSERT(block.pMappedMemory == nullptr, "Likely missing a call to unmapAutomappedMemory");
vmaDestroyBuffer(allocator, block.buffer, block.allocation);
}
blocks.clear();
}
std::tuple<uint32_t, uint32_t> BlockBufferAllocator::getWritePosAndNewWriteLocation(uint32_t currentWritePos, uint32_t amount, uint32_t totalSize, uint32_t align)
{
assert(amount < totalSize);
currentWritePos = ((currentWritePos + align - 1) / align) * align;
if (currentWritePos + amount < totalSize)
{
return std::make_tuple(currentWritePos, currentWritePos + amount);
}
return std::make_tuple(0u, amount);
}
void BlockBufferAllocator::allocateNewBlock(uint32_t minimumSize)
{
uint32_t newBlockSize = std::max({minimumSize, (blocks.empty() ? minimumFirstBlockSize : 0), minimumBlockSize, (totalCapacity < static_cast<uint64_t>(std::numeric_limits<uint32_t>::max())) ? static_cast<uint32_t>(totalCapacity) : std::numeric_limits<uint32_t>::max()});
auto bufferCreateInfo = vk::BufferCreateInfo()
.setSize(newBlockSize)
.setUsage(usageFlags);
totalCapacity += newBlockSize;
Block newBlock;
newBlock.size = newBlockSize;
vk::Result result = static_cast<vk::Result>(vmaCreateBuffer(allocator, reinterpret_cast<const VkBufferCreateInfo*>( &bufferCreateInfo ), &allocInfo, reinterpret_cast<VkBuffer*>( &newBlock.buffer ), &newBlock.allocation, nullptr));
if (result != vk::Result::eSuccess)
{
// Failed to allocate memory!
vk::throwResultException( result, "vmaCreateBuffer" );
}
if (autoMap)
{
vmaMapMemory(allocator, newBlock.allocation, &newBlock.pMappedMemory);
}
blocks.push_back(newBlock);
currentWritePosInLastBlock = 0;
}
BlockBufferAllocator::AllocationResult BlockBufferAllocator::alloc(uint32_t amount, uint32_t align)
{
if (!blocks.empty())
{
const uint32_t lastBlockSize = blocks.back().size;
if (amount < lastBlockSize)
{
// attempt to see if this request fits in the remaining size in the last block
uint32_t newWritePos = ((currentWritePosInLastBlock + align - 1) / align) * align;
if (newWritePos + amount < lastBlockSize)
{
currentWritePosInLastBlock = newWritePos + amount;
return BlockBufferAllocator::AllocationResult(blocks.back(), newWritePos);
}
}
}
// otherwise, allocate a new block
allocateNewBlock(amount);
uint32_t newWritePos = 0;
ASSERT(newWritePos + amount <= blocks.back().size, "Failed to allocate new block");
currentWritePosInLastBlock = newWritePos + amount;
return BlockBufferAllocator::AllocationResult(blocks.back(), newWritePos);
}
void * BlockBufferAllocator::mapMemory(AllocationResult memoryAllocation)
{
void* mappedData = nullptr;
if (memoryAllocation.block.pMappedMemory)
{
mappedData = memoryAllocation.block.pMappedMemory;
}
else
{
vmaMapMemory(allocator, memoryAllocation.block.allocation, &mappedData);
}
if (memoryAllocation.offset > 0)
{
return reinterpret_cast<uint8_t*>(mappedData) + memoryAllocation.offset;
}
else
{
return mappedData;
}
}
void BlockBufferAllocator::unmapMemory(AllocationResult memoryAllocation)
{
if (memoryAllocation.block.pMappedMemory)
{
// no-op - call unmapAutomappedMemory instead
return;
}
vmaUnmapMemory(allocator, memoryAllocation.block.allocation);
}
void BlockBufferAllocator::unmapAutomappedMemory()
{
ASSERT(autoMap, "Only useful when autoMap == true");
for (auto& block : blocks)
{
if (block.pMappedMemory)
{
vmaUnmapMemory(allocator, block.allocation);
block.pMappedMemory = nullptr;
}
}
}
void BlockBufferAllocator::flushAutomappedMemory()
{
ASSERT(autoMap, "Only useful when autoMap == true");
for (auto& block : blocks)
{
ASSERT(block.pMappedMemory != nullptr, "Block must still be (auto-)mapped");
vmaFlushAllocation(allocator, block.allocation, 0, VK_WHOLE_SIZE);
}
}
void BlockBufferAllocator::clean()
{
uint64_t totalMemoryAllocated = 0;
uint64_t totalMemoryUsed = 0;
for (auto& block : blocks)
{
totalMemoryAllocated += static_cast<uint64_t>(block.size);
}
if (!blocks.empty())
{
totalMemoryUsed = totalMemoryAllocated - (blocks.back().size - currentWritePosInLastBlock);
}
uint32_t old_minimumFirstBlockSize = minimumFirstBlockSize;
if (blocks.size() > 1)
{
minimumFirstBlockSize = totalMemoryAllocated;
}
else if (totalMemoryUsed < (minimumFirstBlockSize / 4))
{
minimumFirstBlockSize = minimumFirstBlockSize / 2;
}
if ((old_minimumFirstBlockSize != minimumFirstBlockSize) && (minimumFirstBlockSize > minimumBlockSize))
{
// free all existing blocks
for (auto& block : blocks)
{
ASSERT(block.pMappedMemory == nullptr, "Likely missing a call to unmapAutomappedMemory");
vmaDestroyBuffer(allocator, block.buffer, block.allocation);
}
blocks.clear();
}
ASSERT(blocks.size() <= 1, "Should either be 0 or 1 retained block");
if (autoMap)
{
// re-map blocks that were retained
for (auto& block : blocks)
{
if (block.pMappedMemory == nullptr)
{
vmaMapMemory(allocator, block.allocation, &block.pMappedMemory);
}
}
}
currentWritePosInLastBlock = 0;
totalCapacity = (!blocks.empty()) ? blocks.back().size : 0;
}
// MARK: perFrameResources_t
constexpr uint32_t descriptorPoolMaxSetsDefault = 10000;
constexpr uint32_t descriptorPoolSizeDescriptorCountDefault = 10000;
perFrameResources_t::perFrameResources_t(vk::Device& _dev, const VmaAllocator& allocator, const uint32_t& graphicsQueueFamilyIndex, const vk::DispatchLoaderDynamic& vkDynLoader)
: dev(_dev)
, allocator(allocator)
, stagingBufferAllocator(allocator, 1024 * 1024, vk::BufferUsageFlagBits::eTransferSrc, VMA_MEMORY_USAGE_CPU_ONLY)
, streamedVertexBufferAllocator(allocator, 128 * 1024, vk::BufferUsageFlagBits::eVertexBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU, true)
, uniformBufferAllocator(allocator, 1024 * 1024, vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU, true)
, pVkDynLoader(&vkDynLoader)
{
combinedImageSamplerDescriptorPools.push_back(createNewDescriptorPool(vk::DescriptorType::eCombinedImageSampler, descriptorPoolMaxSetsDefault, descriptorPoolSizeDescriptorCountDefault));
uniformDynamicDescriptorPools.push_back(createNewDescriptorPool(vk::DescriptorType::eUniformBufferDynamic, descriptorPoolMaxSetsDefault, descriptorPoolSizeDescriptorCountDefault));
pool = dev.createCommandPool(
vk::CommandPoolCreateInfo()
.setQueueFamilyIndex(graphicsQueueFamilyIndex)
.setFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer)
, nullptr, *pVkDynLoader
);
const auto buffer = dev.allocateCommandBuffers(
vk::CommandBufferAllocateInfo()
.setCommandPool(pool)
.setCommandBufferCount(4)
.setLevel(vk::CommandBufferLevel::ePrimary)
, *pVkDynLoader
);
cmdDraw = buffer[0];
cmdCopy = buffer[1];
cmdDrawDepth = buffer[2];
cmdDrawScene = buffer[3];
pCurrentDrawCmdBuffer = &cmdDraw;
cmdCopy.begin(vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit), vkDynLoader);
cmdDrawDepth.begin(vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit), vkDynLoader);
cmdDrawScene.begin(vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit), vkDynLoader);
previousSubmission = dev.createFence(
vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled),
nullptr, *pVkDynLoader
);
}
perFrameResources_t::DescriptorPoolDetails perFrameResources_t::createNewDescriptorPool(vk::DescriptorType type, uint32_t maxSets, uint32_t descriptorCount)
{
vk::DescriptorPoolSize poolSize(type, descriptorCount);
return DescriptorPoolDetails(dev.createDescriptorPool(vk::DescriptorPoolCreateInfo()
.setMaxSets(maxSets)
.setPPoolSizes(&poolSize)
.setPoolSizeCount(1)
, nullptr, *pVkDynLoader
), poolSize, maxSets);
}
void perFrameResources_t::beginDepthPass()
{
pCurrentDrawCmdBuffer = &cmdDrawDepth;
}
void perFrameResources_t::endCurrentDepthPass()
{
pCurrentDrawCmdBuffer = &cmdDraw;
}
void perFrameResources_t::beginScenePass()
{
pCurrentDrawCmdBuffer = &cmdDrawScene;
}
void perFrameResources_t::endScenePass()
{
pCurrentDrawCmdBuffer = &cmdDraw;
}
vk::CommandBuffer* perFrameResources_t::currentCopyCmdBuffer()
{
return &cmdCopy;
}
vk::CommandBuffer* perFrameResources_t::currentDrawCmdBuffer()
{
return pCurrentDrawCmdBuffer;
}
vk::CommandBuffer perFrameResources_t::copyCmdBuffer()
{
return cmdCopy;
}
vk::CommandBuffer perFrameResources_t::depthPassDrawCmdBuffer()
{
return cmdDrawDepth;
}
vk::CommandBuffer perFrameResources_t::scenePassDrawCmdBuffer()
{
return cmdDrawScene;
}
vk::CommandBuffer perFrameResources_t::renderPassDrawCmdBuffer()
{
return cmdDraw;
}
vk::DescriptorPool perFrameResources_t::getDescriptorPool(uint32_t numSets, vk::DescriptorType descriptorType, uint32_t numDescriptors)
{
// Take into account numSets, descriptorType and numDescriptors to return a descriptorPool (allocating a new one if needed)
DescriptorPoolsContainer* pPools = nullptr;
switch (descriptorType)
{
case vk::DescriptorType::eCombinedImageSampler:
pPools = &combinedImageSamplerDescriptorPools;
break;
case vk::DescriptorType::eUniformBufferDynamic:
pPools = &uniformDynamicDescriptorPools;
break;
default:
debug(LOG_FATAL, "Invalid descriptor type: %s", vk::to_string(descriptorType).c_str());
return vk::DescriptorPool();
}
DescriptorPoolDetails* pCurrPool = &pPools->current();
if ((pCurrPool->maxSets - pCurrPool->requestedSets < numSets)
|| (pCurrPool->size.descriptorCount - pCurrPool->requestedDescriptors < numDescriptors))
{
// not enough room in the current descriptor pool for this request
if (!pPools->nextPool())
{
// No more existing pools - need to create a new one
debug(LOG_INFO, "[%p] Creating new [%zu] descriptor pool of type: %s", (void*)this, pPools->currPool + 1, vk::to_string(descriptorType).c_str());
pPools->push_back(createNewDescriptorPool(descriptorType, descriptorPoolMaxSetsDefault, descriptorPoolSizeDescriptorCountDefault));
pPools->nextPool();
}
pCurrPool = &pPools->current();
}
pCurrPool->requestedSets += numSets;
pCurrPool->requestedDescriptors += numDescriptors;
return pCurrPool->poolHandle;
}
void perFrameResources_t::clean()
{
stagingBufferAllocator.clean();
streamedVertexBufferAllocator.clean();
uniformBufferAllocator.clean();
for (auto fbo : fbo_to_delete)
{
dev.destroyFramebuffer(fbo, nullptr, *pVkDynLoader);
}
fbo_to_delete.clear();
for (auto buffer : buffer_to_delete)
{
dev.destroyBuffer(buffer, nullptr, *pVkDynLoader);
}
buffer_to_delete.clear();
image_view_to_delete.clear();
for (auto image : image_to_delete)
{
dev.destroyImage(image, nullptr, *pVkDynLoader);
}
image_to_delete.clear();
perPSO_dynamicUniformBufferDescriptorSets.clear();
for (auto allocation : vmamemory_to_free)
{
vmaFreeMemory(allocator, allocation);
}
vmamemory_to_free.clear();
for (auto old_pso : pso_to_delete)
{
delete old_pso;
}
pso_to_delete.clear();
}
perFrameResources_t::~perFrameResources_t()
{
dev.destroyCommandPool(pool, nullptr, *pVkDynLoader);
for (const auto& descriptorPoolDetails : combinedImageSamplerDescriptorPools.pools)
{
dev.destroyDescriptorPool(descriptorPoolDetails.poolHandle, nullptr, *pVkDynLoader);
}
for (const auto& descriptorPoolDetails : uniformDynamicDescriptorPools.pools)
{
dev.destroyDescriptorPool(descriptorPoolDetails.poolHandle, nullptr, *pVkDynLoader);
}
dev.destroyFence(previousSubmission, nullptr, *pVkDynLoader);
clean();
}
void perFrameResources_t::DescriptorPoolsContainer::reset(vk::Device dev, const vk::DispatchLoaderDynamic& vkDynLoader)
{
for (auto& descriptorPool : pools)
{
dev.resetDescriptorPool(descriptorPool.poolHandle, vk::DescriptorPoolResetFlags(), vkDynLoader);
descriptorPool.requestedSets = 0;
descriptorPool.requestedDescriptors = 0;
}
currPool = 0;
}
void perFrameResources_t::resetDescriptorPools()
{
combinedImageSamplerDescriptorPools.reset(dev, *pVkDynLoader);
uniformDynamicDescriptorPools.reset(dev, *pVkDynLoader);
}
perFrameResources_t& buffering_mechanism::get_current_resources()
{
ASSERT(!perFrameResources.empty(), "perFrameResources are not initialized??");
return *perFrameResources[currentFrame];
}
perSwapchainImageResources_t& buffering_mechanism::get_current_swapchain_resources()
{
ASSERT(!perFrameResources.empty(), "perSwapchainImageResources are not initialized??");
return *perSwapchainImageResources[currentSwapchainImageResourcesFrame];
}
bool buffering_mechanism::isInitialized()
{
return !perFrameResources.empty();
}
perSwapchainImageResources_t::perSwapchainImageResources_t(vk::Device& _dev, const vk::DispatchLoaderDynamic& vkDynLoader)
: dev(_dev)
, pVkDynLoader(&vkDynLoader)
{
imageAcquireSemaphore = dev.createSemaphore(vk::SemaphoreCreateInfo(), nullptr, *pVkDynLoader);
renderFinishedSemaphore = dev.createSemaphore(vk::SemaphoreCreateInfo(), nullptr, *pVkDynLoader);
}
perSwapchainImageResources_t::~perSwapchainImageResources_t()
{
dev.destroySemaphore(imageAcquireSemaphore, nullptr, *pVkDynLoader);
dev.destroySemaphore(renderFinishedSemaphore, nullptr, *pVkDynLoader);
}
// MARK: buffering_mechanism
void buffering_mechanism::init(vk::Device dev, const VmaAllocator& allocator, size_t swapChainImageCount, const uint32_t& graphicsQueueFamilyIndex, const vk::DispatchLoaderDynamic& vkDynLoader)
{
currentFrame = 0;
currentSwapchainImageResourcesFrame = 0;
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i)
{
perFrameResources.emplace_back(new perFrameResources_t(dev, allocator, graphicsQueueFamilyIndex, vkDynLoader));
perSwapchainImageResources.emplace_back(new perSwapchainImageResources_t(dev, vkDynLoader));
}
const auto fences = std::array<vk::Fence, 1> { buffering_mechanism::get_current_resources().previousSubmission };
dev.resetFences(fences, vkDynLoader);
}
size_t buffering_mechanism::get_current_frame_num()
{
return currentFrame;
}
size_t buffering_mechanism::numFrames()
{
return perFrameResources.size();
}
void buffering_mechanism::destroy(vk::Device dev, const vk::DispatchLoaderDynamic& vkDynLoader)
{
perFrameResources.clear();
perSwapchainImageResources.clear();
currentFrame = 0;
currentSwapchainImageResourcesFrame = 0;
}
void buffering_mechanism::swap(vk::Device dev, const vk::DispatchLoaderDynamic& vkDynLoader, bool skipAcquireNewSwapchainImage)
{
currentFrame = (currentFrame < (perFrameResources.size() - 1)) ? currentFrame + 1 : 0;
if (!skipAcquireNewSwapchainImage)
{
currentSwapchainImageResourcesFrame = (currentSwapchainImageResourcesFrame < (perSwapchainImageResources.size() - 1)) ? currentSwapchainImageResourcesFrame + 1 : 0;
}
const auto fences = std::array<vk::Fence, 1> { buffering_mechanism::get_current_resources().previousSubmission };
dev.waitForFences(fences, true, -1, vkDynLoader);
dev.resetFences(fences, vkDynLoader);
buffering_mechanism::get_current_resources().resetDescriptorPools();
dev.resetCommandPool(buffering_mechanism::get_current_resources().pool, vk::CommandPoolResetFlagBits(), vkDynLoader);
buffering_mechanism::get_current_resources().clean();
buffering_mechanism::get_current_resources().numalloc = 0;
}
// MARK: Definitions of statics
std::vector<std::unique_ptr<perFrameResources_t>> buffering_mechanism::perFrameResources;
std::vector<std::unique_ptr<perSwapchainImageResources_t>> buffering_mechanism::perSwapchainImageResources;
size_t buffering_mechanism::currentFrame;
size_t buffering_mechanism::currentSwapchainImageResourcesFrame;
// MARK: Debug Callback
VKAPI_ATTR VkBool32 VKAPI_CALL WZDebugReportCallback(
VkDebugReportFlagsEXT flags,