6#include <qpa/qplatformvulkaninstance.h>
8#define VMA_IMPLEMENTATION
9#define VMA_DYNAMIC_VULKAN_FUNCTIONS 1
10#define VMA_STATIC_VULKAN_FUNCTIONS 0
11#define VMA_RECORDING_ENABLED 0
12#define VMA_DEDICATED_ALLOCATION 0
14Q_STATIC_LOGGING_CATEGORY(QRHI_LOG_VMA,
"qt.rhi.vma")
16#define VMA_ASSERT(expr) Q_ASSERT(expr)
18#define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1
19#define VMA_DEBUG_LOG(str) QT_PREPEND_NAMESPACE(qDebug)(QT_PREPEND_NAMESPACE(QRHI_LOG_VMA), (str))
20#define VMA_DEBUG_LOG_FORMAT(format, ...) QT_PREPEND_NAMESPACE(qDebug)(QT_PREPEND_NAMESPACE(QRHI_LOG_VMA), format, __VA_ARGS__)
22template<
typename... Args>
23static void debugVmaLeak(
const char *format, Args&&... args)
27 static bool leakCheck =
true;
30 static bool leakCheck = QT_PREPEND_NAMESPACE(qEnvironmentVariableIntValue)(
"QT_RHI_LEAK_CHECK");
33 QT_PREPEND_NAMESPACE(qWarning)(QT_PREPEND_NAMESPACE(QRHI_LOG_VMA), format, std::forward<Args>(args)...);
35#define VMA_LEAK_LOG_FORMAT(format, ...) debugVmaLeak(format, __VA_ARGS__)
37QT_WARNING_DISABLE_GCC(
"-Wsuggest-override")
38QT_WARNING_DISABLE_GCC(
"-Wundef")
39QT_WARNING_DISABLE_CLANG(
"-Wundef")
40#if defined(Q_CC_CLANG) && Q_CC_CLANG >= 1100
41QT_WARNING_DISABLE_CLANG(
"-Wdeprecated-copy")
43#include "vk_mem_alloc.h"
47#include <QVulkanFunctions>
48#include <QtGui/qwindow.h>
49#include <private/qvulkandefaultinstance_p.h>
51#include <QtCore/q20memory.h>
52#include <QtCore/qendian.h>
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
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
201
202
203
204
205
208
209
210
211
214
215
216
217
218
222
223
224
225
226
227
228
229
230
231
234
235
236
237
240
241
242
243
244
247
248
249
250
253
254
255
256
259
260
261
262
263
264
265
266
267
268
271
272
273
274
275
278
279
280
281
282
285
286
287
288
289
293
294
295
296
297
298
299
300
301
302
303
304
305
306
309
310
311
312
316
317
318
319
320
321
322
323
326
327
328
329
333
334
335
336
337
338
339
342
343
344
345
346
347
350
351
352
353
354
355
358
359
360
361
362
363
366
367
368
369
370
371
374
375
376
377
378
379
382
383
384
385
386
387
392struct QVkPhysicalDevicePortabilitySubsetFeatures
394 VkStructureType sType;
396 VkBool32 constantAlphaColorBlendFactors;
398 VkBool32 imageViewFormatReinterpretation;
399 VkBool32 imageViewFormatSwizzle;
400 VkBool32 imageView2DOn3DImage;
401 VkBool32 multisampleArrayImage;
402 VkBool32 mutableComparisonSamplers;
403 VkBool32 pointPolygons;
404 VkBool32 samplerMipLodBias;
405 VkBool32 separateStencilMaskRef;
406 VkBool32 shaderSampleRateInterpolationFunctions;
407 VkBool32 tessellationIsolines;
408 VkBool32 tessellationPointMode;
409 VkBool32 triangleFans;
410 VkBool32 vertexAttributeAccessBeyondStride;
413static const VkStructureType QVK_STRUCTURE_TYPE_PDPSF = VkStructureType(1000163000);
417inline Int aligned(Int v, Int byteAlign)
419 return (v + byteAlign - 1) & ~(byteAlign - 1);
424static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL wrap_vkGetInstanceProcAddr(VkInstance,
const char *pName)
426 return globalVulkanInstance->getInstanceProcAddr(pName);
429static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL wrap_vkGetDeviceProcAddr(VkDevice device,
const char *pName)
431 return globalVulkanInstance->functions()->vkGetDeviceProcAddr(device, pName);
436 return reinterpret_cast<VmaAllocation>(a);
441 return reinterpret_cast<VmaAllocator>(a);
445
446
447
448
449
450
451QByteArrayList QRhiVulkanInitParams::preferredInstanceExtensions()
454 QByteArrayLiteral(
"VK_KHR_get_physical_device_properties2"),
456 QByteArrayLiteral(
"VK_EXT_swapchain_colorspace")
461
462
463
464
465QByteArrayList QRhiVulkanInitParams::preferredExtensionsForImportedDevice()
468 QByteArrayLiteral(
"VK_KHR_swapchain"),
469 QByteArrayLiteral(
"VK_EXT_vertex_attribute_divisor"),
470 QByteArrayLiteral(
"VK_KHR_create_renderpass2"),
471 QByteArrayLiteral(
"VK_KHR_depth_stencil_resolve"),
472 QByteArrayLiteral(
"VK_KHR_fragment_shading_rate")
485 qWarning(
"QRhi for Vulkan attempted to be initialized without a QVulkanInstance; using QVulkanDefaultInstance.");
486 inst = QVulkanDefaultInstance::instance();
490 requestedDeviceExtensions = params->deviceExtensions;
493 physDev = importParams->physDev;
494 dev = importParams->dev;
495 if (dev && physDev) {
497 gfxQueueFamilyIdx = importParams->gfxQueueFamilyIdx;
498 gfxQueueIdx = importParams->gfxQueueIdx;
499 gfxQueueFlags = importParams->gfxQueueFlags;
501 if (importParams->vmemAllocator) {
510 QVulkanInstance::DebugMessageTypeFlags type,
511 const void *callbackData)
515#ifdef VK_EXT_debug_utils
516 const VkDebugUtilsMessengerCallbackDataEXT *d =
static_cast<
const VkDebugUtilsMessengerCallbackDataEXT *>(callbackData);
520 if (strstr(d->pMessage,
"Mapping an image with layout")
521 && strstr(d->pMessage,
"can result in undefined behavior if this memory is used by the device"))
532 if (strstr(d->pMessage,
"VUID-VkDescriptorSetAllocateInfo-descriptorPool-00307"))
535 Q_UNUSED(callbackData);
543 case VK_PHYSICAL_DEVICE_TYPE_OTHER:
544 return QRhiDriverInfo::UnknownDevice;
545 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
546 return QRhiDriverInfo::IntegratedDevice;
547 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
548 return QRhiDriverInfo::DiscreteDevice;
549 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
550 return QRhiDriverInfo::VirtualDevice;
551 case VK_PHYSICAL_DEVICE_TYPE_CPU:
552 return QRhiDriverInfo::CpuDevice;
554 return QRhiDriverInfo::UnknownDevice;
558static inline void fillDriverInfo(QRhiDriverInfo *info,
const VkPhysicalDeviceProperties &physDevProperties)
560 info->deviceName = QByteArray(physDevProperties.deviceName);
561 info->deviceId = physDevProperties.deviceID;
562 info->vendorId = physDevProperties.vendorID;
563 info->deviceType = toRhiDeviceType(physDevProperties.deviceType);
569 VkBaseOutStructure *s =
reinterpret_cast<VkBaseOutStructure *>(head);
571 VkBaseOutStructure *next =
reinterpret_cast<VkBaseOutStructure *>(s->pNext);
577 s->pNext =
reinterpret_cast<VkBaseOutStructure *>(entry);
582 if (!inst || !inst->isValid()) {
583 qWarning(
"Vulkan instance is not valid");
588 qCDebug(QRHI_LOG_INFO,
"Initializing QRhi Vulkan backend %p with flags %d",
this,
int(rhiFlags));
591 f = inst->functions();
592 if (QRHI_LOG_INFO().isEnabled(QtDebugMsg)) {
593 qCDebug(QRHI_LOG_INFO,
"Enabled instance extensions:");
594 const QByteArrayList extensions = inst->extensions();
595 for (
const char *ext : extensions)
596 qCDebug(QRHI_LOG_INFO,
" %s", ext);
600 caps.debugUtils = inst->extensions().contains(QByteArrayLiteral(
"VK_EXT_debug_utils"));
602 QList<VkQueueFamilyProperties> queueFamilyProps;
603 auto queryQueueFamilyProps = [
this, &queueFamilyProps] {
604 uint32_t queueCount = 0;
605 f->vkGetPhysicalDeviceQueueFamilyProperties(physDev, &queueCount,
nullptr);
606 queueFamilyProps.resize(
int(queueCount));
607 f->vkGetPhysicalDeviceQueueFamilyProperties(physDev, &queueCount, queueFamilyProps.data());
612 uint32_t physDevCount = 0;
613 f->vkEnumeratePhysicalDevices(inst->vkInstance(), &physDevCount,
nullptr);
615 qWarning(
"No physical devices");
618 QVarLengthArray<VkPhysicalDevice, 4> physDevs(physDevCount);
619 VkResult err =
f->vkEnumeratePhysicalDevices(inst->vkInstance(), &physDevCount, physDevs.data());
620 if (err != VK_SUCCESS || !physDevCount) {
621 qWarning(
"Failed to enumerate physical devices: %d", err);
625 int physDevIndex = -1;
626 int requestedPhysDevIndex = -1;
627 if (qEnvironmentVariableIsSet(
"QT_VK_PHYSICAL_DEVICE_INDEX"))
628 requestedPhysDevIndex = qEnvironmentVariableIntValue(
"QT_VK_PHYSICAL_DEVICE_INDEX");
630 if (requestedPhysDevIndex < 0 && requestedRhiAdapter) {
631 VkPhysicalDevice requestedPhysDev =
static_cast<QVulkanAdapter *>(requestedRhiAdapter)->physDev;
632 for (
int i = 0; i <
int(physDevCount); ++i) {
633 if (physDevs[i] == requestedPhysDev) {
634 requestedPhysDevIndex = i;
640 if (requestedPhysDevIndex < 0 && flags.testFlag(QRhi::PreferSoftwareRenderer)) {
641 for (
int i = 0; i <
int(physDevCount); ++i) {
642 f->vkGetPhysicalDeviceProperties(physDevs[i], &physDevProperties);
643 if (physDevProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) {
644 requestedPhysDevIndex = i;
650 for (
int i = 0; i <
int(physDevCount); ++i) {
651 f->vkGetPhysicalDeviceProperties(physDevs[i], &physDevProperties);
652 qCDebug(QRHI_LOG_INFO,
"Physical device %d: '%s' %d.%d.%d (api %d.%d.%d vendor 0x%X device 0x%X type %d)",
654 physDevProperties.deviceName,
655 VK_VERSION_MAJOR(physDevProperties.driverVersion),
656 VK_VERSION_MINOR(physDevProperties.driverVersion),
657 VK_VERSION_PATCH(physDevProperties.driverVersion),
658 VK_VERSION_MAJOR(physDevProperties.apiVersion),
659 VK_VERSION_MINOR(physDevProperties.apiVersion),
660 VK_VERSION_PATCH(physDevProperties.apiVersion),
661 physDevProperties.vendorID,
662 physDevProperties.deviceID,
663 physDevProperties.deviceType);
664 if (physDevIndex < 0 && (requestedPhysDevIndex < 0 || requestedPhysDevIndex ==
int(i))) {
666 qCDebug(QRHI_LOG_INFO,
" using this physical device");
670 if (physDevIndex < 0) {
671 qWarning(
"No matching physical device");
674 physDev = physDevs[physDevIndex];
675 f->vkGetPhysicalDeviceProperties(physDev, &physDevProperties);
677 f->vkGetPhysicalDeviceProperties(physDev, &physDevProperties);
678 qCDebug(QRHI_LOG_INFO,
"Using imported physical device '%s' %d.%d.%d (api %d.%d.%d vendor 0x%X device 0x%X type %d)",
679 physDevProperties.deviceName,
680 VK_VERSION_MAJOR(physDevProperties.driverVersion),
681 VK_VERSION_MINOR(physDevProperties.driverVersion),
682 VK_VERSION_PATCH(physDevProperties.driverVersion),
683 VK_VERSION_MAJOR(physDevProperties.apiVersion),
684 VK_VERSION_MINOR(physDevProperties.apiVersion),
685 VK_VERSION_PATCH(physDevProperties.apiVersion),
686 physDevProperties.vendorID,
687 physDevProperties.deviceID,
688 physDevProperties.deviceType);
691 caps.apiVersion = inst->apiVersion();
697 const QVersionNumber physDevApiVersion(VK_VERSION_MAJOR(physDevProperties.apiVersion),
698 VK_VERSION_MINOR(physDevProperties.apiVersion));
699 if (physDevApiVersion < caps.apiVersion) {
700 qCDebug(QRHI_LOG_INFO) <<
"Instance has api version" << caps.apiVersion
701 <<
"whereas the chosen physical device has" << physDevApiVersion
702 <<
"- restricting to the latter";
703 caps.apiVersion = physDevApiVersion;
708 QVulkanInfoVector<QVulkanExtension> devExts;
709 uint32_t devExtCount = 0;
710 f->vkEnumerateDeviceExtensionProperties(physDev,
nullptr, &devExtCount,
nullptr);
712 QList<VkExtensionProperties> extProps(devExtCount);
713 f->vkEnumerateDeviceExtensionProperties(physDev,
nullptr, &devExtCount, extProps.data());
714 for (
const VkExtensionProperties &p : std::as_const(extProps))
715 devExts.append({ p.extensionName, p.specVersion });
717 qCDebug(QRHI_LOG_INFO,
"%d device extensions available",
int(devExts.size()));
719 const bool hasPhysDevProp2 = inst->extensions().contains(QByteArrayLiteral(
"VK_KHR_get_physical_device_properties2"));
721 bool featuresQueried =
false;
723 VkPhysicalDeviceFeatures2 physDevFeaturesChainable = {};
724 physDevFeaturesChainable.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
727#ifdef VK_KHR_fragment_shading_rate
728 VkPhysicalDeviceFragmentShadingRateFeaturesKHR fragmentShadingRateFeatures = {};
729 fragmentShadingRateFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR;
730 if (devExts.contains(
"VK_KHR_fragment_shading_rate"))
731 addToChain(&physDevFeaturesChainable, &fragmentShadingRateFeatures);
733#ifdef VK_EXT_device_fault
734 VkPhysicalDeviceFaultFeaturesEXT deviceFaultFeatures = {};
735 deviceFaultFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT;
736 if (devExts.contains(VK_EXT_DEVICE_FAULT_EXTENSION_NAME))
737 addToChain(&physDevFeaturesChainable, &deviceFaultFeatures);
740 QVkPhysicalDevicePortabilitySubsetFeatures portabilitySubsetFeatures = {};
741 portabilitySubsetFeatures.sType = QVK_STRUCTURE_TYPE_PDPSF;
742 if (hasPhysDevProp2 && devExts.contains(QByteArrayLiteral(
"VK_KHR_portability_subset")))
743 addToChain(&physDevFeaturesChainable, &portabilitySubsetFeatures);
748 if (!featuresQueried) {
750 if (caps.apiVersion >= QVersionNumber(1, 2)) {
751 physDevFeatures11IfApi12OrNewer = {};
752 physDevFeatures11IfApi12OrNewer.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
753 physDevFeatures12 = {};
754 physDevFeatures12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
756 physDevFeatures13 = {};
757 physDevFeatures13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
759 physDevFeatures14 = {};
760 physDevFeatures14.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_4_FEATURES;
763 addToChain(&physDevFeaturesChainable, &physDevFeatures11IfApi12OrNewer);
764 physDevFeatures11IfApi12OrNewer.pNext = &physDevFeatures12;
766 if (caps.apiVersion >= QVersionNumber(1, 3))
767 physDevFeatures12.pNext = &physDevFeatures13;
769 if (caps.apiVersion >= QVersionNumber(1, 4))
770 physDevFeatures13.pNext = &physDevFeatures14;
773 f->vkGetPhysicalDeviceFeatures2(physDev, &physDevFeaturesChainable);
774 memcpy(&physDevFeatures, &physDevFeaturesChainable.features,
sizeof(VkPhysicalDeviceFeatures));
775 featuresQueried =
true;
782 if (!featuresQueried) {
790 if (caps.apiVersion == QVersionNumber(1, 1)) {
792 multiviewFeaturesIfApi11 = {};
793 multiviewFeaturesIfApi11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES;
794 addToChain(&physDevFeaturesChainable, &multiviewFeaturesIfApi11);
797 shaderDrawParametersFeaturesIfApi11 = {};
798 shaderDrawParametersFeaturesIfApi11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES;
799 addToChain(&physDevFeaturesChainable, &shaderDrawParametersFeaturesIfApi11);
801 f->vkGetPhysicalDeviceFeatures2(physDev, &physDevFeaturesChainable);
802 memcpy(&physDevFeatures, &physDevFeaturesChainable.features,
sizeof(VkPhysicalDeviceFeatures));
803 featuresQueried =
true;
808 if (!featuresQueried) {
811 f->vkGetPhysicalDeviceFeatures(physDev, &physDevFeatures);
812 featuresQueried =
true;
820 std::optional<uint32_t> gfxQueueFamilyIdxOpt;
821 std::optional<uint32_t> computelessGfxQueueCandidateIdxOpt;
822 queryQueueFamilyProps();
823 const uint32_t queueFamilyCount = uint32_t(queueFamilyProps.size());
824 for (uint32_t i = 0; i < queueFamilyCount; ++i) {
825 qCDebug(QRHI_LOG_INFO,
"queue family %u: flags=0x%x count=%u",
826 i, queueFamilyProps[i].queueFlags, queueFamilyProps[i].queueCount);
827 if (!gfxQueueFamilyIdxOpt.has_value()
828 && (queueFamilyProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
829 && (!maybeWindow || inst->supportsPresent(physDev, i, maybeWindow)))
831 if (queueFamilyProps[i].queueFlags & VK_QUEUE_COMPUTE_BIT)
832 gfxQueueFamilyIdxOpt = i;
833 else if (!computelessGfxQueueCandidateIdxOpt.has_value())
834 computelessGfxQueueCandidateIdxOpt = i;
837 if (gfxQueueFamilyIdxOpt.has_value()) {
838 gfxQueueFamilyIdx = gfxQueueFamilyIdxOpt.value();
840 if (computelessGfxQueueCandidateIdxOpt.has_value()) {
841 gfxQueueFamilyIdx = computelessGfxQueueCandidateIdxOpt.value();
843 qWarning(
"No graphics (or no graphics+present) queue family found");
848 VkDeviceQueueCreateInfo queueInfo = {};
849 const float prio[] = { 0 };
850 queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
851 queueInfo.queueFamilyIndex = gfxQueueFamilyIdx;
852 queueInfo.queueCount = 1;
853 queueInfo.pQueuePriorities = prio;
855 QList<
const char *> requestedDevExts;
856 requestedDevExts.append(
"VK_KHR_swapchain");
858 if (devExts.contains(QByteArrayLiteral(
"VK_KHR_portability_subset"))) {
859 if (hasPhysDevProp2) {
860 requestedDevExts.append(
"VK_KHR_portability_subset");
862 qWarning(
"VK_KHR_portability_subset should be enabled on the device "
863 "but the instance does not have VK_KHR_get_physical_device_properties2 enabled. "
868#ifdef VK_EXT_vertex_attribute_divisor
869 if (devExts.contains(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME)) {
870 if (hasPhysDevProp2) {
871 requestedDevExts.append(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME);
872 caps.vertexAttribDivisor =
true;
877#ifdef VK_KHR_create_renderpass2
878 if (devExts.contains(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) {
882 bool canEnable =
true;
883 if (caps.apiVersion < QVersionNumber(1, 1)) {
884 canEnable = hasPhysDevProp2
885 && devExts.contains(QByteArrayLiteral(
"VK_KHR_multiview"))
886 && devExts.contains(QByteArrayLiteral(
"VK_KHR_maintenance2"));
888 requestedDevExts.append(
"VK_KHR_multiview");
889 requestedDevExts.append(
"VK_KHR_maintenance2");
893 requestedDevExts.append(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME);
894 caps.renderPass2KHR =
true;
899#ifdef VK_KHR_depth_stencil_resolve
901 const bool hasRenderPass2Dep = caps.renderPass2KHR || caps.apiVersion >= QVersionNumber(1, 2);
902 if (hasRenderPass2Dep && devExts.contains(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME)) {
903 requestedDevExts.append(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME);
904 caps.depthStencilResolveKHR =
true;
909#ifdef VK_KHR_fragment_shading_rate
911 const bool hasRenderPass2Dep = caps.renderPass2KHR || caps.apiVersion >= QVersionNumber(1, 2);
912 if (hasRenderPass2Dep && devExts.contains(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME))
913 requestedDevExts.append(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME);
917#ifdef VK_EXT_device_fault
918 if (devExts.contains(VK_EXT_DEVICE_FAULT_EXTENSION_NAME)) {
919 requestedDevExts.append(VK_EXT_DEVICE_FAULT_EXTENSION_NAME);
920 caps.deviceFault =
true;
924 for (
const QByteArray &ext : std::as_const(requestedDeviceExtensions)) {
925 if (!ext.isEmpty() && !requestedDevExts.contains(ext)) {
926 if (devExts.contains(ext)) {
927 requestedDevExts.append(ext.constData());
929 qWarning(
"Device extension %s requested in QRhiVulkanInitParams is not supported",
935 const QByteArrayList envExtList = qgetenv(
"QT_VULKAN_DEVICE_EXTENSIONS").split(
';');
936 for (
const QByteArray &ext : envExtList) {
937 if (!ext.isEmpty() && !requestedDevExts.contains(ext)) {
938 if (devExts.contains(ext)) {
939 requestedDevExts.append(ext.constData());
941 qWarning(
"Device extension %s requested in QT_VULKAN_DEVICE_EXTENSIONS is not supported",
947 if (QRHI_LOG_INFO().isEnabled(QtDebugMsg)) {
948 qCDebug(QRHI_LOG_INFO,
"Enabling device extensions:");
949 for (
const char *ext : std::as_const(requestedDevExts))
950 qCDebug(QRHI_LOG_INFO,
" %s", ext);
953 VkDeviceCreateInfo devInfo = {};
954 devInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
955 devInfo.queueCreateInfoCount = 1;
956 devInfo.pQueueCreateInfos = &queueInfo;
958 devInfo.enabledLayerCount = 0;
959 devInfo.ppEnabledLayerNames =
nullptr;
960 devInfo.enabledExtensionCount = uint32_t(requestedDevExts.size());
961 devInfo.ppEnabledExtensionNames = requestedDevExts.constData();
977 physDevFeaturesChainable.features.robustBufferAccess = VK_FALSE;
980 physDevFeatures13.robustImageAccess = VK_FALSE;
984 if (caps.apiVersion >= QVersionNumber(1, 1)) {
991 devInfo.pNext = &physDevFeaturesChainable;
995 physDevFeatures.robustBufferAccess = VK_FALSE;
996 devInfo.pEnabledFeatures = &physDevFeatures;
999 VkResult err =
f->vkCreateDevice(physDev, &devInfo,
nullptr, &dev);
1000 if (err != VK_SUCCESS) {
1001 qWarning(
"Failed to create device: %d", err);
1005 qCDebug(QRHI_LOG_INFO,
"Using imported device %p", dev);
1010 caps.deviceFault =
true;
1011 caps.vertexAttribDivisor =
true;
1012 caps.renderPass2KHR =
true;
1013 caps.depthStencilResolveKHR =
true;
1016 vkGetPhysicalDeviceSurfaceCapabilitiesKHR =
reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR>(
1017 inst->getInstanceProcAddr(
"vkGetPhysicalDeviceSurfaceCapabilitiesKHR"));
1018 vkGetPhysicalDeviceSurfaceFormatsKHR =
reinterpret_cast<PFN_vkGetPhysicalDeviceSurfaceFormatsKHR>(
1019 inst->getInstanceProcAddr(
"vkGetPhysicalDeviceSurfaceFormatsKHR"));
1020 vkGetPhysicalDeviceSurfacePresentModesKHR =
reinterpret_cast<PFN_vkGetPhysicalDeviceSurfacePresentModesKHR>(
1021 inst->getInstanceProcAddr(
"vkGetPhysicalDeviceSurfacePresentModesKHR"));
1023 df = inst->deviceFunctions(dev);
1025 VkCommandPoolCreateInfo poolInfo = {};
1026 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1027 poolInfo.queueFamilyIndex = gfxQueueFamilyIdx;
1029 VkResult err =
df->vkCreateCommandPool(dev, &poolInfo,
nullptr, &cmdPool[i]);
1030 if (err != VK_SUCCESS) {
1031 qWarning(
"Failed to create command pool: %d", err);
1036 qCDebug(QRHI_LOG_INFO,
"Using queue family index %u and queue index %u",
1037 gfxQueueFamilyIdx, gfxQueueIdx);
1040 if (gfxQueueFlags && caps.apiVersion >= QVersionNumber(1, 1)) {
1041 VkDeviceQueueInfo2 queueInfo = {};
1042 queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2;
1043 queueInfo.flags = gfxQueueFlags;
1044 queueInfo.queueFamilyIndex = gfxQueueFamilyIdx;
1045 queueInfo.queueIndex = gfxQueueIdx;
1046 df->vkGetDeviceQueue2(dev, &queueInfo, &gfxQueue);
1049 df->vkGetDeviceQueue(dev, gfxQueueFamilyIdx, gfxQueueIdx, &gfxQueue);
1051 if (queueFamilyProps.isEmpty())
1052 queryQueueFamilyProps();
1054 caps.compute = (queueFamilyProps[gfxQueueFamilyIdx].queueFlags & VK_QUEUE_COMPUTE_BIT) != 0;
1055 timestampValidBits = queueFamilyProps[gfxQueueFamilyIdx].timestampValidBits;
1057 ubufAlign = physDevProperties.limits.minUniformBufferOffsetAlignment;
1060 texbufAlign = qMax<VkDeviceSize>(4, physDevProperties.limits.optimalBufferCopyOffsetAlignment);
1062 caps.depthClamp = physDevFeatures.depthClamp;
1064 caps.wideLines = physDevFeatures.wideLines;
1066 caps.texture3DSliceAs2D = caps.apiVersion >= QVersionNumber(1, 1);
1068 caps.tessellation = physDevFeatures.tessellationShader;
1069 caps.geometryShader = physDevFeatures.geometryShader;
1071 caps.nonFillPolygonMode = physDevFeatures.fillModeNonSolid;
1073 caps.drawIndirectMulti = physDevFeatures.multiDrawIndirect;
1075 caps.dualSrcBlend = physDevFeatures.dualSrcBlend;
1076 caps.drawIndirectFirstInstance = physDevFeatures.drawIndirectFirstInstance;
1078#ifdef VK_VERSION_1_2
1079 if (caps.apiVersion >= QVersionNumber(1, 2)) {
1080 caps.multiView = physDevFeatures11IfApi12OrNewer.multiview;
1081 caps.shaderDrawParameters = physDevFeatures11IfApi12OrNewer.shaderDrawParameters;
1084 caps.drawIndirectCount = physDevFeatures12.drawIndirectCount && caps.drawIndirectMulti;
1088#ifdef VK_VERSION_1_1
1089 if (caps.apiVersion == QVersionNumber(1, 1)) {
1090 caps.multiView = multiviewFeaturesIfApi11.multiview;
1091 caps.shaderDrawParameters = shaderDrawParametersFeaturesIfApi11.shaderDrawParameters;
1095#ifdef VK_KHR_fragment_shading_rate
1096 fragmentShadingRates.clear();
1097 if (caps.apiVersion >= QVersionNumber(1, 1)) {
1098 caps.perDrawShadingRate = fragmentShadingRateFeatures.pipelineFragmentShadingRate;
1099 caps.imageBasedShadingRate = fragmentShadingRateFeatures.attachmentFragmentShadingRate;
1100 if (caps.imageBasedShadingRate) {
1101 VkPhysicalDeviceFragmentShadingRatePropertiesKHR shadingRateProps = {};
1102 shadingRateProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_PROPERTIES_KHR;
1103 VkPhysicalDeviceProperties2 props2 = {};
1104 props2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
1105 props2.pNext = &shadingRateProps;
1106 f->vkGetPhysicalDeviceProperties2(physDev, &props2);
1107 caps.imageBasedShadingRateTileSize =
int(shadingRateProps.maxFragmentShadingRateAttachmentTexelSize.width);
1110 if (caps.perDrawShadingRate) {
1111 PFN_vkGetPhysicalDeviceFragmentShadingRatesKHR vkGetPhysicalDeviceFragmentShadingRatesKHR =
1112 reinterpret_cast<PFN_vkGetPhysicalDeviceFragmentShadingRatesKHR>(
1113 inst->getInstanceProcAddr(
"vkGetPhysicalDeviceFragmentShadingRatesKHR"));
1114 if (vkGetPhysicalDeviceFragmentShadingRatesKHR) {
1116 vkGetPhysicalDeviceFragmentShadingRatesKHR(physDev, &count,
nullptr);
1117 fragmentShadingRates.resize(count);
1118 for (VkPhysicalDeviceFragmentShadingRateKHR &s : fragmentShadingRates) {
1120 s.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_KHR;
1122 vkGetPhysicalDeviceFragmentShadingRatesKHR(physDev, &count, fragmentShadingRates.data());
1124 vkCmdSetFragmentShadingRateKHR =
reinterpret_cast<PFN_vkCmdSetFragmentShadingRateKHR>(
1125 f->vkGetDeviceProcAddr(dev,
"vkCmdSetFragmentShadingRateKHR"));
1134#ifdef VK_KHR_create_renderpass2
1135 if (caps.renderPass2KHR) {
1136 vkCreateRenderPass2KHR =
reinterpret_cast<PFN_vkCreateRenderPass2KHR>(f->vkGetDeviceProcAddr(dev,
"vkCreateRenderPass2KHR"));
1137 if (!vkCreateRenderPass2KHR)
1138 caps.renderPass2KHR =
false;
1142#ifdef VK_VERSION_1_2
1143 if (caps.drawIndirectCount) {
1144 vkCmdDrawIndirectCount =
reinterpret_cast<PFN_vkCmdDrawIndirectCount>(
1145 f->vkGetDeviceProcAddr(dev,
"vkCmdDrawIndirectCount"));
1146 vkCmdDrawIndexedIndirectCount =
reinterpret_cast<PFN_vkCmdDrawIndexedIndirectCount>(
1147 f->vkGetDeviceProcAddr(dev,
"vkCmdDrawIndexedIndirectCount"));
1148 if (!vkCmdDrawIndirectCount || !vkCmdDrawIndexedIndirectCount) {
1149 qWarning(
"Failed to resolve vkCmdDrawIndirectCount/vkCmdDrawIndexedIndirectCount; disabling DrawIndirectCount feature.");
1150 caps.drawIndirectCount =
false;
1157 adapterLuidValid =
false;
1159#ifdef VK_VERSION_1_2
1160 if (caps.apiVersion >= QVersionNumber(1, 2)) {
1161 VkPhysicalDeviceVulkan11Properties v11props = {};
1162 v11props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES;
1163 VkPhysicalDeviceProperties2 props2 = {};
1164 props2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
1165 props2.pNext = &v11props;
1166 f->vkGetPhysicalDeviceProperties2(physDev, &props2);
1167 if (v11props.deviceLUIDValid) {
1168 const LUID *luid =
reinterpret_cast<
const LUID *>(v11props.deviceLUID);
1169 memcpy(&adapterLuid, luid, VK_LUID_SIZE);
1170 adapterLuidValid =
true;
1171 dxgiHdrInfo =
new QDxgiHdrInfo(adapterLuid);
1172 qCDebug(QRHI_LOG_INFO,
"DXGI adapter LUID for physical device is %lu, %lu",
1173 adapterLuid.LowPart, adapterLuid.HighPart);
1180 VmaVulkanFunctions funcs = {};
1181 funcs.vkGetInstanceProcAddr = wrap_vkGetInstanceProcAddr;
1182 funcs.vkGetDeviceProcAddr = wrap_vkGetDeviceProcAddr;
1184 VmaAllocatorCreateInfo allocatorInfo = {};
1187 allocatorInfo.flags = VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT;
1188 allocatorInfo.physicalDevice = physDev;
1189 allocatorInfo.device = dev;
1190 allocatorInfo.pVulkanFunctions = &funcs;
1191 allocatorInfo.instance = inst->vkInstance();
1199#ifdef VK_VERSION_1_4
1200 if (caps.apiVersion >= QVersionNumber(1, 4))
1201 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_4;
1204#ifdef VK_VERSION_1_3
1205 if (caps.apiVersion >= QVersionNumber(1, 3))
1206 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_3;
1209#ifdef VK_VERSION_1_2
1210 if (caps.apiVersion >= QVersionNumber(1, 2))
1211 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_2;
1214#ifdef VK_VERSION_1_1
1215 if (caps.apiVersion >= QVersionNumber(1, 1))
1216 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_1;
1219#ifdef VK_VERSION_1_0
1220 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_0;
1223 VmaAllocator vmaallocator;
1224 VkResult err = vmaCreateAllocator(&allocatorInfo, &vmaallocator);
1225 if (err != VK_SUCCESS) {
1226 qWarning(
"Failed to create allocator: %d", err);
1232 inst->installDebugOutputFilter(qvk_debug_filter);
1234 VkDescriptorPool pool;
1235 VkResult err = createDescriptorPool(&pool);
1236 if (err == VK_SUCCESS)
1237 descriptorPools.append(pool);
1239 qWarning(
"Failed to create initial descriptor pool: %d", err);
1241 VkQueryPoolCreateInfo timestampQueryPoolInfo = {};
1242 timestampQueryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
1243 timestampQueryPoolInfo.queryType = VK_QUERY_TYPE_TIMESTAMP;
1245 err =
df->vkCreateQueryPool(dev, ×tampQueryPoolInfo,
nullptr, ×tampQueryPool);
1246 if (err != VK_SUCCESS) {
1247 qWarning(
"Failed to create timestamp query pool: %d", err);
1250 timestampQueryPoolMap.resize(QVK_MAX_ACTIVE_TIMESTAMP_PAIRS);
1251 timestampQueryPoolMap.fill(
false);
1253#ifdef VK_EXT_debug_utils
1254 if (caps.debugUtils) {
1255 vkSetDebugUtilsObjectNameEXT =
reinterpret_cast<PFN_vkSetDebugUtilsObjectNameEXT>(f->vkGetDeviceProcAddr(dev,
"vkSetDebugUtilsObjectNameEXT"));
1256 vkCmdBeginDebugUtilsLabelEXT =
reinterpret_cast<PFN_vkCmdBeginDebugUtilsLabelEXT>(f->vkGetDeviceProcAddr(dev,
"vkCmdBeginDebugUtilsLabelEXT"));
1257 vkCmdEndDebugUtilsLabelEXT =
reinterpret_cast<PFN_vkCmdEndDebugUtilsLabelEXT>(f->vkGetDeviceProcAddr(dev,
"vkCmdEndDebugUtilsLabelEXT"));
1258 vkCmdInsertDebugUtilsLabelEXT =
reinterpret_cast<PFN_vkCmdInsertDebugUtilsLabelEXT>(f->vkGetDeviceProcAddr(dev,
"vkCmdInsertDebugUtilsLabelEXT"));
1262#ifdef VK_EXT_device_fault
1263 if (caps.deviceFault) {
1264 vkGetDeviceFaultInfoEXT =
reinterpret_cast<PFN_vkGetDeviceFaultInfoEXT>(f->vkGetDeviceProcAddr(dev,
"vkGetDeviceFaultInfoEXT"));
1270 nativeHandlesStruct.physDev = physDev;
1271 nativeHandlesStruct.dev = dev;
1272 nativeHandlesStruct.gfxQueueFamilyIdx = gfxQueueFamilyIdx;
1273 nativeHandlesStruct.gfxQueueIdx = gfxQueueIdx;
1274 nativeHandlesStruct.gfxQueueFlags = gfxQueueFlags;
1275 nativeHandlesStruct.gfxQueue = gfxQueue;
1276 nativeHandlesStruct.vmemAllocator = allocator;
1277 nativeHandlesStruct.inst = inst;
1288 df->vkQueueWaitIdle(gfxQueue);
1295 dxgiHdrInfo =
nullptr;
1299 if (ofr.cmdFence[i]) {
1300 df->vkDestroyFence(dev, ofr.cmdFence[i],
nullptr);
1301 ofr.cmdFence[i] = VK_NULL_HANDLE;
1303 ofr.cmdFenceWaitable[i] =
false;
1306 if (pipelineCache) {
1307 df->vkDestroyPipelineCache(dev, pipelineCache,
nullptr);
1308 pipelineCache = VK_NULL_HANDLE;
1311 for (
const DescriptorPoolData &pool : descriptorPools)
1312 df->vkDestroyDescriptorPool(dev, pool.pool,
nullptr);
1314 descriptorPools.clear();
1316 if (timestampQueryPool) {
1317 df->vkDestroyQueryPool(dev, timestampQueryPool,
nullptr);
1318 timestampQueryPool = VK_NULL_HANDLE;
1322 vmaDestroyAllocator(toVmaAllocator(allocator));
1328 df->vkDestroyCommandPool(dev, cmdPool[i],
nullptr);
1329 cmdPool[i] = VK_NULL_HANDLE;
1331 freeSecondaryCbs[i].clear();
1332 ofr.cbWrapper[i]->cb = VK_NULL_HANDLE;
1335 if (!importedDevice && dev) {
1336 df->vkDestroyDevice(dev,
nullptr);
1337 inst->resetDeviceFunctions(dev);
1338 dev = VK_NULL_HANDLE;
1348QRhi::AdapterList
QRhiVulkan::enumerateAdaptersBeforeCreate(QRhiNativeHandles *nativeHandles)
const
1350 VkPhysicalDevice requestedPhysDev = VK_NULL_HANDLE;
1351 if (nativeHandles) {
1352 QRhiVulkanNativeHandles *h =
static_cast<QRhiVulkanNativeHandles *>(nativeHandles);
1353 requestedPhysDev = h->physDev;
1356 QRhi::AdapterList list;
1357 QVulkanFunctions *f = inst->functions();
1358 uint32_t physDevCount = 0;
1359 f->vkEnumeratePhysicalDevices(inst->vkInstance(), &physDevCount,
nullptr);
1363 QVarLengthArray<VkPhysicalDevice, 4> physDevs(physDevCount);
1364 VkResult err = f->vkEnumeratePhysicalDevices(inst->vkInstance(), &physDevCount, physDevs.data());
1365 if (err != VK_SUCCESS || !physDevCount)
1368 VkPhysicalDeviceProperties physDevProperties = {};
1369 for (uint32_t i = 0; i < physDevCount; ++i) {
1370 if (requestedPhysDev && physDevs[i] != requestedPhysDev)
1373 f->vkGetPhysicalDeviceProperties(physDevs[i], &physDevProperties);
1374 QVulkanAdapter *a =
new QVulkanAdapter;
1375 a->physDev = physDevs[i];
1376 fillDriverInfo(&a->adapterInfo, physDevProperties);
1390 VkDescriptorPoolSize descPoolSizes[] = {
1391 { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, QVK_UNIFORM_BUFFERS_PER_POOL },
1392 { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, QVK_UNIFORM_BUFFERS_PER_POOL },
1393 { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, QVK_COMBINED_IMAGE_SAMPLERS_PER_POOL },
1394 { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, QVK_SAMPLED_IMAGES_PER_POOL },
1395 { VK_DESCRIPTOR_TYPE_SAMPLER, QVK_SAMPLERS_PER_POOL },
1396 { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, QVK_STORAGE_BUFFERS_PER_POOL },
1397 { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, QVK_STORAGE_IMAGES_PER_POOL }
1399 VkDescriptorPoolCreateInfo descPoolInfo = {};
1400 descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
1404 descPoolInfo.flags = 0;
1406 descPoolInfo.poolSizeCount =
sizeof(descPoolSizes) /
sizeof(descPoolSizes[0]);
1407 descPoolInfo.pPoolSizes = descPoolSizes;
1408 return df->vkCreateDescriptorPool(dev, &descPoolInfo,
nullptr, pool);
1413 auto tryAllocate = [
this, allocInfo, result](
int poolIndex) {
1414 allocInfo->descriptorPool = descriptorPools[poolIndex].pool;
1415 VkResult r =
df->vkAllocateDescriptorSets(dev, allocInfo, result);
1416 if (r == VK_SUCCESS)
1417 descriptorPools[poolIndex].refCount += 1;
1421 int lastPoolIdx = descriptorPools.size() - 1;
1422 for (
int i = lastPoolIdx; i >= 0; --i) {
1423 if (descriptorPools[i].refCount == 0) {
1424 df->vkResetDescriptorPool(dev, descriptorPools[i].pool, 0);
1425 descriptorPools[i].allocedDescSets = 0;
1427 if (descriptorPools[i].allocedDescSets +
int(allocInfo->descriptorSetCount) <= QVK_DESC_SETS_PER_POOL) {
1428 VkResult err = tryAllocate(i);
1429 if (err == VK_SUCCESS) {
1430 descriptorPools[i].allocedDescSets += allocInfo->descriptorSetCount;
1431 *resultPoolIndex = i;
1437 VkDescriptorPool newPool;
1438 VkResult poolErr = createDescriptorPool(&newPool);
1439 if (poolErr == VK_SUCCESS) {
1440 descriptorPools.append(newPool);
1441 lastPoolIdx = descriptorPools.size() - 1;
1442 VkResult err = tryAllocate(lastPoolIdx);
1443 if (err != VK_SUCCESS) {
1444 qWarning(
"Failed to allocate descriptor set from new pool too, giving up: %d", err);
1447 descriptorPools[lastPoolIdx].allocedDescSets += allocInfo->descriptorSetCount;
1448 *resultPoolIndex = lastPoolIdx;
1451 qWarning(
"Failed to allocate new descriptor pool: %d", poolErr);
1458 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
1460 case QRhiTexture::RGBA8:
1461 return srgb ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM;
1462 case QRhiTexture::BGRA8:
1463 return srgb ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_B8G8R8A8_UNORM;
1464 case QRhiTexture::R8:
1465 return srgb ? VK_FORMAT_R8_SRGB : VK_FORMAT_R8_UNORM;
1466 case QRhiTexture::RG8:
1467 return srgb ? VK_FORMAT_R8G8_SRGB : VK_FORMAT_R8G8_UNORM;
1468 case QRhiTexture::R16:
1469 return VK_FORMAT_R16_UNORM;
1470 case QRhiTexture::RG16:
1471 return VK_FORMAT_R16G16_UNORM;
1472 case QRhiTexture::RED_OR_ALPHA8:
1473 return VK_FORMAT_R8_UNORM;
1475 case QRhiTexture::RGBA16F:
1476 return VK_FORMAT_R16G16B16A16_SFLOAT;
1477 case QRhiTexture::RGBA32F:
1478 return VK_FORMAT_R32G32B32A32_SFLOAT;
1479 case QRhiTexture::R16F:
1480 return VK_FORMAT_R16_SFLOAT;
1481 case QRhiTexture::R32F:
1482 return VK_FORMAT_R32_SFLOAT;
1484 case QRhiTexture::RGB10A2:
1486 return VK_FORMAT_A2B10G10R10_UNORM_PACK32;
1488 case QRhiTexture::R8SI:
1489 return VK_FORMAT_R8_SINT;
1490 case QRhiTexture::R32SI:
1491 return VK_FORMAT_R32_SINT;
1492 case QRhiTexture::RG32SI:
1493 return VK_FORMAT_R32G32_SINT;
1494 case QRhiTexture::RGBA32SI:
1495 return VK_FORMAT_R32G32B32A32_SINT;
1497 case QRhiTexture::R8UI:
1498 return VK_FORMAT_R8_UINT;
1499 case QRhiTexture::R32UI:
1500 return VK_FORMAT_R32_UINT;
1501 case QRhiTexture::RG32UI:
1502 return VK_FORMAT_R32G32_UINT;
1503 case QRhiTexture::RGBA32UI:
1504 return VK_FORMAT_R32G32B32A32_UINT;
1506 case QRhiTexture::D16:
1507 return VK_FORMAT_D16_UNORM;
1508 case QRhiTexture::D24:
1509 return VK_FORMAT_X8_D24_UNORM_PACK32;
1510 case QRhiTexture::D24S8:
1511 return VK_FORMAT_D24_UNORM_S8_UINT;
1512 case QRhiTexture::D32F:
1513 return VK_FORMAT_D32_SFLOAT;
1514 case QRhiTexture::D32FS8:
1515 return VK_FORMAT_D32_SFLOAT_S8_UINT;
1517 case QRhiTexture::BC1:
1518 return srgb ? VK_FORMAT_BC1_RGB_SRGB_BLOCK : VK_FORMAT_BC1_RGB_UNORM_BLOCK;
1519 case QRhiTexture::BC2:
1520 return srgb ? VK_FORMAT_BC2_SRGB_BLOCK : VK_FORMAT_BC2_UNORM_BLOCK;
1521 case QRhiTexture::BC3:
1522 return srgb ? VK_FORMAT_BC3_SRGB_BLOCK : VK_FORMAT_BC3_UNORM_BLOCK;
1523 case QRhiTexture::BC4:
1524 return VK_FORMAT_BC4_UNORM_BLOCK;
1525 case QRhiTexture::BC5:
1526 return VK_FORMAT_BC5_UNORM_BLOCK;
1527 case QRhiTexture::BC6H:
1528 return VK_FORMAT_BC6H_UFLOAT_BLOCK;
1529 case QRhiTexture::BC7:
1530 return srgb ? VK_FORMAT_BC7_SRGB_BLOCK : VK_FORMAT_BC7_UNORM_BLOCK;
1532 case QRhiTexture::ETC2_RGB8:
1533 return srgb ? VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK : VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;
1534 case QRhiTexture::ETC2_RGB8A1:
1535 return srgb ? VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK : VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK;
1536 case QRhiTexture::ETC2_RGBA8:
1537 return srgb ? VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK : VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;
1539 case QRhiTexture::ASTC_4x4:
1540 return srgb ? VK_FORMAT_ASTC_4x4_SRGB_BLOCK : VK_FORMAT_ASTC_4x4_UNORM_BLOCK;
1541 case QRhiTexture::ASTC_5x4:
1542 return srgb ? VK_FORMAT_ASTC_5x4_SRGB_BLOCK : VK_FORMAT_ASTC_5x4_UNORM_BLOCK;
1543 case QRhiTexture::ASTC_5x5:
1544 return srgb ? VK_FORMAT_ASTC_5x5_SRGB_BLOCK : VK_FORMAT_ASTC_5x5_UNORM_BLOCK;
1545 case QRhiTexture::ASTC_6x5:
1546 return srgb ? VK_FORMAT_ASTC_6x5_SRGB_BLOCK : VK_FORMAT_ASTC_6x5_UNORM_BLOCK;
1547 case QRhiTexture::ASTC_6x6:
1548 return srgb ? VK_FORMAT_ASTC_6x6_SRGB_BLOCK : VK_FORMAT_ASTC_6x6_UNORM_BLOCK;
1549 case QRhiTexture::ASTC_8x5:
1550 return srgb ? VK_FORMAT_ASTC_8x5_SRGB_BLOCK : VK_FORMAT_ASTC_8x5_UNORM_BLOCK;
1551 case QRhiTexture::ASTC_8x6:
1552 return srgb ? VK_FORMAT_ASTC_8x6_SRGB_BLOCK : VK_FORMAT_ASTC_8x6_UNORM_BLOCK;
1553 case QRhiTexture::ASTC_8x8:
1554 return srgb ? VK_FORMAT_ASTC_8x8_SRGB_BLOCK : VK_FORMAT_ASTC_8x8_UNORM_BLOCK;
1555 case QRhiTexture::ASTC_10x5:
1556 return srgb ? VK_FORMAT_ASTC_10x5_SRGB_BLOCK : VK_FORMAT_ASTC_10x5_UNORM_BLOCK;
1557 case QRhiTexture::ASTC_10x6:
1558 return srgb ? VK_FORMAT_ASTC_10x6_SRGB_BLOCK : VK_FORMAT_ASTC_10x6_UNORM_BLOCK;
1559 case QRhiTexture::ASTC_10x8:
1560 return srgb ? VK_FORMAT_ASTC_10x8_SRGB_BLOCK : VK_FORMAT_ASTC_10x8_UNORM_BLOCK;
1561 case QRhiTexture::ASTC_10x10:
1562 return srgb ? VK_FORMAT_ASTC_10x10_SRGB_BLOCK : VK_FORMAT_ASTC_10x10_UNORM_BLOCK;
1563 case QRhiTexture::ASTC_12x10:
1564 return srgb ? VK_FORMAT_ASTC_12x10_SRGB_BLOCK : VK_FORMAT_ASTC_12x10_UNORM_BLOCK;
1565 case QRhiTexture::ASTC_12x12:
1566 return srgb ? VK_FORMAT_ASTC_12x12_SRGB_BLOCK : VK_FORMAT_ASTC_12x12_UNORM_BLOCK;
1569 Q_UNREACHABLE_RETURN(VK_FORMAT_R8G8B8A8_UNORM);
1576 case VK_FORMAT_R8G8B8A8_UNORM:
1577 return QRhiTexture::RGBA8;
1578 case VK_FORMAT_R8G8B8A8_SRGB:
1580 (*flags) |= QRhiTexture::sRGB;
1581 return QRhiTexture::RGBA8;
1582 case VK_FORMAT_B8G8R8A8_UNORM:
1583 return QRhiTexture::BGRA8;
1584 case VK_FORMAT_B8G8R8A8_SRGB:
1586 (*flags) |= QRhiTexture::sRGB;
1587 return QRhiTexture::BGRA8;
1588 case VK_FORMAT_R16G16B16A16_SFLOAT:
1589 return QRhiTexture::RGBA16F;
1590 case VK_FORMAT_R32G32B32A32_SFLOAT:
1591 return QRhiTexture::RGBA32F;
1592 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
1593 return QRhiTexture::RGB10A2;
1595 qWarning(
"VkFormat %d cannot be read back", format);
1598 return QRhiTexture::UnknownFormat;
1604 case QRhiTexture::Format::D16:
1605 case QRhiTexture::Format::D24:
1606 case QRhiTexture::Format::D24S8:
1607 case QRhiTexture::Format::D32F:
1608 case QRhiTexture::Format::D32FS8:
1619 case QRhiTexture::Format::D24S8:
1620 case QRhiTexture::Format::D32FS8:
1630 if (isDepthTextureFormat(format)) {
1631 if (isStencilTextureFormat(format))
1632 return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
1634 return VK_IMAGE_ASPECT_DEPTH_BIT;
1636 return VK_IMAGE_ASPECT_COLOR_BIT;
1647 VkPhysicalDeviceMemoryProperties physDevMemProps;
1648 f->vkGetPhysicalDeviceMemoryProperties(physDev, &physDevMemProps);
1650 VkMemoryRequirements memReq;
1651 df->vkGetImageMemoryRequirements(dev, img, &memReq);
1652 uint32_t memTypeIndex = uint32_t(-1);
1654 if (memReq.memoryTypeBits) {
1656 const VkMemoryType *memType = physDevMemProps.memoryTypes;
1657 bool foundDevLocal =
false;
1658 for (uint32_t i = startIndex; i < physDevMemProps.memoryTypeCount; ++i) {
1659 if (memReq.memoryTypeBits & (1 << i)) {
1660 if (memType[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
1661 if (!foundDevLocal) {
1662 foundDevLocal =
true;
1665 if (memType[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
1674 return memTypeIndex;
1678 const QSize &pixelSize,
1679 VkImageUsageFlags usage,
1680 VkImageAspectFlags aspectMask,
1681 VkSampleCountFlagBits samples,
1682 VkDeviceMemory *mem,
1687 VkMemoryRequirements memReq;
1690 *mem = VK_NULL_HANDLE;
1691 for (
int i = 0; i < count; ++i) {
1692 images[i] = VK_NULL_HANDLE;
1693 views[i] = VK_NULL_HANDLE;
1696 auto cleanup = qScopeGuard([
this, mem, images, views, count] {
1697 for (
int i = 0; i < count; ++i) {
1699 df->vkDestroyImageView(dev, views[i],
nullptr);
1700 views[i] = VK_NULL_HANDLE;
1703 df->vkDestroyImage(dev, images[i],
nullptr);
1704 images[i] = VK_NULL_HANDLE;
1708 df->vkFreeMemory(dev, *mem,
nullptr);
1709 *mem = VK_NULL_HANDLE;
1713 for (
int i = 0; i < count; ++i) {
1714 VkImageCreateInfo imgInfo = {};
1715 imgInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1716 imgInfo.imageType = VK_IMAGE_TYPE_2D;
1717 imgInfo.format = format;
1718 imgInfo.extent.width = uint32_t(pixelSize.width());
1719 imgInfo.extent.height = uint32_t(pixelSize.height());
1720 imgInfo.extent.depth = 1;
1721 imgInfo.mipLevels = imgInfo.arrayLayers = 1;
1722 imgInfo.samples = samples;
1723 imgInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
1724 imgInfo.usage = usage | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
1725 imgInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1727 err =
df->vkCreateImage(dev, &imgInfo,
nullptr, images + i);
1728 if (err != VK_SUCCESS) {
1729 qWarning(
"Failed to create image: %d", err);
1736 df->vkGetImageMemoryRequirements(dev, images[i], &memReq);
1739 VkMemoryAllocateInfo memInfo = {};
1740 memInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1741 memInfo.allocationSize = aligned(memReq.size, memReq.alignment) * VkDeviceSize(count);
1743 uint32_t startIndex = 0;
1745 memInfo.memoryTypeIndex = chooseTransientImageMemType(images[0], startIndex);
1746 if (memInfo.memoryTypeIndex == uint32_t(-1)) {
1747 qWarning(
"No suitable memory type found");
1750 startIndex = memInfo.memoryTypeIndex + 1;
1751 err =
df->vkAllocateMemory(dev, &memInfo,
nullptr, mem);
1752 if (err != VK_SUCCESS && err != VK_ERROR_OUT_OF_DEVICE_MEMORY) {
1753 qWarning(
"Failed to allocate image memory: %d", err);
1756 }
while (err != VK_SUCCESS);
1758 VkDeviceSize ofs = 0;
1759 for (
int i = 0; i < count; ++i) {
1760 err =
df->vkBindImageMemory(dev, images[i], *mem, ofs);
1761 if (err != VK_SUCCESS) {
1762 qWarning(
"Failed to bind image memory: %d", err);
1765 ofs += aligned(memReq.size, memReq.alignment);
1767 VkImageViewCreateInfo imgViewInfo = {};
1768 imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1769 imgViewInfo.image = images[i];
1770 imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
1771 imgViewInfo.format = format;
1772 imgViewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
1773 imgViewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
1774 imgViewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
1775 imgViewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
1776 imgViewInfo.subresourceRange.aspectMask = aspectMask;
1777 imgViewInfo.subresourceRange.levelCount = imgViewInfo.subresourceRange.layerCount = 1;
1779 err =
df->vkCreateImageView(dev, &imgViewInfo,
nullptr, views + i);
1780 if (err != VK_SUCCESS) {
1781 qWarning(
"Failed to create image view: %d", err);
1792 if (optimalDsFormat != VK_FORMAT_UNDEFINED)
1793 return optimalDsFormat;
1795 const VkFormat dsFormatCandidates[] = {
1796 VK_FORMAT_D24_UNORM_S8_UINT,
1797 VK_FORMAT_D32_SFLOAT_S8_UINT,
1798 VK_FORMAT_D16_UNORM_S8_UINT
1800 const int dsFormatCandidateCount =
sizeof(dsFormatCandidates) /
sizeof(VkFormat);
1801 int dsFormatIdx = 0;
1802 while (dsFormatIdx < dsFormatCandidateCount) {
1803 optimalDsFormat = dsFormatCandidates[dsFormatIdx];
1804 VkFormatProperties fmtProp;
1805 f->vkGetPhysicalDeviceFormatProperties(physDev, optimalDsFormat, &fmtProp);
1806 if (fmtProp.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
1810 if (dsFormatIdx == dsFormatCandidateCount)
1811 qWarning(
"Failed to find an optimal depth-stencil format");
1813 return optimalDsFormat;
1818 bool prepare(VkRenderPassCreateInfo *rpInfo,
int multiViewCount,
bool multiViewCap)
1820 if (multiViewCount < 2)
1822 if (!multiViewCap) {
1823 qWarning(
"Cannot create multiview render pass without support for the Vulkan 1.1 multiview feature");
1826#ifdef VK_VERSION_1_1
1827 uint32_t allViewsMask = 0;
1828 for (uint32_t i = 0; i < uint32_t(multiViewCount); ++i)
1829 allViewsMask |= (1 << i);
1830 multiViewMask = allViewsMask;
1831 multiViewCorrelationMask = allViewsMask;
1832 multiViewInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO;
1833 multiViewInfo.subpassCount = 1;
1834 multiViewInfo.pViewMasks = &multiViewMask;
1835 multiViewInfo.correlationMaskCount = 1;
1836 multiViewInfo.pCorrelationMasks = &multiViewCorrelationMask;
1837 rpInfo->pNext = &multiViewInfo;
1842#ifdef VK_VERSION_1_1
1849#ifdef VK_KHR_create_renderpass2
1853struct RenderPass2SetupHelper
1855 RenderPass2SetupHelper(QRhiVulkan *rhiD) : rhiD(rhiD) { }
1857 bool prepare(VkRenderPassCreateInfo2 *rpInfo2,
const VkRenderPassCreateInfo *rpInfo,
const QVkRenderPassDescriptor *rpD,
int multiViewCount) {
1861 if (multiViewCount >= 2) {
1862 for (uint32_t i = 0; i < uint32_t(multiViewCount); ++i)
1863 viewMask |= (1 << i);
1866 attDescs2.resize(rpInfo->attachmentCount);
1867 for (qsizetype i = 0; i < attDescs2.count(); ++i) {
1868 VkAttachmentDescription2KHR &att2(attDescs2[i]);
1869 const VkAttachmentDescription &att(rpInfo->pAttachments[i]);
1871 att2.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2;
1872 att2.flags = att.flags;
1873 att2.format = att.format;
1874 att2.samples = att.samples;
1875 att2.loadOp = att.loadOp;
1876 att2.storeOp = att.storeOp;
1877 att2.stencilLoadOp = att.stencilLoadOp;
1878 att2.stencilStoreOp = att.stencilStoreOp;
1879 att2.initialLayout = att.initialLayout;
1880 att2.finalLayout = att.finalLayout;
1885 subpass2.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR;
1886 const VkSubpassDescription &subpassDesc(rpInfo->pSubpasses[0]);
1887 subpass2.flags = subpassDesc.flags;
1888 subpass2.pipelineBindPoint = subpassDesc.pipelineBindPoint;
1889 if (multiViewCount >= 2)
1890 subpass2.viewMask = viewMask;
1893 qsizetype startIndex = attRefs2.count();
1894 for (uint32_t j = 0; j < subpassDesc.colorAttachmentCount; ++j) {
1895 attRefs2.append({});
1896 VkAttachmentReference2KHR &attref2(attRefs2.last());
1897 const VkAttachmentReference &attref(subpassDesc.pColorAttachments[j]);
1898 attref2.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
1899 attref2.attachment = attref.attachment;
1900 attref2.layout = attref.layout;
1901 attref2.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1903 subpass2.colorAttachmentCount = subpassDesc.colorAttachmentCount;
1904 subpass2.pColorAttachments = attRefs2.constData() + startIndex;
1907 if (subpassDesc.pResolveAttachments) {
1908 startIndex = attRefs2.count();
1909 for (uint32_t j = 0; j < subpassDesc.colorAttachmentCount; ++j) {
1910 attRefs2.append({});
1911 VkAttachmentReference2KHR &attref2(attRefs2.last());
1912 const VkAttachmentReference &attref(subpassDesc.pResolveAttachments[j]);
1913 attref2.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
1914 attref2.attachment = attref.attachment;
1915 attref2.layout = attref.layout;
1916 attref2.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1918 subpass2.pResolveAttachments = attRefs2.constData() + startIndex;
1922 if (subpassDesc.pDepthStencilAttachment) {
1923 startIndex = attRefs2.count();
1924 attRefs2.append({});
1925 VkAttachmentReference2KHR &attref2(attRefs2.last());
1926 const VkAttachmentReference &attref(*subpassDesc.pDepthStencilAttachment);
1927 attref2.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
1928 attref2.attachment = attref.attachment;
1929 attref2.layout = attref.layout;
1930 attref2.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
1931 subpass2.pDepthStencilAttachment = attRefs2.constData() + startIndex;
1935#ifdef VK_KHR_depth_stencil_resolve
1937 if (rpD->hasDepthStencilResolve) {
1938 startIndex = attRefs2.count();
1939 attRefs2.append({});
1940 VkAttachmentReference2KHR &attref2(attRefs2.last());
1941 attref2.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
1942 attref2.attachment = rpD->dsResolveRef.attachment;
1943 attref2.layout = rpD->dsResolveRef.layout;
1944 attref2.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
1945 dsResolveDesc.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR;
1946 dsResolveDesc.depthResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT;
1947 dsResolveDesc.stencilResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT;
1948 dsResolveDesc.pDepthStencilResolveAttachment = attRefs2.constData() + startIndex;
1949 addToChain(&subpass2, &dsResolveDesc);
1953#ifdef VK_KHR_fragment_shading_rate
1954 shadingRateAttInfo = {};
1955 if (rpD->hasShadingRateMap) {
1956 startIndex = attRefs2.count();
1957 attRefs2.append({});
1958 VkAttachmentReference2KHR &attref2(attRefs2.last());
1959 attref2.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
1960 attref2.attachment = rpD->shadingRateRef.attachment;
1961 attref2.layout = rpD->shadingRateRef.layout;
1962 shadingRateAttInfo.sType = VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR;
1963 shadingRateAttInfo.pFragmentShadingRateAttachment = attRefs2.constData() + startIndex;
1964 shadingRateAttInfo.shadingRateAttachmentTexelSize.width = rhiD->caps.imageBasedShadingRateTileSize;
1965 shadingRateAttInfo.shadingRateAttachmentTexelSize.height = rhiD->caps.imageBasedShadingRateTileSize;
1966 addToChain(&subpass2, &shadingRateAttInfo);
1972 subpassDeps2.clear();
1973 for (uint32_t i = 0; i < rpInfo->dependencyCount; ++i) {
1974 const VkSubpassDependency &dep(rpInfo->pDependencies[i]);
1975 subpassDeps2.append({});
1976 VkSubpassDependency2 &dep2(subpassDeps2.last());
1977 dep2.sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2_KHR;
1978 dep2.srcSubpass = dep.srcSubpass;
1979 dep2.dstSubpass = dep.dstSubpass;
1980 dep2.srcStageMask = dep.srcStageMask;
1981 dep2.dstStageMask = dep.dstStageMask;
1982 dep2.srcAccessMask = dep.srcAccessMask;
1983 dep2.dstAccessMask = dep.dstAccessMask;
1984 dep2.dependencyFlags = dep.dependencyFlags;
1987 rpInfo2->sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR;
1988 rpInfo2->pNext =
nullptr;
1989 rpInfo2->flags = rpInfo->flags;
1990 rpInfo2->attachmentCount = rpInfo->attachmentCount;
1991 rpInfo2->pAttachments = attDescs2.constData();
1992 rpInfo2->subpassCount = 1;
1993 rpInfo2->pSubpasses = &subpass2;
1994 rpInfo2->dependencyCount = subpassDeps2.count();
1995 rpInfo2->pDependencies = !subpassDeps2.isEmpty() ? subpassDeps2.constData() :
nullptr;
1996 if (multiViewCount >= 2) {
1997 rpInfo2->correlatedViewMaskCount = 1;
1998 rpInfo2->pCorrelatedViewMasks = &viewMask;
2004 QVarLengthArray<VkAttachmentDescription2KHR, 8> attDescs2;
2005 QVarLengthArray<VkAttachmentReference2KHR, 8> attRefs2;
2006 VkSubpassDescription2KHR subpass2;
2007 QVarLengthArray<VkSubpassDependency2KHR, 4> subpassDeps2;
2008#ifdef VK_KHR_depth_stencil_resolve
2009 VkSubpassDescriptionDepthStencilResolveKHR dsResolveDesc;
2011#ifdef VK_KHR_fragment_shading_rate
2012 VkFragmentShadingRateAttachmentInfoKHR shadingRateAttInfo;
2019 VkSubpassDescription *subpassDesc,
2022 memset(subpassDesc, 0,
sizeof(VkSubpassDescription));
2023 subpassDesc->pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
2024 subpassDesc->colorAttachmentCount = uint32_t(rpD->colorRefs.size());
2025 subpassDesc->pColorAttachments = !rpD->colorRefs.isEmpty() ? rpD->colorRefs.constData() :
nullptr;
2026 subpassDesc->pDepthStencilAttachment = rpD
->hasDepthStencil ? &rpD->dsRef :
nullptr;
2027 subpassDesc->pResolveAttachments = !rpD->resolveRefs.isEmpty() ? rpD->resolveRefs.constData() :
nullptr;
2029 memset(rpInfo, 0,
sizeof(VkRenderPassCreateInfo));
2030 rpInfo->sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
2031 rpInfo->attachmentCount = uint32_t(rpD->attDescs.size());
2032 rpInfo->pAttachments = rpD->attDescs.constData();
2033 rpInfo->subpassCount = 1;
2034 rpInfo->pSubpasses = subpassDesc;
2035 rpInfo->dependencyCount = uint32_t(rpD->subpassDeps.size());
2036 rpInfo->pDependencies = !rpD->subpassDeps.isEmpty() ? rpD->subpassDeps.constData() :
nullptr;
2042 VkSubpassDependency selfDependency = {};
2043 VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT
2044 | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT
2045 | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT
2046 | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
2047 selfDependency.srcSubpass = 0;
2048 selfDependency.dstSubpass = 0;
2049 selfDependency.srcStageMask = stageMask;
2050 selfDependency.dstStageMask = stageMask;
2051 selfDependency.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
2052 selfDependency.dstAccessMask = selfDependency.srcAccessMask;
2053 VkDependencyFlags depFlags = VK_DEPENDENCY_BY_REGION_BIT;
2054#ifdef VK_VERSION_1_1
2055 if (rpD->multiViewCount >= 2)
2056 depFlags |= VK_DEPENDENCY_VIEW_LOCAL_BIT;
2058 selfDependency.dependencyFlags = depFlags;
2059 rpD->subpassDeps.append(selfDependency);
2063 bool hasDepthStencil,
2064 VkSampleCountFlagBits samples,
2065 VkFormat colorFormat,
2066 QRhiShadingRateMap *shadingRateMap)
2070 VkAttachmentDescription attDesc = {};
2071 attDesc.format = colorFormat;
2072 attDesc.samples = samples;
2073 attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
2074 attDesc.storeOp = samples > VK_SAMPLE_COUNT_1_BIT ? VK_ATTACHMENT_STORE_OP_DONT_CARE : VK_ATTACHMENT_STORE_OP_STORE;
2075 attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
2076 attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2077 attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
2078 attDesc.finalLayout = samples > VK_SAMPLE_COUNT_1_BIT ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
2079 rpD->attDescs.append(attDesc);
2081 rpD->colorRefs.append({ 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL });
2086 rpD->multiViewCount = 0;
2088 if (hasDepthStencil) {
2092 attDesc.format = optimalDepthStencilFormat();
2093 attDesc.samples = samples;
2094 attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
2095 attDesc.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2096 attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
2097 attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2098 attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
2099 attDesc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
2100 rpD->attDescs.append(attDesc);
2102 rpD->dsRef = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
2107 if (samples > VK_SAMPLE_COUNT_1_BIT) {
2109 attDesc.format = colorFormat;
2110 attDesc.samples = VK_SAMPLE_COUNT_1_BIT;
2111 attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
2112 attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
2113 attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
2114 attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2115 attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
2116 attDesc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
2117 rpD->attDescs.append(attDesc);
2119 rpD->resolveRefs.append({ uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL });
2122 rpD->dsResolveRef = {};
2124 rpD->shadingRateRef = {};
2125#ifdef VK_KHR_fragment_shading_rate
2126 if (shadingRateMap) {
2128 attDesc.format = VK_FORMAT_R8_UINT;
2129 attDesc.samples = VK_SAMPLE_COUNT_1_BIT;
2130 attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
2131 attDesc.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2132 attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
2133 attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2134 attDesc.initialLayout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR;
2135 attDesc.finalLayout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR;
2136 rpD->attDescs.append(attDesc);
2138 rpD->shadingRateRef = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR };
2143 VkSubpassDependency subpassDep = {};
2144 subpassDep.srcSubpass = VK_SUBPASS_EXTERNAL;
2145 subpassDep.dstSubpass = 0;
2146 subpassDep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
2147 subpassDep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
2148 subpassDep.srcAccessMask = 0;
2149 subpassDep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
2150 rpD->subpassDeps.append(subpassDep);
2151 if (hasDepthStencil) {
2152 memset(&subpassDep, 0,
sizeof(subpassDep));
2153 subpassDep.srcSubpass = VK_SUBPASS_EXTERNAL;
2154 subpassDep.dstSubpass = 0;
2155 subpassDep.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT
2156 | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
2157 subpassDep.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT
2158 | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
2159 subpassDep.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
2160 subpassDep.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT
2161 | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
2162 rpD->subpassDeps.append(subpassDep);
2167 VkRenderPassCreateInfo rpInfo;
2168 VkSubpassDescription subpassDesc;
2169 fillRenderPassCreateInfo(&rpInfo, &subpassDesc, rpD);
2171#ifdef VK_KHR_create_renderpass2
2172 if (caps.renderPass2KHR) {
2174 VkRenderPassCreateInfo2KHR rpInfo2;
2175 RenderPass2SetupHelper rp2Helper(
this);
2176 if (!rp2Helper.prepare(&rpInfo2, &rpInfo, rpD, 0))
2178 VkResult err = vkCreateRenderPass2KHR(dev, &rpInfo2,
nullptr, &rpD->rp);
2179 if (err != VK_SUCCESS) {
2180 qWarning(
"Failed to create renderpass (using VkRenderPassCreateInfo2KHR): %d", err);
2187 qWarning(
"Variable rate shading with image is not supported without VK_KHR_create_renderpass2");
2188 VkResult err =
df->vkCreateRenderPass(dev, &rpInfo,
nullptr, &rpD->rp);
2189 if (err != VK_SUCCESS) {
2190 qWarning(
"Failed to create renderpass: %d", err);
2199 const QRhiColorAttachment *colorAttachmentsBegin,
2200 const QRhiColorAttachment *colorAttachmentsEnd,
2204 QRhiRenderBuffer *depthStencilBuffer,
2205 QRhiTexture *depthTexture,
2206 QRhiTexture *depthResolveTexture,
2208 QRhiShadingRateMap *shadingRateMap)
2212 int multiViewCount = 0;
2213 for (
auto it = colorAttachmentsBegin; it != colorAttachmentsEnd; ++it) {
2216 Q_ASSERT(texD || rbD);
2217 const VkFormat vkformat = texD ? texD->viewFormat : rbD->vkformat;
2218 const VkSampleCountFlagBits samples = texD ? texD->samples : rbD->samples;
2220 VkAttachmentDescription attDesc = {};
2221 attDesc.format = vkformat;
2222 attDesc.samples = samples;
2223 attDesc.loadOp = preserveColor ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_CLEAR;
2224 attDesc.storeOp = (it->resolveTexture() && !preserveColor) ? VK_ATTACHMENT_STORE_OP_DONT_CARE : VK_ATTACHMENT_STORE_OP_STORE;
2225 attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
2226 attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2228 attDesc.initialLayout = preserveColor ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_UNDEFINED;
2229 attDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
2230 rpD->attDescs.append(attDesc);
2232 const VkAttachmentReference ref = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
2233 rpD->colorRefs.append(ref);
2235 if (it->multiViewCount() >= 2) {
2236 if (multiViewCount > 0 && multiViewCount != it->multiViewCount())
2237 qWarning(
"Inconsistent multiViewCount in color attachment set");
2239 multiViewCount = it->multiViewCount();
2240 }
else if (multiViewCount > 0) {
2241 qWarning(
"Mixing non-multiview color attachments within a multiview render pass");
2244 Q_ASSERT(multiViewCount == 0 || multiViewCount >= 2);
2245 rpD->multiViewCount = uint32_t(multiViewCount);
2249 const VkFormat dsFormat = depthTexture ?
QRHI_RES(QVkTexture, depthTexture)->viewFormat
2250 :
QRHI_RES(QVkRenderBuffer, depthStencilBuffer)->vkformat;
2251 const VkSampleCountFlagBits samples = depthTexture ?
QRHI_RES(QVkTexture, depthTexture)->samples
2252 :
QRHI_RES(QVkRenderBuffer, depthStencilBuffer)->samples;
2253 const VkAttachmentLoadOp loadOp = preserveDs ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_CLEAR;
2254 const VkAttachmentStoreOp storeOp = storeDs ? VK_ATTACHMENT_STORE_OP_STORE : VK_ATTACHMENT_STORE_OP_DONT_CARE;
2255 VkAttachmentDescription attDesc = {};
2256 attDesc.format = dsFormat;
2257 attDesc.samples = samples;
2258 attDesc.loadOp = loadOp;
2259 attDesc.storeOp = storeOp;
2260 attDesc.stencilLoadOp = loadOp;
2261 attDesc.stencilStoreOp = storeOp;
2262 attDesc.initialLayout = preserveDs ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_UNDEFINED;
2263 attDesc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
2264 rpD->attDescs.append(attDesc);
2265 if (depthTexture && depthTexture->arraySize() >= 2 && depthLayer == -1 && colorAttachmentsBegin == colorAttachmentsEnd) {
2266 multiViewCount = depthTexture->arraySize();
2267 rpD->multiViewCount = multiViewCount;
2269 rpD->dsRef = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
2274 for (
auto it = colorAttachmentsBegin; it != colorAttachmentsEnd; ++it) {
2275 if (it->resolveTexture()) {
2277 const VkFormat dstFormat = rtexD->vkformat;
2278 if (rtexD->samples > VK_SAMPLE_COUNT_1_BIT)
2279 qWarning(
"Resolving into a multisample texture is not supported");
2283 const VkFormat srcFormat = texD ? texD->vkformat : rbD->vkformat;
2284 if (srcFormat != dstFormat) {
2288 qWarning(
"Multisample resolve between different formats (%d and %d) is not supported.",
2289 int(srcFormat),
int(dstFormat));
2292 VkAttachmentDescription attDesc = {};
2293 attDesc.format = rtexD->viewFormat;
2294 attDesc.samples = VK_SAMPLE_COUNT_1_BIT;
2295 attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
2296 attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
2297 attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
2298 attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2299 attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
2300 attDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
2301 rpD->attDescs.append(attDesc);
2303 const VkAttachmentReference ref = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
2304 rpD->resolveRefs.append(ref);
2306 const VkAttachmentReference ref = { VK_ATTACHMENT_UNUSED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
2307 rpD->resolveRefs.append(ref);
2310 Q_ASSERT(rpD->colorRefs.size() == rpD->resolveRefs.size());
2315 if (rtexD->samples > VK_SAMPLE_COUNT_1_BIT)
2316 qWarning(
"Resolving into a multisample depth texture is not supported");
2317 const VkFormat dstFormat = rtexD->vkformat;
2321 Q_ASSERT(texD || rbD);
2322 const VkFormat srcFormat = texD ? texD->vkformat : rbD->vkformat;
2323 if (srcFormat != dstFormat) {
2324 qWarning(
"Multisample resolve between different depth-stencil formats (%d and %d) is not supported.",
2325 int(srcFormat),
int(dstFormat));
2328 VkAttachmentDescription attDesc = {};
2329 attDesc.format = rtexD->viewFormat;
2330 attDesc.samples = VK_SAMPLE_COUNT_1_BIT;
2331 attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
2332 attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
2333 attDesc.stencilLoadOp = attDesc.loadOp;
2334 attDesc.stencilStoreOp = attDesc.storeOp;
2335 attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
2336 attDesc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
2337 rpD->attDescs.append(attDesc);
2338 rpD->dsResolveRef = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
2340 rpD->dsResolveRef = {};
2344 rpD->shadingRateRef = {};
2345#ifdef VK_KHR_fragment_shading_rate
2346 if (shadingRateMap) {
2347 VkAttachmentDescription attDesc = {};
2348 attDesc.format = VK_FORMAT_R8_UINT;
2349 attDesc.samples = VK_SAMPLE_COUNT_1_BIT;
2350 attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
2351 attDesc.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2352 attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
2353 attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
2354 attDesc.initialLayout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR;
2355 attDesc.finalLayout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR;
2356 rpD->attDescs.append(attDesc);
2357 rpD->shadingRateRef = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR };
2371 VkSubpassDependency subpassDep = {};
2372 subpassDep.srcSubpass = VK_SUBPASS_EXTERNAL;
2373 subpassDep.dstSubpass = 0;
2376 subpassDep.srcStageMask |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
2377 subpassDep.srcAccessMask |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
2378 subpassDep.dstAccessMask |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
2381 subpassDep.srcStageMask |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT
2382 | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
2383 subpassDep.srcAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
2384 subpassDep.dstAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
2386 if (subpassDep.srcStageMask) {
2387 subpassDep.dstStageMask = subpassDep.srcStageMask;
2388 subpassDep.dstAccessMask |= subpassDep.srcAccessMask;
2389 rpD->subpassDeps.append(subpassDep);
2394 VkRenderPassCreateInfo rpInfo;
2395 VkSubpassDescription subpassDesc;
2396 fillRenderPassCreateInfo(&rpInfo, &subpassDesc, rpD);
2399 if (!multiViewHelper.prepare(&rpInfo, multiViewCount, caps.multiView))
2402#ifdef VK_KHR_create_renderpass2
2403 if (caps.renderPass2KHR) {
2405 VkRenderPassCreateInfo2KHR rpInfo2;
2406 RenderPass2SetupHelper rp2Helper(
this);
2407 if (!rp2Helper.prepare(&rpInfo2, &rpInfo, rpD, multiViewCount))
2410 VkResult err = vkCreateRenderPass2KHR(dev, &rpInfo2,
nullptr, &rpD->rp);
2411 if (err != VK_SUCCESS) {
2412 qWarning(
"Failed to create renderpass (using VkRenderPassCreateInfo2KHR): %d", err);
2419 qWarning(
"Resolving multisample depth-stencil buffers is not supported without "
2420 "VK_KHR_depth_stencil_resolve and VK_KHR_create_renderpass2");
2423 qWarning(
"Variable rate shading with image is not supported without VK_KHR_create_renderpass2");
2424 VkResult err =
df->vkCreateRenderPass(dev, &rpInfo,
nullptr, &rpD->rp);
2425 if (err != VK_SUCCESS) {
2426 qWarning(
"Failed to create renderpass: %d", err);
2437 if (swapChainD->pixelSize.isEmpty()) {
2438 qWarning(
"Surface size is 0, cannot create swapchain");
2443 df->vkQueueWaitIdle(gfxQueue);
2445 if (!vkCreateSwapchainKHR) {
2446 vkCreateSwapchainKHR =
reinterpret_cast<PFN_vkCreateSwapchainKHR>(f->vkGetDeviceProcAddr(dev,
"vkCreateSwapchainKHR"));
2447 vkDestroySwapchainKHR =
reinterpret_cast<PFN_vkDestroySwapchainKHR>(f->vkGetDeviceProcAddr(dev,
"vkDestroySwapchainKHR"));
2448 vkGetSwapchainImagesKHR =
reinterpret_cast<PFN_vkGetSwapchainImagesKHR>(f->vkGetDeviceProcAddr(dev,
"vkGetSwapchainImagesKHR"));
2449 vkAcquireNextImageKHR =
reinterpret_cast<PFN_vkAcquireNextImageKHR>(f->vkGetDeviceProcAddr(dev,
"vkAcquireNextImageKHR"));
2450 vkQueuePresentKHR =
reinterpret_cast<PFN_vkQueuePresentKHR>(f->vkGetDeviceProcAddr(dev,
"vkQueuePresentKHR"));
2451 if (!vkCreateSwapchainKHR || !vkDestroySwapchainKHR || !vkGetSwapchainImagesKHR || !vkAcquireNextImageKHR || !vkQueuePresentKHR) {
2452 qWarning(
"Swapchain functions not available");
2457 VkSurfaceCapabilitiesKHR surfaceCaps;
2458 vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physDev, swapChainD->surface, &surfaceCaps);
2459 quint32 reqBufferCount;
2460 if (swapChainD->m_flags.testFlag(QRhiSwapChain::MinimalBufferCount) || surfaceCaps.maxImageCount == 0) {
2461 reqBufferCount = qMax<quint32>(2, surfaceCaps.minImageCount);
2463 reqBufferCount = qMax(qMin<quint32>(surfaceCaps.maxImageCount, 3), surfaceCaps.minImageCount);
2465 VkSurfaceTransformFlagBitsKHR preTransform =
2466 (surfaceCaps.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
2467 ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR
2468 : surfaceCaps.currentTransform;
2494 VkCompositeAlphaFlagBitsKHR compositeAlpha =
2495 (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR)
2496 ? VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR
2497 : VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
2499 if (swapChainD->m_flags.testFlag(QRhiSwapChain::SurfaceHasPreMulAlpha)) {
2500 if (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR)
2501 compositeAlpha = VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
2502 else if (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR)
2503 compositeAlpha = VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR;
2504 }
else if (swapChainD->m_flags.testFlag(QRhiSwapChain::SurfaceHasNonPreMulAlpha)) {
2505 if (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR)
2506 compositeAlpha = VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR;
2507 else if (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR)
2508 compositeAlpha = VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
2511 VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
2512 swapChainD
->supportsReadback = (surfaceCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
2513 if (swapChainD
->supportsReadback && swapChainD->m_flags.testFlag(QRhiSwapChain::UsedAsTransferSource))
2514 usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
2516 const bool stereo =
bool(swapChainD->m_window) && (swapChainD->m_window->format().stereo())
2517 && surfaceCaps.maxImageArrayLayers > 1;
2520 VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
2521 if (swapChainD->m_flags.testFlag(QRhiSwapChain::NoVSync)) {
2525 if (swapChainD->supportedPresentationModes.contains(VK_PRESENT_MODE_MAILBOX_KHR) && !stereo)
2526 presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
2527 else if (swapChainD->supportedPresentationModes.contains(VK_PRESENT_MODE_IMMEDIATE_KHR))
2528 presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
2536 const bool reuseExisting = swapChainD->sc && swapChainD->lastConnectedSurface == swapChainD->surface;
2538 qCDebug(QRHI_LOG_INFO,
"Creating %s swapchain of %u buffers, size %dx%d, presentation mode %d",
2539 reuseExisting ?
"recycled" :
"new",
2540 reqBufferCount, swapChainD->pixelSize.width(), swapChainD->pixelSize.height(), presentMode);
2542 VkSwapchainCreateInfoKHR swapChainInfo = {};
2543 swapChainInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
2544 swapChainInfo.surface = swapChainD->surface;
2545 swapChainInfo.minImageCount = reqBufferCount;
2546 swapChainInfo.imageFormat = swapChainD->colorFormat;
2547 swapChainInfo.imageColorSpace = swapChainD->colorSpace;
2548 swapChainInfo.imageExtent = VkExtent2D { uint32_t(swapChainD->pixelSize.width()), uint32_t(swapChainD->pixelSize.height()) };
2549 swapChainInfo.imageArrayLayers = stereo ? 2u : 1u;
2550 swapChainInfo.imageUsage = usage;
2551 swapChainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
2552 swapChainInfo.preTransform = preTransform;
2553 swapChainInfo.compositeAlpha = compositeAlpha;
2554 swapChainInfo.presentMode = presentMode;
2555 swapChainInfo.clipped =
true;
2556 swapChainInfo.oldSwapchain = reuseExisting ? swapChainD->sc : VK_NULL_HANDLE;
2558 VkSwapchainKHR newSwapChain;
2559 VkResult err = vkCreateSwapchainKHR(dev, &swapChainInfo,
nullptr, &newSwapChain);
2560 if (err != VK_SUCCESS) {
2561 qWarning(
"Failed to create swapchain: %d", err);
2564 setObjectName(uint64_t(newSwapChain), VK_OBJECT_TYPE_SWAPCHAIN_KHR, swapChainD->m_objectName);
2569 swapChainD->sc = newSwapChain;
2570 swapChainD->lastConnectedSurface = swapChainD->surface;
2572 quint32 actualSwapChainBufferCount = 0;
2573 err = vkGetSwapchainImagesKHR(dev, swapChainD->sc, &actualSwapChainBufferCount,
nullptr);
2574 if (err != VK_SUCCESS || actualSwapChainBufferCount == 0) {
2575 qWarning(
"Failed to get swapchain images: %d", err);
2579 if (actualSwapChainBufferCount != reqBufferCount)
2580 qCDebug(QRHI_LOG_INFO,
"Actual swapchain buffer count is %u", actualSwapChainBufferCount);
2583 QVarLengthArray<VkImage, QVkSwapChain::EXPECTED_MAX_BUFFER_COUNT> swapChainImages(actualSwapChainBufferCount);
2584 err = vkGetSwapchainImagesKHR(dev, swapChainD->sc, &actualSwapChainBufferCount, swapChainImages.data());
2585 if (err != VK_SUCCESS) {
2586 qWarning(
"Failed to get swapchain images: %d", err);
2590 QVarLengthArray<VkImage, QVkSwapChain::EXPECTED_MAX_BUFFER_COUNT> msaaImages(swapChainD->bufferCount);
2591 QVarLengthArray<VkImageView, QVkSwapChain::EXPECTED_MAX_BUFFER_COUNT> msaaViews(swapChainD->bufferCount);
2592 if (swapChainD->samples > VK_SAMPLE_COUNT_1_BIT) {
2593 if (!createTransientImage(swapChainD->colorFormat,
2594 swapChainD->pixelSize,
2595 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
2596 VK_IMAGE_ASPECT_COLOR_BIT,
2597 swapChainD->samples,
2598 &swapChainD->msaaImageMem,
2601 swapChainD->bufferCount))
2603 qWarning(
"Failed to create transient image for MSAA color buffer");
2608 VkFenceCreateInfo fenceInfo = {};
2609 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
2610 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
2613 swapChainD->imageRes.resize(swapChainD
->bufferCount * (stereo ? 2u : 1u));
2617 image.image = swapChainImages[i];
2618 if (swapChainD->samples > VK_SAMPLE_COUNT_1_BIT) {
2619 image.msaaImage = msaaImages[i];
2620 image.msaaImageView = msaaViews[i];
2623 VkImageViewCreateInfo imgViewInfo = {};
2624 imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
2625 imgViewInfo.image = swapChainImages[i];
2626 imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
2627 imgViewInfo.format = swapChainD->colorFormat;
2628 imgViewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
2629 imgViewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
2630 imgViewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
2631 imgViewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
2632 imgViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2633 imgViewInfo.subresourceRange.levelCount = imgViewInfo.subresourceRange.layerCount = 1;
2634 err =
df->vkCreateImageView(dev, &imgViewInfo,
nullptr, &image.imageView);
2635 if (err != VK_SUCCESS) {
2636 qWarning(
"Failed to create swapchain image view %d: %d", i, err);
2642 VkSemaphoreCreateInfo semInfo = {};
2643 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
2644 df->vkCreateSemaphore(dev, &semInfo,
nullptr, &image.drawSem);
2649 image.image = swapChainImages[i];
2650 if (swapChainD->samples > VK_SAMPLE_COUNT_1_BIT) {
2651 image.msaaImage = msaaImages[i];
2652 image.msaaImageView = msaaViews[i];
2655 VkImageViewCreateInfo imgViewInfo = {};
2656 imgViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
2657 imgViewInfo.image = swapChainImages[i];
2658 imgViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
2659 imgViewInfo.format = swapChainD->colorFormat;
2660 imgViewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
2661 imgViewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
2662 imgViewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
2663 imgViewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
2664 imgViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2665 imgViewInfo.subresourceRange.baseArrayLayer = 1;
2666 imgViewInfo.subresourceRange.levelCount = imgViewInfo.subresourceRange.layerCount = 1;
2667 err =
df->vkCreateImageView(dev, &imgViewInfo,
nullptr, &image.imageView);
2668 if (err != VK_SUCCESS) {
2669 qWarning(
"Failed to create swapchain image view %d: %d", i, err);
2673 VkSemaphoreCreateInfo semInfo = {};
2674 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
2675 df->vkCreateSemaphore(dev, &semInfo,
nullptr, &image.drawSem);
2681 swapChainD->currentImageIndex = 0;
2683 if (swapChainD->shadingRateMap() && caps.renderPass2KHR && caps.imageBasedShadingRate) {
2685 Q_ASSERT(texD->flags().testFlag(QRhiTexture::UsedAsShadingRateMap));
2686 VkImageViewCreateInfo viewInfo = {};
2687 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
2688 viewInfo.image = texD->image;
2689 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
2690 viewInfo.format = texD->viewFormat;
2691 viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
2692 viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
2693 viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
2694 viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
2695 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2696 viewInfo.subresourceRange.baseMipLevel = 0;
2697 viewInfo.subresourceRange.levelCount = 1;
2698 viewInfo.subresourceRange.baseArrayLayer = 0;
2699 viewInfo.subresourceRange.layerCount = 1;
2700 VkResult err =
df->vkCreateImageView(dev, &viewInfo,
nullptr, &swapChainD->shadingRateMapView);
2701 if (err != VK_SUCCESS) {
2702 qWarning(
"Failed to create swapchain shading rate map view: %d", err);
2707 VkSemaphoreCreateInfo semInfo = {};
2708 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
2716 df->vkCreateSemaphore(dev, &semInfo,
nullptr, &frame.imageSem);
2718 err =
df->vkCreateFence(dev, &fenceInfo,
nullptr, &frame.cmdFence);
2719 if (err != VK_SUCCESS) {
2720 qWarning(
"Failed to create command buffer fence: %d", err);
2733 if (swapChainD->sc == VK_NULL_HANDLE)
2737 df->vkQueueWaitIdle(gfxQueue);
2741 if (frame.cmdFence) {
2743 df->vkWaitForFences(dev, 1, &frame.cmdFence, VK_TRUE, UINT64_MAX);
2744 df->vkDestroyFence(dev, frame.cmdFence,
nullptr);
2745 frame.cmdFence = VK_NULL_HANDLE;
2748 if (frame.imageSem) {
2749 df->vkDestroySemaphore(dev, frame.imageSem,
nullptr);
2750 frame.imageSem = VK_NULL_HANDLE;
2757 df->vkDestroyFramebuffer(dev, image.fb,
nullptr);
2758 image.fb = VK_NULL_HANDLE;
2760 if (image.imageView) {
2761 df->vkDestroyImageView(dev, image.imageView,
nullptr);
2762 image.imageView = VK_NULL_HANDLE;
2764 if (image.msaaImageView) {
2765 df->vkDestroyImageView(dev, image.msaaImageView,
nullptr);
2766 image.msaaImageView = VK_NULL_HANDLE;
2768 if (image.msaaImage) {
2769 df->vkDestroyImage(dev, image.msaaImage,
nullptr);
2770 image.msaaImage = VK_NULL_HANDLE;
2772 if (image.drawSem) {
2773 df->vkDestroySemaphore(dev, image.drawSem,
nullptr);
2774 image.drawSem = VK_NULL_HANDLE;
2778 if (swapChainD->msaaImageMem) {
2779 df->vkFreeMemory(dev, swapChainD->msaaImageMem,
nullptr);
2780 swapChainD->msaaImageMem = VK_NULL_HANDLE;
2783 if (swapChainD->shadingRateMapView) {
2784 df->vkDestroyImageView(dev, swapChainD->shadingRateMapView,
nullptr);
2785 swapChainD->shadingRateMapView = VK_NULL_HANDLE;
2788 vkDestroySwapchainKHR(dev, swapChainD->sc,
nullptr);
2789 swapChainD->sc = VK_NULL_HANDLE;
2796 VkCommandPoolResetFlags flags = 0;
2802 flags |= VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT;
2805 df->vkResetCommandPool(dev, cmdPool[currentFrameSlot], flags);
2811 for (quint64 i = 0; i < timestampValidBits; i += 8)
2812 mask |= 0xFFULL << i;
2813 const quint64 ts0 = timestamp[0] & mask;
2814 const quint64 ts1 = timestamp[1] & mask;
2815 const float nsecsPerTick = physDevProperties.limits.timestampPeriod;
2816 if (!qFuzzyIsNull(nsecsPerTick)) {
2817 const float elapsedMs =
float(ts1 - ts0) * nsecsPerTick / 1000000.0f;
2818 const double elapsedSec = elapsedMs / 1000.0;
2829 const int frameResIndex = swapChainD->bufferCount > 1 ? currentFrameSlot : 0;
2832 inst->handle()->beginFrame(swapChainD->window);
2833 auto instEndFrameOnErrorGuard = qScopeGuard([
this, swapChainD] {
2834 inst->handle()->endFrame(swapChainD->window);
2845 QRhi::FrameOpResult waitResult = waitCommandCompletion(frameResIndex);
2846 if (waitResult != QRhi::FrameOpSuccess)
2851 uint32_t imageIndex = 0;
2852 VkResult err = vkAcquireNextImageKHR(dev, swapChainD->sc, UINT64_MAX,
2853 frame.imageSem, VK_NULL_HANDLE, &imageIndex);
2855 if (err == VK_SUCCESS || err == VK_SUBOPTIMAL_KHR) {
2856 swapChainD->currentImageIndex = imageIndex;
2859 }
else if (err == VK_ERROR_OUT_OF_DATE_KHR) {
2860 return QRhi::FrameOpSwapChainOutOfDate;
2862 if (err == VK_ERROR_DEVICE_LOST) {
2863 qWarning(
"Device loss detected in vkAcquireNextImageKHR()");
2864 printExtraErrorInfo(err);
2866 return QRhi::FrameOpDeviceLost;
2868 qWarning(
"Failed to acquire next swapchain image: %d", err);
2869 return QRhi::FrameOpError;
2881 QRhi::FrameOpResult cbres = startPrimaryCommandBuffer(&frame.cmdBuf);
2882 if (cbres != QRhi::FrameOpSuccess)
2885 swapChainD->cbWrapper.cb = frame.cmdBuf;
2888 swapChainD->rtWrapper.d.fb = image.fb;
2892 swapChainD->imageRes[swapChainD->currentImageIndex + swapChainD
->bufferCount]);
2893 swapChainD->rtWrapperRight.d.fb = image.fb;
2900 quint64 timestamp[2] = { 0, 0 };
2901 VkResult err =
df->vkGetQueryPoolResults(dev, timestampQueryPool, uint32_t(frame
.timestampQueryIndex), 2,
2902 2 *
sizeof(quint64), timestamp,
sizeof(quint64),
2903 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
2904 timestampQueryPoolMap.clearBit(frame.timestampQueryIndex / 2);
2906 if (err == VK_SUCCESS) {
2908 const double elapsedSec = elapsedSecondsFromTimestamp(timestamp, &ok);
2910 swapChainD->cbWrapper.lastGpuTime = elapsedSec;
2912 qWarning(
"Failed to query timestamp: %d", err);
2917 if (rhiFlags.testFlag(QRhi::EnableTimestamps) && swapChainD->bufferCount > 1) {
2918 int timestampQueryIdx = -1;
2919 for (
int i = 0; i < timestampQueryPoolMap.size(); ++i) {
2920 if (!timestampQueryPoolMap.testBit(i)) {
2921 timestampQueryPoolMap.setBit(i);
2922 timestampQueryIdx = i * 2;
2926 if (timestampQueryIdx >= 0) {
2927 df->vkCmdResetQueryPool(frame.cmdBuf, timestampQueryPool, uint32_t(timestampQueryIdx), 2);
2929 df->vkCmdWriteTimestamp(frame.cmdBuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2930 timestampQueryPool, uint32_t(timestampQueryIdx));
2935 instEndFrameOnErrorGuard.dismiss();
2936 return QRhi::FrameOpSuccess;
2944 auto cleanup = qScopeGuard([
this, swapChainD] {
2945 inst->handle()->endFrame(swapChainD->window);
2950 int frameResIndex = swapChainD->bufferCount > 1 ? currentFrameSlot : 0;
2955 VkImageMemoryBarrier presTrans = {};
2956 presTrans.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
2957 presTrans.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
2958 presTrans.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
2959 presTrans.image = image.image;
2960 presTrans.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2961 presTrans.subresourceRange.levelCount = presTrans.subresourceRange.layerCount = 1;
2965 presTrans.srcAccessMask = 0;
2966 presTrans.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
2967 df->vkCmdPipelineBarrier(frame.cmdBuf,
2968 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
2969 0, 0,
nullptr, 0,
nullptr,
2973 presTrans.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
2974 presTrans.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
2975 df->vkCmdPipelineBarrier(frame.cmdBuf,
2976 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
2977 0, 0,
nullptr, 0,
nullptr,
2985 df->vkCmdWriteTimestamp(frame.cmdBuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2991 const bool needsPresent = !flags.testFlag(QRhi::SkipPresent);
2992 QRhi::FrameOpResult submitres = endAndSubmitPrimaryCommandBuffer(frame.cmdBuf,
2994 frame.imageSemWaitable ? &frame.imageSem :
nullptr,
2995 needsPresent ? &image.drawSem :
nullptr);
2996 if (submitres != QRhi::FrameOpSuccess)
3004 VkPresentInfoKHR presInfo = {};
3005 presInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
3006 presInfo.swapchainCount = 1;
3007 presInfo.pSwapchains = &swapChainD->sc;
3008 presInfo.pImageIndices = &swapChainD->currentImageIndex;
3009 waitSemaphoresForPresent.append(image.drawSem);
3010 presInfo.waitSemaphoreCount = uint32_t(waitSemaphoresForPresent.count());;
3011 presInfo.pWaitSemaphores = waitSemaphoresForPresent.constData();
3015 inst->presentAboutToBeQueued(swapChainD->window);
3017 VkResult err = vkQueuePresentKHR(gfxQueue, &presInfo);
3018 waitSemaphoresForPresent.clear();
3019 if (err != VK_SUCCESS) {
3020 if (err == VK_ERROR_OUT_OF_DATE_KHR) {
3021 return QRhi::FrameOpSwapChainOutOfDate;
3022 }
else if (err != VK_SUBOPTIMAL_KHR) {
3023 if (err == VK_ERROR_DEVICE_LOST) {
3024 qWarning(
"Device loss detected in vkQueuePresentKHR()");
3025 printExtraErrorInfo(err);
3027 return QRhi::FrameOpDeviceLost;
3029 qWarning(
"Failed to present: %d", err);
3030 return QRhi::FrameOpError;
3036 inst->presentQueued(swapChainD->window);
3041 currentFrameSlot = (currentFrameSlot + 1) % QVK_FRAMES_IN_FLIGHT;
3046 return QRhi::FrameOpSuccess;
3060 QRHI_RES(QVkCommandBuffer, cb)->resetState();
3070 VkCommandBufferAllocateInfo cmdBufInfo = {};
3071 cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
3072 cmdBufInfo.commandPool = cmdPool[currentFrameSlot];
3073 cmdBufInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
3074 cmdBufInfo.commandBufferCount = 1;
3076 VkResult err =
df->vkAllocateCommandBuffers(dev, &cmdBufInfo, cb);
3077 if (err != VK_SUCCESS) {
3078 if (err == VK_ERROR_DEVICE_LOST) {
3079 qWarning(
"Device loss detected in vkAllocateCommandBuffers()");
3080 printExtraErrorInfo(err);
3082 return QRhi::FrameOpDeviceLost;
3084 qWarning(
"Failed to allocate frame command buffer: %d", err);
3085 return QRhi::FrameOpError;
3089 VkCommandBufferBeginInfo cmdBufBeginInfo = {};
3090 cmdBufBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
3092 VkResult err =
df->vkBeginCommandBuffer(*cb, &cmdBufBeginInfo);
3093 if (err != VK_SUCCESS) {
3094 if (err == VK_ERROR_DEVICE_LOST) {
3095 qWarning(
"Device loss detected in vkBeginCommandBuffer()");
3096 printExtraErrorInfo(err);
3098 return QRhi::FrameOpDeviceLost;
3100 qWarning(
"Failed to begin frame command buffer: %d", err);
3101 return QRhi::FrameOpError;
3104 return QRhi::FrameOpSuccess;
3108 VkSemaphore *waitSem, VkSemaphore *signalSem)
3110 VkResult err =
df->vkEndCommandBuffer(cb);
3111 if (err != VK_SUCCESS) {
3112 if (err == VK_ERROR_DEVICE_LOST) {
3113 qWarning(
"Device loss detected in vkEndCommandBuffer()");
3114 printExtraErrorInfo(err);
3116 return QRhi::FrameOpDeviceLost;
3118 qWarning(
"Failed to end frame command buffer: %d", err);
3119 return QRhi::FrameOpError;
3122 VkSubmitInfo submitInfo = {};
3123 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
3124 submitInfo.commandBufferCount = 1;
3125 submitInfo.pCommandBuffers = &cb;
3128 waitSemaphoresForQueueSubmit.append(*waitSem);
3130 signalSemaphoresForQueueSubmit.append(*signalSem);
3132 submitInfo.waitSemaphoreCount = uint32_t(waitSemaphoresForQueueSubmit.count());
3133 if (!waitSemaphoresForQueueSubmit.isEmpty()) {
3134 submitInfo.pWaitSemaphores = waitSemaphoresForQueueSubmit.constData();
3135 semaphoresWaitMasksForQueueSubmit.resize(waitSemaphoresForQueueSubmit.count(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
3136 submitInfo.pWaitDstStageMask = semaphoresWaitMasksForQueueSubmit.constData();
3138 submitInfo.signalSemaphoreCount = uint32_t(signalSemaphoresForQueueSubmit.count());
3139 if (!signalSemaphoresForQueueSubmit.isEmpty()) {
3140 submitInfo.pSignalSemaphores = signalSemaphoresForQueueSubmit.constData();
3143 err =
df->vkQueueSubmit(gfxQueue, 1, &submitInfo, cmdFence);
3145 waitSemaphoresForQueueSubmit.clear();
3146 signalSemaphoresForQueueSubmit.clear();
3148 if (err != VK_SUCCESS) {
3149 if (err == VK_ERROR_DEVICE_LOST) {
3150 qWarning(
"Device loss detected in vkQueueSubmit()");
3151 printExtraErrorInfo(err);
3153 return QRhi::FrameOpDeviceLost;
3155 qWarning(
"Failed to submit to graphics queue: %d", err);
3156 return QRhi::FrameOpError;
3159 return QRhi::FrameOpSuccess;
3164 for (QVkSwapChain *sc : std::as_const(swapchains)) {
3165 const int frameResIndex = sc->bufferCount > 1 ? frameSlot : 0;
3166 QVkSwapChain::FrameResources &frame(sc->frameRes[frameResIndex]);
3167 if (frame.cmdFenceWaitable) {
3168 VkResult err = df->vkWaitForFences(dev, 1, &frame.cmdFence, VK_TRUE, UINT64_MAX);
3170 if (err != VK_SUCCESS) {
3171 if (err == VK_ERROR_DEVICE_LOST) {
3172 qWarning(
"Device loss detected in vkWaitForFences()");
3173 printExtraErrorInfo(err);
3175 return QRhi::FrameOpDeviceLost;
3177 qWarning(
"Failed to wait for fence: %d", err);
3178 return QRhi::FrameOpError;
3181 df->vkResetFences(dev, 1, &frame.cmdFence);
3182 frame.cmdFenceWaitable =
false;
3186 if (ofr.cmdFenceWaitable[frameSlot]) {
3187 VkResult err =
df->vkWaitForFences(dev, 1, &ofr.cmdFence[frameSlot], VK_TRUE, UINT64_MAX);
3188 if (err != VK_SUCCESS) {
3189 if (err == VK_ERROR_DEVICE_LOST) {
3190 qWarning(
"Device loss detected in vkWaitForFences()");
3191 printExtraErrorInfo(err);
3193 return QRhi::FrameOpDeviceLost;
3195 qWarning(
"Failed to wait for offscreen fence: %d", err);
3196 return QRhi::FrameOpError;
3198 df->vkResetFences(dev, 1, &ofr.cmdFence[frameSlot]);
3199 ofr.cmdFenceWaitable[frameSlot] =
false;
3202 return QRhi::FrameOpSuccess;
3207 QRhi::FrameOpResult waitResult = waitCommandCompletion(currentFrameSlot);
3208 if (waitResult != QRhi::FrameOpSuccess)
3214 QRhi::FrameOpResult cbres = startPrimaryCommandBuffer(&cbWrapper->cb);
3215 if (cbres != QRhi::FrameOpSuccess)
3221 if (ofr.timestampQueryIndex[currentFrameSlot] >= 0) {
3222 quint64 timestamp[2] = { 0, 0 };
3223 VkResult err =
df->vkGetQueryPoolResults(dev, timestampQueryPool,
3224 uint32_t(ofr.timestampQueryIndex[currentFrameSlot]), 2,
3225 2 *
sizeof(quint64), timestamp,
sizeof(quint64),
3226 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
3227 timestampQueryPoolMap.clearBit(ofr.timestampQueryIndex[currentFrameSlot] / 2);
3228 ofr.timestampQueryIndex[currentFrameSlot] = -1;
3229 if (err == VK_SUCCESS) {
3231 const double elapsedSec = elapsedSecondsFromTimestamp(timestamp, &ok);
3235 qWarning(
"Failed to query timestamp: %d", err);
3239 if (rhiFlags.testFlag(QRhi::EnableTimestamps)) {
3240 int timestampQueryIdx = -1;
3241 for (
int i = 0; i < timestampQueryPoolMap.size(); ++i) {
3242 if (!timestampQueryPoolMap.testBit(i)) {
3243 timestampQueryPoolMap.setBit(i);
3244 timestampQueryIdx = i * 2;
3248 if (timestampQueryIdx >= 0) {
3249 df->vkCmdResetQueryPool(cbWrapper->cb, timestampQueryPool, uint32_t(timestampQueryIdx), 2);
3251 df->vkCmdWriteTimestamp(cbWrapper->cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
3252 timestampQueryPool, uint32_t(timestampQueryIdx));
3253 ofr.timestampQueryIndex[currentFrameSlot] = timestampQueryIdx;
3258 return QRhi::FrameOpSuccess;
3264 Q_ASSERT(ofr.active);
3270 const bool readbacksPending = !activeTextureReadbacks.isEmpty() || !activeBufferReadbacks.isEmpty();
3274 if (ofr.timestampQueryIndex[currentFrameSlot] >= 0) {
3275 df->vkCmdWriteTimestamp(cbWrapper->cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
3276 timestampQueryPool, uint32_t(ofr.timestampQueryIndex[currentFrameSlot] + 1));
3279 if (!ofr.cmdFence[currentFrameSlot]) {
3280 VkFenceCreateInfo fenceInfo = {};
3281 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
3282 VkResult err =
df->vkCreateFence(dev, &fenceInfo,
nullptr, &ofr.cmdFence[currentFrameSlot]);
3283 if (err != VK_SUCCESS) {
3284 qWarning(
"Failed to create command buffer fence: %d", err);
3285 return QRhi::FrameOpError;
3289 QRhi::FrameOpResult submitres = endAndSubmitPrimaryCommandBuffer(cbWrapper->cb, ofr.cmdFence[currentFrameSlot],
nullptr,
nullptr);
3290 if (submitres != QRhi::FrameOpSuccess)
3293 ofr.cmdFenceWaitable[currentFrameSlot] =
true;
3296 if (readbacksPending) {
3297 df->vkWaitForFences(dev, 1, &ofr.cmdFence[currentFrameSlot], VK_TRUE, UINT64_MAX);
3298 df->vkResetFences(dev, 1, &ofr.cmdFence[currentFrameSlot]);
3299 ofr.cmdFenceWaitable[currentFrameSlot] =
false;
3306 currentFrameSlot = (currentFrameSlot + 1) % QVK_FRAMES_IN_FLIGHT;
3308 return QRhi::FrameOpSuccess;
3330 swapChainFrameRes = &swapChainD->frameRes[swapChainD->bufferCount > 1 ? currentFrameSlot : 0];
3332 swapChainD->cbWrapper.resetCommands();
3333 cb = swapChainD->cbWrapper.cb;
3336 ? &swapChainFrameRes->imageSem
3338 QRhi::FrameOpResult submitres = endAndSubmitPrimaryCommandBuffer(cb, VK_NULL_HANDLE, waitSem,
nullptr);
3339 if (submitres != QRhi::FrameOpSuccess)
3345 df->vkQueueWaitIdle(gfxQueue);
3352 startPrimaryCommandBuffer(&ofr.cbWrapper[currentFrameSlot]->cb);
3354 startPrimaryCommandBuffer(&swapChainFrameRes->cmdBuf);
3355 swapChainD->cbWrapper.cb = swapChainFrameRes->cmdBuf;
3362 return QRhi::FrameOpSuccess;
3369 u
.access =
int(bufUsage.access);
3370 u
.stage =
int(bufUsage.stage);
3378 u
.access =
int(texUsage.access);
3379 u
.stage =
int(texUsage.stage);
3385 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QVkTexture, QVkRenderBuffer>(rtD->description(), rtD->d.currentResIdList))
3389 rtD->d.rp->lastActiveFrameSlot = currentFrameSlot;
3391 for (
auto it = rtD->m_desc.cbeginColorAttachments(), itEnd = rtD->m_desc.cendColorAttachments(); it != itEnd; ++it) {
3413 if (rtD->m_desc.depthStencilBuffer()) {
3415 Q_ASSERT(rbD->m_type == QRhiRenderBuffer::DepthStencil);
3422 if (rtD->m_desc.depthTexture()) {
3429 if (rtD->m_desc.depthResolveTexture()) {
3436 if (rtD->m_desc.shadingRateMap()) {
3455 VkCommandBuffer secondaryCb;
3457 if (!freeSecondaryCbs[currentFrameSlot].isEmpty()) {
3458 secondaryCb = freeSecondaryCbs[currentFrameSlot].last();
3459 freeSecondaryCbs[currentFrameSlot].removeLast();
3461 VkCommandBufferAllocateInfo cmdBufInfo = {};
3462 cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
3463 cmdBufInfo.commandPool = cmdPool[currentFrameSlot];
3464 cmdBufInfo.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY;
3465 cmdBufInfo.commandBufferCount = 1;
3467 VkResult err =
df->vkAllocateCommandBuffers(dev, &cmdBufInfo, &secondaryCb);
3468 if (err != VK_SUCCESS) {
3469 qWarning(
"Failed to create secondary command buffer: %d", err);
3470 return VK_NULL_HANDLE;
3474 VkCommandBufferBeginInfo cmdBufBeginInfo = {};
3475 cmdBufBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
3476 cmdBufBeginInfo.flags = rtD ? VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT : 0;
3477 VkCommandBufferInheritanceInfo cmdBufInheritInfo = {};
3478 cmdBufInheritInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
3479 cmdBufInheritInfo.subpass = 0;
3481 cmdBufInheritInfo.renderPass = rtD
->rp->rp;
3482 cmdBufInheritInfo.framebuffer = rtD->fb;
3484 cmdBufBeginInfo.pInheritanceInfo = &cmdBufInheritInfo;
3486 VkResult err =
df->vkBeginCommandBuffer(secondaryCb, &cmdBufBeginInfo);
3487 if (err != VK_SUCCESS) {
3488 qWarning(
"Failed to begin secondary command buffer: %d", err);
3489 return VK_NULL_HANDLE;
3497 VkResult err =
df->vkEndCommandBuffer(cb);
3498 if (err != VK_SUCCESS)
3499 qWarning(
"Failed to end secondary command buffer: %d", err);
3503 cmd.args.executeSecondary.cb = cb;
3508 e.secondaryCommandBuffer.cb = cb;
3509 releaseQueue.append(e);
3513 QRhiRenderTarget *rt,
3514 const QColor &colorClearValue,
3515 const QRhiDepthStencilClearValue &depthStencilClearValue,
3516 QRhiResourceUpdateBatch *resourceUpdates,
3517 QRhiCommandBuffer::BeginPassFlags flags)
3522 if (resourceUpdates)
3532 switch (rt->resourceType()) {
3533 case QRhiResource::SwapChainRenderTarget:
3548 case QRhiResource::TextureRenderTarget:
3562 cbD->currentTarget = rt;
3567 VkRenderPassBeginInfo rpBeginInfo = {};
3568 rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
3569 rpBeginInfo.renderPass = rtD
->rp->rp;
3570 rpBeginInfo.framebuffer = rtD->fb;
3571 rpBeginInfo.renderArea.extent.width = uint32_t(rtD->pixelSize.width());
3572 rpBeginInfo.renderArea.extent.height = uint32_t(rtD->pixelSize.height());
3574 const bool rpHasAnyClearOp =
std::any_of(rtD
->rp->attDescs.cbegin(), rtD
->rp->attDescs.cend(),
3575 [](
const VkAttachmentDescription &attDesc) {
3576 return (attDesc.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR
3577 || attDesc.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR);
3580 QVarLengthArray<VkClearValue, (QVkRenderTargetData::MAX_COLOR_ATTACHMENTS + 1) * 2 + 1> cvs;
3581 if (rpHasAnyClearOp) {
3583 VkClearValue cv = {};
3584 cv.color = { { colorClearValue.redF(), colorClearValue.greenF(), colorClearValue.blueF(),
3585 colorClearValue.alphaF() } };
3589 VkClearValue cv = {};
3590 cv.depthStencil = { depthStencilClearValue.depthClearValue(), depthStencilClearValue.stencilClearValue() };
3594 VkClearValue cv = {};
3595 cv.color = { { colorClearValue.redF(), colorClearValue.greenF(), colorClearValue.blueF(),
3596 colorClearValue.alphaF() } };
3600 VkClearValue cv = {};
3601 cv.depthStencil = { depthStencilClearValue.depthClearValue(), depthStencilClearValue.stencilClearValue() };
3605 VkClearValue cv = {};
3606 cv.color = { { 0.0f, 0.0f, 0.0f, 0.0f } };
3610 Q_ASSERT(!rpHasAnyClearOp || cvs.size() == rtD
->rp->attDescs.size());
3611 rpBeginInfo.clearValueCount = uint32_t(cvs.size());
3615 cmd.args.beginRenderPass.desc = rpBeginInfo;
3616 cmd.args.beginRenderPass.clearValueIndex = cbD->pools.clearValue.size();
3618 cbD->pools.clearValue.append(cvs.constData(), cvs.size());
3621 cbD->activeSecondaryCbStack.append(startSecondaryCommandBuffer(rtD));
3626 rateCmd.args.setShadingRate.w = 1;
3627 rateCmd.args.setShadingRate.h = 1;
3639 VkCommandBuffer secondaryCb = cbD->activeSecondaryCbStack.last();
3640 cbD->activeSecondaryCbStack.removeLast();
3641 endAndEnqueueSecondaryCommandBuffer(secondaryCb, cbD);
3648 cbD->currentTarget =
nullptr;
3650 if (resourceUpdates)
3655 QRhiResourceUpdateBatch *resourceUpdates,
3656 QRhiCommandBuffer::BeginPassFlags flags)
3661 if (resourceUpdates)
3669 cbD->computePassState.reset();
3672 cbD->activeSecondaryCbStack.append(startSecondaryCommandBuffer());
3683 VkCommandBuffer secondaryCb = cbD->activeSecondaryCbStack.last();
3684 cbD->activeSecondaryCbStack.removeLast();
3685 endAndEnqueueSecondaryCommandBuffer(secondaryCb, cbD);
3690 if (resourceUpdates)
3697 Q_ASSERT(psD->pipeline);
3703 df->vkCmdBindPipeline(cbD->activeSecondaryCbStack.last(), VK_PIPELINE_BIND_POINT_COMPUTE, psD->pipeline);
3707 cmd.args.bindPipeline.bindPoint = VK_PIPELINE_BIND_POINT_COMPUTE;
3708 cmd.args.bindPipeline.pipeline = psD->pipeline;
3711 cbD->currentGraphicsPipeline =
nullptr;
3712 cbD->currentComputePipeline = ps;
3721 QRhiShaderResourceBinding::Type bindingType,
3722 int loadTypeVal,
int storeTypeVal,
int loadStoreTypeVal)
3724 VkAccessFlags access = 0;
3725 if (bindingType == loadTypeVal) {
3726 access = VK_ACCESS_SHADER_READ_BIT;
3728 access = VK_ACCESS_SHADER_WRITE_BIT;
3729 if (bindingType == loadStoreTypeVal)
3730 access |= VK_ACCESS_SHADER_READ_BIT;
3732 auto it = writtenResources->find(resource);
3733 if (it != writtenResources->end())
3734 it->second.accessFlags |= access;
3735 else if (bindingType == storeTypeVal || bindingType == loadStoreTypeVal)
3736 writtenResources->insert(resource, { access,
true });
3741 return (access & VK_ACCESS_SHADER_WRITE_BIT) != 0
3742 || (access & VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) != 0
3743 || (access & VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT) != 0
3744 || (access & VK_ACCESS_TRANSFER_WRITE_BIT) != 0
3745 || (access & VK_ACCESS_HOST_WRITE_BIT) != 0
3746 || (access & VK_ACCESS_MEMORY_WRITE_BIT) != 0;
3752 QVarLengthArray<VkImageMemoryBarrier, 8> *imageBarriers,
3753 QVarLengthArray<VkBufferMemoryBarrier, 8> *bufferBarriers)
3755 if (!cbD->currentComputeSrb)
3761 for (
auto [res, accessAndIsNewFlag] : cbD->computePassState.writtenResources)
3762 accessAndIsNewFlag = { 0,
false };
3765 for (
auto &binding : srbD->m_bindings) {
3766 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(binding);
3767 switch (b->type()) {
3768 case QRhiShaderResourceBinding::ImageLoad:
3769 case QRhiShaderResourceBinding::ImageStore:
3770 case QRhiShaderResourceBinding::ImageLoadStore:
3771 qrhivk_accumulateComputeResource(&cbD->computePassState.writtenResources,
3774 QRhiShaderResourceBinding::ImageLoad,
3775 QRhiShaderResourceBinding::ImageStore,
3776 QRhiShaderResourceBinding::ImageLoadStore);
3778 case QRhiShaderResourceBinding::BufferLoad:
3779 case QRhiShaderResourceBinding::BufferStore:
3780 case QRhiShaderResourceBinding::BufferLoadStore:
3781 qrhivk_accumulateComputeResource(&cbD->computePassState.writtenResources,
3784 QRhiShaderResourceBinding::BufferLoad,
3785 QRhiShaderResourceBinding::BufferStore,
3786 QRhiShaderResourceBinding::BufferLoadStore);
3793 for (
auto it = cbD->computePassState.writtenResources.begin(); it != cbD->computePassState.writtenResources.end(); ) {
3794 const VkAccessFlags accessInThisDispatch = it->second.accessFlags;
3795 const bool isNewInThisDispatch = it->second.isNew;
3796 if (accessInThisDispatch && !isNewInThisDispatch) {
3797 if (it.key()->resourceType() == QRhiResource::Texture) {
3799 VkImageMemoryBarrier barrier = {};
3800 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
3801 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
3803 barrier.subresourceRange.baseMipLevel = 0;
3804 barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS;
3805 barrier.subresourceRange.baseArrayLayer = 0;
3806 barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
3807 barrier.oldLayout = texD->usageState.layout;
3808 barrier.newLayout = texD->usageState.layout;
3809 barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
3810 barrier.dstAccessMask = accessInThisDispatch;
3811 barrier.image = texD->image;
3812 imageBarriers->append(barrier);
3815 VkBufferMemoryBarrier barrier = {};
3816 barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
3817 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
3818 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
3819 barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
3820 barrier.dstAccessMask = accessInThisDispatch;
3821 barrier.buffer = bufD->buffers[bufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0];
3822 barrier.size = VK_WHOLE_SIZE;
3823 bufferBarriers->append(barrier);
3829 if (accessInThisDispatch == VK_ACCESS_SHADER_READ_BIT)
3830 it = cbD->computePassState.writtenResources.erase(it);
3841 QVarLengthArray<VkImageMemoryBarrier, 8> imageBarriers;
3842 QVarLengthArray<VkBufferMemoryBarrier, 8> bufferBarriers;
3843 collectComputeBarriers(cbD, &imageBarriers, &bufferBarriers);
3846 VkCommandBuffer secondaryCb = cbD->activeSecondaryCbStack.last();
3847 if (!imageBarriers.isEmpty() || !bufferBarriers.isEmpty()) {
3848 df->vkCmdPipelineBarrier(secondaryCb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
3850 bufferBarriers.size(), bufferBarriers.isEmpty() ?
nullptr : bufferBarriers.constData(),
3851 imageBarriers.size(), imageBarriers.isEmpty() ?
nullptr : imageBarriers.constData());
3853 df->vkCmdDispatch(secondaryCb, uint32_t(x), uint32_t(y), uint32_t(z));
3855 if (!imageBarriers.isEmpty() || !bufferBarriers.isEmpty()) {
3858 cmd.args.imageAndBufferBarrier.srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
3859 cmd.args.imageAndBufferBarrier.dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
3860 cmd.args.imageAndBufferBarrier.imageCount = imageBarriers.size();
3861 cmd.args.imageAndBufferBarrier.imageIndex = cbD->pools.imageBarrier.size();
3862 cbD->pools.imageBarrier.append(imageBarriers.constData(), imageBarriers.size());
3863 cmd.args.imageAndBufferBarrier.bufferCount = bufferBarriers.size();
3864 cmd.args.imageAndBufferBarrier.bufferIndex = cbD->pools.bufferBarrier.size();
3865 cbD->pools.bufferBarrier.append(bufferBarriers.constData(), bufferBarriers.size());
3869 cmd.args.dispatch.x = x;
3870 cmd.args.dispatch.y = y;
3871 cmd.args.dispatch.z = z;
3876 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
3877 QRhiBuffer *countBuffer, quint32 countBufferOffset,
3878 quint32 maxDrawCount, quint32 stride)
3880 if (!caps.drawIndirectCount) {
3881 qWarning(
"drawIndirectCount called but the DrawIndirectCount feature is not supported");
3891 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
3893 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3897 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
3901 if (countBufD->m_type == QRhiBuffer::Dynamic)
3903 const int countBufSlot = countBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3907 VkBuffer countBufVk = countBufD->buffers[countBufSlot];
3910#ifdef VK_VERSION_1_2
3911 vkCmdDrawIndirectCount(cbD->activeSecondaryCbStack.last(),
3912 indirectBufVk, indirectBufferOffset,
3913 countBufVk, countBufferOffset,
3914 maxDrawCount, stride);
3919 cmd.args.drawIndirectCount.indirectBuffer = indirectBufVk;
3920 cmd.args.drawIndirectCount.indirectBufferOffset = indirectBufferOffset;
3921 cmd.args.drawIndirectCount.countBuffer = countBufVk;
3922 cmd.args.drawIndirectCount.countBufferOffset = countBufferOffset;
3923 cmd.args.drawIndirectCount.maxDrawCount = maxDrawCount;
3924 cmd.args.drawIndirectCount.stride = stride;
3929 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
3930 QRhiBuffer *countBuffer, quint32 countBufferOffset,
3931 quint32 maxDrawCount, quint32 stride)
3933 if (!caps.drawIndirectCount) {
3934 qWarning(
"drawIndexedIndirectCount called but the DrawIndirectCount feature is not supported");
3944 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
3946 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3950 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
3954 if (countBufD->m_type == QRhiBuffer::Dynamic)
3956 const int countBufSlot = countBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3960 VkBuffer countBufVk = countBufD->buffers[countBufSlot];
3963#ifdef VK_VERSION_1_2
3964 vkCmdDrawIndexedIndirectCount(cbD->activeSecondaryCbStack.last(),
3965 indirectBufVk, indirectBufferOffset,
3966 countBufVk, countBufferOffset,
3967 maxDrawCount, stride);
3972 cmd.args.drawIndexedIndirectCount.indirectBuffer = indirectBufVk;
3973 cmd.args.drawIndexedIndirectCount.indirectBufferOffset = indirectBufferOffset;
3974 cmd.args.drawIndexedIndirectCount.countBuffer = countBufVk;
3975 cmd.args.drawIndexedIndirectCount.countBufferOffset = countBufferOffset;
3976 cmd.args.drawIndexedIndirectCount.maxDrawCount = maxDrawCount;
3977 cmd.args.drawIndexedIndirectCount.stride = stride;
3982 quint32 indirectBufferOffset)
3990 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
3992 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3993 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
3998 VkAccessFlags indirectSrcAccess = 0;
3999 VkPipelineStageFlags indirectSrcStage = 0;
4004 if (cbD->computePassState.writtenResources.contains(indirectBufD)) {
4005 indirectSrcAccess |= VK_ACCESS_SHADER_WRITE_BIT;
4006 indirectSrcStage |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
4014 const auto trackedIt = passResTracker
.buffers().find(indirectBufD);
4015 if (trackedIt != passResTracker
.buffers().cend()
4018 indirectSrcAccess |= VkAccessFlags(trackedIt->second.stateAtPassBegin.access);
4019 indirectSrcStage |= VkPipelineStageFlags(trackedIt->second.stateAtPassBegin.stage);
4022 u.access |= VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
4023 u.stage |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
4030 QVarLengthArray<VkImageMemoryBarrier, 8> imageBarriers;
4031 QVarLengthArray<VkBufferMemoryBarrier, 8> bufferBarriers;
4032 collectComputeBarriers(cbD, &imageBarriers, &bufferBarriers);
4034 VkBufferMemoryBarrier indirectBarrier = {};
4035 const bool needsIndirectBarrier = indirectSrcStage != 0 && accessIsWrite(indirectSrcAccess);
4036 if (needsIndirectBarrier) {
4037 indirectBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
4038 indirectBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
4039 indirectBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
4040 indirectBarrier.srcAccessMask = indirectSrcAccess;
4041 indirectBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
4042 indirectBarrier.buffer = indirectBufVk;
4043 indirectBarrier.size = VK_WHOLE_SIZE;
4047 VkCommandBuffer secondaryCb = cbD->activeSecondaryCbStack.last();
4048 if (!imageBarriers.isEmpty() || !bufferBarriers.isEmpty()) {
4049 df->vkCmdPipelineBarrier(secondaryCb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
4051 bufferBarriers.size(), bufferBarriers.isEmpty() ?
nullptr : bufferBarriers.constData(),
4052 imageBarriers.size(), imageBarriers.isEmpty() ?
nullptr : imageBarriers.constData());
4054 if (needsIndirectBarrier) {
4055 df->vkCmdPipelineBarrier(secondaryCb, indirectSrcStage, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT,
4057 1, &indirectBarrier,
4060 df->vkCmdDispatchIndirect(secondaryCb, indirectBufVk, VkDeviceSize(indirectBufferOffset));
4062 if (!imageBarriers.isEmpty() || !bufferBarriers.isEmpty()) {
4065 cmd.args.imageAndBufferBarrier.srcStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
4066 cmd.args.imageAndBufferBarrier.dstStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
4067 cmd.args.imageAndBufferBarrier.imageCount = imageBarriers.size();
4068 cmd.args.imageAndBufferBarrier.imageIndex = cbD->pools.imageBarrier.size();
4069 cbD->pools.imageBarrier.append(imageBarriers.constData(), imageBarriers.size());
4070 cmd.args.imageAndBufferBarrier.bufferCount = bufferBarriers.size();
4071 cmd.args.imageAndBufferBarrier.bufferIndex = cbD->pools.bufferBarrier.size();
4072 cbD->pools.bufferBarrier.append(bufferBarriers.constData(), bufferBarriers.size());
4074 if (needsIndirectBarrier) {
4077 cmd.args.bufferBarrier.srcStageMask = indirectSrcStage;
4078 cmd.args.bufferBarrier.dstStageMask = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
4079 cmd.args.bufferBarrier.count = 1;
4080 cmd.args.bufferBarrier.index = cbD->pools.bufferBarrier.size();
4081 cbD->pools.bufferBarrier.append(indirectBarrier);
4085 cmd.args.dispatchIndirect.indirectBuffer = indirectBufVk;
4086 cmd.args.dispatchIndirect.indirectBufferOffset = VkDeviceSize(indirectBufferOffset);
4092 VkShaderModuleCreateInfo shaderInfo = {};
4093 shaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
4094 shaderInfo.codeSize = size_t(spirv.size());
4095 shaderInfo.pCode =
reinterpret_cast<
const quint32 *>(spirv.constData());
4096 VkShaderModule shaderModule;
4097 VkResult err =
df->vkCreateShaderModule(dev, &shaderInfo,
nullptr, &shaderModule);
4098 if (err != VK_SUCCESS) {
4099 qWarning(
"Failed to create shader module: %d", err);
4100 return VK_NULL_HANDLE;
4102 return shaderModule;
4110 VkPipelineCacheCreateInfo pipelineCacheInfo = {};
4111 pipelineCacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
4112 pipelineCacheInfo.initialDataSize = initialDataSize;
4113 pipelineCacheInfo.pInitialData = initialData;
4114 VkResult err =
df->vkCreatePipelineCache(dev, &pipelineCacheInfo,
nullptr, &pipelineCache);
4115 if (err != VK_SUCCESS) {
4116 qWarning(
"Failed to create pipeline cache: %d", err);
4126 QVarLengthArray<VkDescriptorBufferInfo, 8> bufferInfos;
4127 using ArrayOfImageDesc = QVarLengthArray<VkDescriptorImageInfo, 8>;
4128 QVarLengthArray<ArrayOfImageDesc, 8> imageInfos;
4129 QVarLengthArray<VkWriteDescriptorSet, 12> writeInfos;
4130 QVarLengthArray<std::pair<
int,
int>, 12> infoIndices;
4132 for (
int i = 0, ie = srbD->sortedBindings.size(); i != ie; ++i) {
4133 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings.at(i));
4136 VkWriteDescriptorSet writeInfo = {};
4137 writeInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
4138 writeInfo.dstSet = srbD->descSets[currentFrameSlot];
4139 writeInfo.dstBinding = uint32_t(b->binding);
4140 writeInfo.descriptorCount = 1;
4142 int bufferInfoIndex = -1;
4143 int imageInfoIndex = -1;
4145 switch (b->type()) {
4146 case QRhiShaderResourceBinding::UniformBuffer:
4148 writeInfo.descriptorType = b->ubuf().hasDynamicOffset ? VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC
4149 : VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
4150 QRhiBuffer *buf = b->ubuf().buf;
4152 bd.ubuf.id = bufD->m_id;
4154 VkDescriptorBufferInfo bufInfo = {};
4155 bufInfo.buffer = bufD->m_type == QRhiBuffer::Dynamic ? bufD->buffers[currentFrameSlot] : bufD->buffers[0];
4156 bufInfo.offset = b->ubuf().offset;
4157 bufInfo.range = b->ubuf().maybeSize ? b->ubuf().maybeSize : VK_WHOLE_SIZE;
4159 Q_ASSERT(aligned(bufInfo.offset, ubufAlign) == bufInfo.offset);
4160 bufferInfoIndex = bufferInfos.size();
4161 bufferInfos.append(bufInfo);
4164 case QRhiShaderResourceBinding::SampledTexture:
4166 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
4167 writeInfo.descriptorCount = data->count();
4168 writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
4169 ArrayOfImageDesc imageInfo(data->count());
4170 bd.stex.d.resize(data->count());
4171 for (
int elem = 0; elem < data->count(); ++elem) {
4174 bd.stex.d[elem].texId = texD->m_id;
4176 bd.stex.d[elem].samplerId = samplerD->m_id;
4177 bd.stex.d[elem].samplerGeneration = samplerD
->generation;
4178 imageInfo[elem].sampler = samplerD->sampler;
4179 imageInfo[elem].imageView = texD->imageView;
4180 imageInfo[elem].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
4182 imageInfoIndex = imageInfos.size();
4183 imageInfos.append(imageInfo);
4186 case QRhiShaderResourceBinding::Texture:
4188 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
4189 writeInfo.descriptorCount = data->count();
4190 writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
4191 ArrayOfImageDesc imageInfo(data->count());
4192 bd.stex.d.resize(data->count());
4193 for (
int elem = 0; elem < data->count(); ++elem) {
4195 bd.stex.d[elem].texId = texD->m_id;
4197 bd.stex.d[elem].samplerId = 0;
4198 bd.stex.d[elem].samplerGeneration = 0;
4199 imageInfo[elem].sampler = VK_NULL_HANDLE;
4200 imageInfo[elem].imageView = texD->imageView;
4201 imageInfo[elem].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
4203 imageInfoIndex = imageInfos.size();
4204 imageInfos.append(imageInfo);
4207 case QRhiShaderResourceBinding::Sampler:
4210 writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
4211 bd.stex.d.resize(1);
4212 bd.stex.d[0].texId = 0;
4213 bd.stex.d[0].texGeneration = 0;
4214 bd.stex.d[0].samplerId = samplerD->m_id;
4216 ArrayOfImageDesc imageInfo(1);
4217 imageInfo[0].sampler = samplerD->sampler;
4218 imageInfo[0].imageView = VK_NULL_HANDLE;
4219 imageInfo[0].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
4220 imageInfoIndex = imageInfos.size();
4221 imageInfos.append(imageInfo);
4224 case QRhiShaderResourceBinding::ImageLoad:
4225 case QRhiShaderResourceBinding::ImageStore:
4226 case QRhiShaderResourceBinding::ImageLoadStore:
4229 VkImageView view = texD->perLevelImageViewForLoadStore(b->simage().level);
4231 writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
4232 bd.simage.id = texD->m_id;
4234 ArrayOfImageDesc imageInfo(1);
4235 imageInfo[0].sampler = VK_NULL_HANDLE;
4236 imageInfo[0].imageView = view;
4237 imageInfo[0].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
4238 imageInfoIndex = imageInfos.size();
4239 imageInfos.append(imageInfo);
4243 case QRhiShaderResourceBinding::BufferLoad:
4244 case QRhiShaderResourceBinding::BufferStore:
4245 case QRhiShaderResourceBinding::BufferLoadStore:
4248 writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
4249 bd.sbuf.id = bufD->m_id;
4251 VkDescriptorBufferInfo bufInfo = {};
4252 bufInfo.buffer = bufD->m_type == QRhiBuffer::Dynamic ? bufD->buffers[currentFrameSlot] : bufD->buffers[0];
4253 bufInfo.offset = b->sbuf().offset;
4254 bufInfo.range = b->sbuf().maybeSize ? b->sbuf().maybeSize : VK_WHOLE_SIZE;
4255 bufferInfoIndex = bufferInfos.size();
4256 bufferInfos.append(bufInfo);
4263 writeInfos.append(writeInfo);
4264 infoIndices.append({ bufferInfoIndex, imageInfoIndex });
4267 for (
int i = 0, writeInfoCount = writeInfos.size(); i < writeInfoCount; ++i) {
4268 const int bufferInfoIndex = infoIndices[i].first;
4269 const int imageInfoIndex = infoIndices[i].second;
4270 if (bufferInfoIndex >= 0)
4271 writeInfos[i].pBufferInfo = &bufferInfos[bufferInfoIndex];
4272 else if (imageInfoIndex >= 0)
4273 writeInfos[i].pImageInfo = imageInfos[imageInfoIndex].constData();
4276 df->vkUpdateDescriptorSets(dev, uint32_t(writeInfos.size()), writeInfos.constData(), 0,
nullptr);
4280 VkAccessFlags access, VkPipelineStageFlags stage)
4283 Q_ASSERT(access && stage);
4291 if (s.access == access && s.stage == stage) {
4294 if (!accessIsWrite(access))
4298 VkBufferMemoryBarrier bufMemBarrier = {};
4299 bufMemBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
4300 bufMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
4301 bufMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
4302 bufMemBarrier.srcAccessMask = s.access;
4303 bufMemBarrier.dstAccessMask = access;
4304 bufMemBarrier.buffer = bufD->buffers[slot];
4305 bufMemBarrier.size = VK_WHOLE_SIZE;
4309 cmd.args.bufferBarrier.srcStageMask = s.stage;
4310 cmd.args.bufferBarrier.dstStageMask = stage;
4311 cmd.args.bufferBarrier.count = 1;
4312 cmd.args.bufferBarrier.index = cbD->pools.bufferBarrier.size();
4313 cbD->pools.bufferBarrier.append(bufMemBarrier);
4320 VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stage)
4323 Q_ASSERT(layout && access && stage);
4325 if (s.access == access && s.stage == stage && s.layout == layout) {
4326 if (!accessIsWrite(access))
4330 VkImageMemoryBarrier barrier = {};
4331 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
4332 barrier.subresourceRange.aspectMask = aspectMaskForTextureFormat(texD->m_format);
4333 barrier.subresourceRange.baseMipLevel = 0;
4334 barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS;
4335 barrier.subresourceRange.baseArrayLayer = 0;
4336 barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
4337 barrier.oldLayout = s.layout;
4338 barrier.newLayout = layout;
4339 barrier.srcAccessMask = s.access;
4340 barrier.dstAccessMask = access;
4341 barrier.image = texD->image;
4343 VkPipelineStageFlags srcStage = s.stage;
4346 srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
4350 cmd.args.imageBarrier.srcStageMask = srcStage;
4351 cmd.args.imageBarrier.dstStageMask = stage;
4352 cmd.args.imageBarrier.count = 1;
4353 cmd.args.imageBarrier.index = cbD->pools.imageBarrier.size();
4354 cbD->pools.imageBarrier.append(barrier);
4365 VkImageMemoryBarrier barrier = {};
4366 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
4367 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
4368 barrier.subresourceRange.baseMipLevel = 0;
4369 barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS;
4370 barrier.subresourceRange.baseArrayLayer = 0;
4371 barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
4372 barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
4373 barrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
4374 barrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
4375 barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT
4376 | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
4377 barrier.image = rbD->image;
4379 const VkPipelineStageFlags stages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT
4380 | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
4384 cmd.args.imageBarrier.srcStageMask = stages;
4385 cmd.args.imageBarrier.dstStageMask = stages;
4386 cmd.args.imageBarrier.count = 1;
4387 cmd.args.imageBarrier.index = cbD->pools.imageBarrier.size();
4388 cbD->pools.imageBarrier.append(barrier);
4392 VkImageLayout oldLayout, VkImageLayout newLayout,
4393 VkAccessFlags srcAccess, VkAccessFlags dstAccess,
4394 VkPipelineStageFlags srcStage, VkPipelineStageFlags dstStage,
4395 int startLayer,
int layerCount,
4396 int startLevel,
int levelCount)
4399 VkImageMemoryBarrier barrier = {};
4400 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
4401 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
4402 barrier.subresourceRange.baseMipLevel = uint32_t(startLevel);
4403 barrier.subresourceRange.levelCount = uint32_t(levelCount);
4404 barrier.subresourceRange.baseArrayLayer = uint32_t(startLayer);
4405 barrier.subresourceRange.layerCount = uint32_t(layerCount);
4406 barrier.oldLayout = oldLayout;
4407 barrier.newLayout = newLayout;
4408 barrier.srcAccessMask = srcAccess;
4409 barrier.dstAccessMask = dstAccess;
4410 barrier.image = image;
4414 cmd.args.imageBarrier.srcStageMask = srcStage;
4415 cmd.args.imageBarrier.dstStageMask = dstStage;
4416 cmd.args.imageBarrier.count = 1;
4417 cmd.args.imageBarrier.index = cbD->pools.imageBarrier.size();
4418 cbD->pools.imageBarrier.append(barrier);
4423 VkDeviceSize size = 0;
4424 const qsizetype imageSizeBytes = subresDesc.image().isNull() ?
4425 subresDesc.data().size() : subresDesc.image().sizeInBytes();
4426 if (imageSizeBytes > 0)
4427 size += aligned(VkDeviceSize(imageSizeBytes), texbufAlign);
4432 const QRhiTextureSubresourceUploadDescription &subresDesc,
4433 size_t *curOfs,
void *mp,
4434 BufferImageCopyList *copyInfos)
4436 qsizetype copySizeBytes = 0;
4437 qsizetype imageSizeBytes = 0;
4438 const void *src =
nullptr;
4439 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4440 const bool is1D = texD->m_flags.testFlag(QRhiTexture::OneDimensional);
4442 VkBufferImageCopy copyInfo = {};
4443 copyInfo.bufferOffset = *curOfs;
4444 copyInfo.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
4445 copyInfo.imageSubresource.mipLevel = uint32_t(level);
4446 copyInfo.imageSubresource.baseArrayLayer = is3D ? 0 : uint32_t(layer);
4447 copyInfo.imageSubresource.layerCount = 1;
4448 copyInfo.imageExtent.depth = 1;
4450 copyInfo.imageOffset.z = uint32_t(layer);
4452 copyInfo.imageOffset.y = uint32_t(layer);
4454 const QByteArray rawData = subresDesc.data();
4455 const QPoint dp = subresDesc.destinationTopLeft();
4456 QImage image = subresDesc.image();
4457 if (!image.isNull()) {
4458 copySizeBytes = imageSizeBytes = image.sizeInBytes();
4459 QSize size = image.size();
4460 src = image.constBits();
4463 int bpc = qMax(1, image.depth() / 8);
4465 copyInfo.bufferRowLength = uint32_t(image.bytesPerLine() / bpc);
4466 if (!subresDesc.sourceSize().isEmpty() || !subresDesc.sourceTopLeft().isNull()) {
4467 const int sx = subresDesc.sourceTopLeft().x();
4468 const int sy = subresDesc.sourceTopLeft().y();
4469 if (!subresDesc.sourceSize().isEmpty())
4470 size = subresDesc.sourceSize();
4471 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
4472 if (size.width() == image.width()) {
4475 src = image.constBits() + sy * image.bytesPerLine() + sx * bpc;
4476 copySizeBytes = size.height() * image.bytesPerLine();
4478 image = image.copy(sx, sy, size.width(), size.height());
4479 src = image.constBits();
4482 copySizeBytes = image.sizeInBytes();
4483 bpc = qMax(1, image.depth() / 8);
4484 copyInfo.bufferRowLength = uint32_t(image.bytesPerLine() / bpc);
4487 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
4489 copyInfo.imageOffset.x = dp.x();
4490 copyInfo.imageOffset.y = dp.y();
4491 copyInfo.imageExtent.width = uint32_t(size.width());
4492 copyInfo.imageExtent.height = uint32_t(size.height());
4493 copyInfos->append(copyInfo);
4494 }
else if (!rawData.isEmpty() && isCompressedFormat(texD->m_format)) {
4495 copySizeBytes = imageSizeBytes = rawData.size();
4496 src = rawData.constData();
4497 QSize size = q->sizeForMipLevel(level, texD->m_pixelSize);
4498 const int subresw = size.width();
4499 const int subresh = size.height();
4500 if (!subresDesc.sourceSize().isEmpty())
4501 size = subresDesc.sourceSize();
4502 size = clampedCompressedSubResourceUploadSizeForSourceData(texD->m_format, size,
4504 if (size.height() == 0)
4506 const int w = size.width();
4507 const int h = size.height();
4509 compressedFormatInfo(texD->m_format, QSize(w, h),
nullptr,
nullptr, &blockDim);
4511 copyInfo.imageOffset.x = aligned(dp.x(), blockDim.width());
4512 copyInfo.imageOffset.y = aligned(dp.y(), blockDim.height());
4515 copyInfo.imageExtent.width = uint32_t(dp.x() + w == subresw ? w : aligned(w, blockDim.width()));
4516 copyInfo.imageExtent.height = uint32_t(dp.y() + h == subresh ? h : aligned(h, blockDim.height()));
4517 copyInfos->append(copyInfo);
4518 }
else if (!rawData.isEmpty()) {
4519 copySizeBytes = imageSizeBytes = rawData.size();
4520 src = rawData.constData();
4521 QSize size = q->sizeForMipLevel(level, texD->m_pixelSize);
4522 if (!subresDesc.sourceSize().isEmpty())
4523 size = subresDesc.sourceSize();
4524 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
4526 quint32 bytesPerPixel = 0;
4527 textureFormatInfo(texD->m_format, size,
nullptr,
nullptr, &bytesPerPixel);
4528 if (subresDesc.dataStride() && bytesPerPixel)
4529 copyInfo.bufferRowLength = subresDesc.dataStride() / bytesPerPixel;
4531 size = clampedSubResourceUploadSizeForSourceData(size, subresDesc.dataStride(),
4532 bytesPerPixel, rawData.size());
4534 if (!size.isEmpty()) {
4535 copyInfo.imageOffset.x = dp.x();
4536 copyInfo.imageOffset.y = dp.y();
4537 copyInfo.imageExtent.width = uint32_t(size.width());
4538 copyInfo.imageExtent.height = uint32_t(size.height());
4539 copyInfos->append(copyInfo);
4542 qWarning(
"Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
4546 memcpy(
reinterpret_cast<
char *>(mp) + *curOfs, src, size_t(copySizeBytes));
4547 *curOfs += aligned(VkDeviceSize(imageSizeBytes), texbufAlign);
4553 if (err == VK_ERROR_DEVICE_LOST)
4554 printDeviceLossErrorInfo();
4555 if (err == VK_ERROR_OUT_OF_DEVICE_MEMORY)
4556 qWarning() <<
"Out of device memory, current allocator statistics are" << statistics();
4561#ifdef VK_EXT_device_fault
4562 if (!dev || !caps.deviceFault || !vkGetDeviceFaultInfoEXT)
4565 VkDeviceFaultCountsEXT faultCounts{};
4566 faultCounts.sType = VK_STRUCTURE_TYPE_DEVICE_FAULT_COUNTS_EXT;
4567 faultCounts.pNext =
nullptr;
4569 VkResult result = vkGetDeviceFaultInfoEXT(dev, &faultCounts,
nullptr);
4570 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
4571 qWarning(
"vkGetDeviceFaultInfoEXT failed with %d", result);
4574 faultCounts.vendorBinarySize = 0;
4576 const auto numAddressInfos = faultCounts.addressInfoCount;
4577 const auto addressInfos
4578 = q20::make_unique_for_overwrite<VkDeviceFaultAddressInfoEXT[]>(numAddressInfos);
4580 const auto numVendorInfos = faultCounts.vendorInfoCount;
4581 const auto vendorInfos
4582 = q20::make_unique_for_overwrite<VkDeviceFaultVendorInfoEXT[]>(numVendorInfos);
4584 VkDeviceFaultInfoEXT info{};
4585 info.sType = VK_STRUCTURE_TYPE_DEVICE_FAULT_INFO_EXT;
4586 info.pNext =
nullptr;
4587 info.pAddressInfos = numAddressInfos ? addressInfos.get() :
nullptr;
4588 info.pVendorInfos = numVendorInfos ? vendorInfos.get() :
nullptr;
4589 info.pVendorBinaryData =
nullptr;
4591 result = vkGetDeviceFaultInfoEXT(dev, &faultCounts, &info);
4592 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
4593 qWarning(
"vkGetDeviceFaultInfoEXT failed with %d", result);
4597 const char *desc = info.description[0] ? info.description :
"n/a";
4598 qWarning(
"VK_ERROR_DEVICE_LOST (VK_EXT_device_fault): %u address infos, %u vendor infos, %llu bytes vendor binary: %s",
4599 faultCounts.addressInfoCount,
4600 faultCounts.vendorInfoCount,
4601 (
unsigned long long)faultCounts.vendorBinarySize,
4604 for (uint32_t i = 0; i < faultCounts.addressInfoCount; ++i) {
4605 const auto &a = addressInfos[i];
4606 auto addressTypeString = [](
const VkDeviceFaultAddressTypeEXT type) {
4608 case VK_DEVICE_FAULT_ADDRESS_TYPE_NONE_EXT:
return "NONE";
4609 case VK_DEVICE_FAULT_ADDRESS_TYPE_READ_INVALID_EXT:
return "READ_INVALID";
4610 case VK_DEVICE_FAULT_ADDRESS_TYPE_WRITE_INVALID_EXT:
return "WRITE_INVALID";
4611 case VK_DEVICE_FAULT_ADDRESS_TYPE_EXECUTE_INVALID_EXT:
return "EXECUTE_INVALID";
4612 case VK_DEVICE_FAULT_ADDRESS_TYPE_INSTRUCTION_POINTER_UNKNOWN_EXT:
return "INSTRUCTION_POINTER_UNKNOWN";
4613 case VK_DEVICE_FAULT_ADDRESS_TYPE_INSTRUCTION_POINTER_INVALID_EXT:
return "INSTRUCTION_POINTER_INVALID";
4614 case VK_DEVICE_FAULT_ADDRESS_TYPE_INSTRUCTION_POINTER_FAULT_EXT:
return "INSTRUCTION_POINTER_FAULT";
4615 default:
return "UNKNOWN";
4618 qWarning(
" AddressInfo[%02u]: type=%s addr=0x%llx precision=%llu",
4620 addressTypeString(a.addressType),
4621 (
unsigned long long)a.reportedAddress,
4622 (
unsigned long long)a.addressPrecision);
4625 for (uint32_t i = 0; i < faultCounts.vendorInfoCount; ++i) {
4626 const auto &v = vendorInfos[i];
4627 qWarning(
" VendorInfo[%02u]: code=%llu data=%llu desc=%s",
4629 (
unsigned long long)v.vendorFaultCode,
4630 (
unsigned long long)v.vendorFaultData,
4644 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
4646 if (u.offset == 0 && u.data.size() == bufD->m_size)
4647 bufD->pendingDynamicUpdates[i].clear();
4648 bufD->pendingDynamicUpdates[i].append({ u.offset, u.data });
4652 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
4653 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
4655 if (!bufD->stagingBuffers[currentFrameSlot]) {
4656 VkBufferCreateInfo bufferInfo = {};
4657 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
4660 bufferInfo.size = bufD->m_size;
4661 bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
4663 VmaAllocationCreateInfo allocInfo = {};
4664 allocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
4666 VmaAllocation allocation;
4667 VkResult err = vmaCreateBuffer(toVmaAllocator(allocator), &bufferInfo, &allocInfo,
4668 &bufD->stagingBuffers[currentFrameSlot], &allocation,
nullptr);
4669 if (err == VK_SUCCESS) {
4670 bufD->stagingAllocations[currentFrameSlot] = allocation;
4671 setAllocationName(allocation, bufD->name());
4673 qWarning(
"Failed to create staging buffer of size %u: %d", bufD->m_size, err);
4674 printExtraErrorInfo(err);
4679 VkResult err = vmaCopyMemoryToAllocation(toVmaAllocator(allocator), u.data.constData(),
4680 toVmaAllocation(bufD->stagingAllocations[currentFrameSlot]),
4681 u.offset, u.data.size());
4682 if (err != VK_SUCCESS) {
4683 qWarning(
"Failed to copy memory to buffer: %d", err);
4687 trackedBufferBarrier(cbD, bufD, 0,
4688 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4690 VkBufferCopy copyInfo = {};
4691 copyInfo.srcOffset = u.offset;
4692 copyInfo.dstOffset = u.offset;
4693 copyInfo.size = u.data.size();
4697 cmd.args.copyBuffer.src = bufD->stagingBuffers[currentFrameSlot];
4698 cmd.args.copyBuffer.dst = bufD->buffers[0];
4699 cmd.args.copyBuffer.desc = copyInfo;
4710 if (bufD->m_type == QRhiBuffer::Immutable) {
4714 e.stagingBuffer.stagingBuffer = bufD->stagingBuffers[currentFrameSlot];
4715 e.stagingBuffer.stagingAllocation = bufD->stagingAllocations[currentFrameSlot];
4716 bufD->stagingBuffers[currentFrameSlot] = VK_NULL_HANDLE;
4717 bufD->stagingAllocations[currentFrameSlot] =
nullptr;
4718 releaseQueue.append(e);
4722 if (bufD->m_type == QRhiBuffer::Dynamic) {
4724 u.result->data.resizeForOverwrite(u.readSize);
4725 VkResult err = vmaCopyAllocationToMemory(toVmaAllocator(allocator),
4726 toVmaAllocation(bufD->allocations[currentFrameSlot]),
4727 u.offset, u.result->data.data(), u.readSize);
4728 if (err != VK_SUCCESS) {
4729 qWarning(
"Failed to copy memory from buffer: %d", err);
4730 u.result->data.clear();
4732 if (u.result->completed)
4733 u.result->completed();
4743 readback.result = u.result;
4744 readback.byteSize = u.readSize;
4746 VkBufferCreateInfo bufferInfo = {};
4747 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
4748 bufferInfo.size = readback.byteSize;
4749 bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
4751 VmaAllocationCreateInfo allocInfo = {};
4752 allocInfo.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
4754 VmaAllocation allocation;
4755 VkResult err = vmaCreateBuffer(toVmaAllocator(allocator), &bufferInfo, &allocInfo, &readback.stagingBuf, &allocation,
nullptr);
4756 if (err == VK_SUCCESS) {
4758 setAllocationName(allocation, bufD->name());
4760 qWarning(
"Failed to create readback buffer of size %u: %d", readback.byteSize, err);
4761 printExtraErrorInfo(err);
4765 trackedBufferBarrier(cbD, bufD, 0, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4767 VkBufferCopy copyInfo = {};
4768 copyInfo.srcOffset = u.offset;
4769 copyInfo.size = u.readSize;
4773 cmd.args.copyBuffer.src = bufD->buffers[0];
4774 cmd.args.copyBuffer.dst = readback.stagingBuf;
4775 cmd.args.copyBuffer.desc = copyInfo;
4779 activeBufferReadbacks.append(readback);
4784 Q_ASSERT(dstD->m_type != QRhiBuffer::Dynamic && srcD->m_type != QRhiBuffer::Dynamic);
4786 trackedBufferBarrier(cbD, srcD, 0, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4787 trackedBufferBarrier(cbD, dstD, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4789 VkBufferCopy copyInfo = {};
4790 copyInfo.srcOffset = u.srcOffset;
4791 copyInfo.dstOffset = u.offset;
4792 copyInfo.size = u.readSize;
4796 cmd.args.copyBuffer.src = srcD->buffers[0];
4797 cmd.args.copyBuffer.dst = dstD->buffers[0];
4798 cmd.args.copyBuffer.desc = copyInfo;
4803 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
4805 trackedBufferBarrier(cbD, bufD, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4809 cmd.args.fillBuffer.dst = bufD->buffers[0];
4810 cmd.args.fillBuffer.offset = u.offset;
4811 cmd.args.fillBuffer.size = u.readSize;
4812 cmd.args.fillBuffer.data = u.fillValue32();
4823 VkDeviceSize stagingSize = 0;
4824 for (
const auto &subres : u.subresDesc)
4825 stagingSize += subresUploadByteSize(subres.desc);
4827 Q_ASSERT(!utexD->stagingBuffers[currentFrameSlot]);
4828 VkBufferCreateInfo bufferInfo = {};
4829 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
4830 bufferInfo.size = stagingSize;
4831 bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
4833 VmaAllocationCreateInfo allocInfo = {};
4834 allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
4836 VmaAllocation allocation;
4837 VkResult err = vmaCreateBuffer(toVmaAllocator(allocator), &bufferInfo, &allocInfo,
4838 &utexD->stagingBuffers[currentFrameSlot], &allocation,
nullptr);
4839 if (err != VK_SUCCESS) {
4840 qWarning(
"Failed to create image staging buffer of size %d: %d",
int(stagingSize), err);
4841 printExtraErrorInfo(err);
4844 utexD->stagingAllocations[currentFrameSlot] = allocation;
4845 setAllocationName(allocation, utexD->name());
4847 BufferImageCopyList copyInfos;
4850 VmaAllocation a = toVmaAllocation(utexD->stagingAllocations[currentFrameSlot]);
4851 err = vmaMapMemory(toVmaAllocator(allocator), a, &mp);
4852 if (err != VK_SUCCESS) {
4853 qWarning(
"Failed to map image data: %d", err);
4854 vmaDestroyBuffer(toVmaAllocator(allocator), utexD->stagingBuffers[currentFrameSlot], a);
4855 utexD->stagingBuffers[currentFrameSlot] = VK_NULL_HANDLE;
4856 utexD->stagingAllocations[currentFrameSlot] =
nullptr;
4860 for (
const auto &subres : u.subresDesc)
4861 prepareUploadSubres(utexD, subres.layer, subres.level, subres.desc, &curOfs, mp, ©Infos);
4862 vmaFlushAllocation(toVmaAllocator(allocator), a, 0, stagingSize);
4863 vmaUnmapMemory(toVmaAllocator(allocator), a);
4865 trackedImageBarrier(cbD, utexD, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
4866 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4868 if (!copyInfos.isEmpty()) {
4871 cmd.args.copyBufferToImage.src = utexD->stagingBuffers[currentFrameSlot];
4872 cmd.args.copyBufferToImage.dst = utexD->image;
4873 cmd.args.copyBufferToImage.dstLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
4874 cmd.args.copyBufferToImage.count = copyInfos.size();
4875 cmd.args.copyBufferToImage.bufferImageCopyIndex = cbD->pools.bufferImageCopy.size();
4876 cbD->pools.bufferImageCopy.append(copyInfos.constData(), copyInfos.size());
4883 e.stagingBuffer.stagingBuffer = utexD->stagingBuffers[currentFrameSlot];
4884 e.stagingBuffer.stagingAllocation = utexD->stagingAllocations[currentFrameSlot];
4885 utexD->stagingBuffers[currentFrameSlot] = VK_NULL_HANDLE;
4886 utexD->stagingAllocations[currentFrameSlot] =
nullptr;
4887 releaseQueue.append(e);
4896 qWarning(
"Texture copy with matching source and destination is not supported");
4901 const bool srcIs3D = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4902 const bool dstIs3D = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4904 VkImageCopy region = {};
4905 region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
4906 region.srcSubresource.mipLevel = uint32_t(u.desc.sourceLevel());
4907 region.srcSubresource.baseArrayLayer = srcIs3D ? 0 : uint32_t(u.desc.sourceLayer());
4908 region.srcSubresource.layerCount = 1;
4910 region.srcOffset.x = u.desc.sourceTopLeft().x();
4911 region.srcOffset.y = u.desc.sourceTopLeft().y();
4913 region.srcOffset.z = uint32_t(u.desc.sourceLayer());
4915 region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
4916 region.dstSubresource.mipLevel = uint32_t(u.desc.destinationLevel());
4917 region.dstSubresource.baseArrayLayer = dstIs3D ? 0 : uint32_t(u.desc.destinationLayer());
4918 region.dstSubresource.layerCount = 1;
4920 region.dstOffset.x = u.desc.destinationTopLeft().x();
4921 region.dstOffset.y = u.desc.destinationTopLeft().y();
4923 region.dstOffset.z = uint32_t(u.desc.destinationLayer());
4925 const QSize mipSize = q->sizeForMipLevel(u.desc.sourceLevel(), srcD->m_pixelSize);
4926 const QSize copySize = u.desc.pixelSize().isEmpty() ? mipSize : u.desc.pixelSize();
4927 region.extent.width = uint32_t(copySize.width());
4928 region.extent.height = uint32_t(copySize.height());
4929 region.extent.depth = 1;
4931 trackedImageBarrier(cbD, srcD, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
4932 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4933 trackedImageBarrier(cbD, dstD, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
4934 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4938 cmd.args.copyImage.src = srcD->image;
4939 cmd.args.copyImage.srcLayout = srcD->usageState.layout;
4940 cmd.args.copyImage.dst = dstD->image;
4941 cmd.args.copyImage.dstLayout = dstD->usageState.layout;
4942 cmd.args.copyImage.desc = region;
4948 readback.desc = u.rb;
4949 readback.result = u.result;
4955 if (texD->samples > VK_SAMPLE_COUNT_1_BIT) {
4956 qWarning(
"Multisample texture cannot be read back");
4959 is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4960 if (u.rb.rect().isValid())
4961 readback.rect = u.rb.rect();
4963 readback.rect = QRect({0, 0}, q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize));
4964 readback.format = texD->m_format;
4970 qWarning(
"Swapchain does not support readback");
4973 if (u.rb.rect().isValid())
4974 readback.rect = u.rb.rect();
4976 readback.rect = QRect({0, 0}, swapChainD->pixelSize);
4977 readback.format = swapchainReadbackTextureFormat(swapChainD->colorFormat,
nullptr);
4978 if (readback.format == QRhiTexture::UnknownFormat)
4984 if (!textureFormatInfo(readback.format, readback.rect.size(),
nullptr,
4985 &readback.byteSize,
nullptr))
4993 const bool combinedDepthStencil = texD && isStencilTextureFormat(readback.format);
4998 const quint64 pixelCount =
4999 quint64(readback.rect.width()) * quint64(readback.rect.height());
5000 const quint64 depthPlaneByteSize = pixelCount * 4;
5001 const quint64 stagingByteSize = combinedDepthStencil
5002 ? depthPlaneByteSize + pixelCount
5003 : readback.byteSize;
5004 if (stagingByteSize > std::numeric_limits<quint32>::max()) {
5005 qWarning(
"Readback of texture of size %dx%d would need %llu bytes "
5006 "which is too large to be handled",
5007 readback.rect.width(), readback.rect.height(), stagingByteSize);
5012 VkBufferCreateInfo bufferInfo = {};
5013 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
5014 bufferInfo.size = stagingByteSize;
5015 bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
5017 VmaAllocationCreateInfo allocInfo = {};
5018 allocInfo.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
5020 VmaAllocation allocation;
5021 VkResult err = vmaCreateBuffer(toVmaAllocator(allocator), &bufferInfo, &allocInfo, &readback.stagingBuf, &allocation,
nullptr);
5022 if (err == VK_SUCCESS) {
5024 setAllocationName(allocation, texD ? texD->name() : swapChainD->name());
5026 qWarning(
"Failed to create readback buffer of size %llu: %d", stagingByteSize, err);
5027 printExtraErrorInfo(err);
5032 VkBufferImageCopy copyDesc = {};
5033 copyDesc.bufferOffset = 0;
5034 copyDesc.imageSubresource.aspectMask = aspectMaskForTextureFormat(readback.format);
5035 copyDesc.imageSubresource.mipLevel = uint32_t(u.rb.level());
5036 copyDesc.imageSubresource.baseArrayLayer = is3D ? 0 : uint32_t(u.rb.layer());
5037 copyDesc.imageSubresource.layerCount = 1;
5038 copyDesc.imageOffset.x = readback.rect.x();
5039 copyDesc.imageOffset.y = readback.rect.y();
5041 copyDesc.imageOffset.z = u.rb.layer();
5042 copyDesc.imageExtent.width = uint32_t(readback.rect.width());
5043 copyDesc.imageExtent.height = uint32_t(readback.rect.height());
5044 copyDesc.imageExtent.depth = 1;
5046 const int bufferImageCopyIndex = cbD->pools.bufferImageCopy.size();
5047 if (combinedDepthStencil) {
5048 copyDesc.imageSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
5049 cbD->pools.bufferImageCopy.append(copyDesc);
5050 copyDesc.bufferOffset = depthPlaneByteSize;
5051 copyDesc.imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
5053 cbD->pools.bufferImageCopy.append(copyDesc);
5054 const int copyCount = cbD->pools.bufferImageCopy.size() - bufferImageCopyIndex;
5057 trackedImageBarrier(cbD, texD, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
5058 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
5061 cmd.args.copyImageToBuffer.src = texD->image;
5062 cmd.args.copyImageToBuffer.srcLayout = texD->usageState.layout;
5063 cmd.args.copyImageToBuffer.dst = readback.stagingBuf;
5064 cmd.args.copyImageToBuffer.count = copyCount;
5065 cmd.args.copyImageToBuffer.bufferImageCopyIndex = bufferImageCopyIndex;
5069 VkImage image = imageRes.image;
5072 qWarning(
"Attempted to read back undefined swapchain image content, "
5073 "results are undefined. (do a render pass first)");
5075 subresourceBarrier(cbD, image,
5076 VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
5077 VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_TRANSFER_READ_BIT,
5078 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
5086 cmd.args.copyImageToBuffer.src = image;
5087 cmd.args.copyImageToBuffer.srcLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
5088 cmd.args.copyImageToBuffer.dst = readback.stagingBuf;
5089 cmd.args.copyImageToBuffer.count = copyCount;
5090 cmd.args.copyImageToBuffer.bufferImageCopyIndex = bufferImageCopyIndex;
5093 activeTextureReadbacks.append(readback);
5096 Q_ASSERT(utexD->m_flags.testFlag(QRhiTexture::UsedWithGenerateMips));
5097 const bool isCube = utexD->m_flags.testFlag(QRhiTexture::CubeMap);
5098 const bool isArray = utexD->m_flags.testFlag(QRhiTexture::TextureArray);
5099 const bool is3D = utexD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
5101 VkImageLayout origLayout = utexD->usageState.layout;
5102 VkAccessFlags origAccess = utexD->usageState.access;
5103 VkPipelineStageFlags origStage = utexD->usageState.stage;
5105 origStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
5107 for (
int layer = 0; layer < (isCube ? 6 : (isArray ? qMax(0, utexD->m_arraySize) : 1)); ++layer) {
5108 int w = utexD->m_pixelSize.width();
5109 int h = utexD->m_pixelSize.height();
5110 int depth = is3D ? qMax(1, utexD->m_depth) : 1;
5113 subresourceBarrier(cbD, utexD->image,
5114 origLayout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
5115 origAccess, VK_ACCESS_TRANSFER_READ_BIT,
5116 origStage, VK_PIPELINE_STAGE_TRANSFER_BIT,
5120 subresourceBarrier(cbD, utexD->image,
5121 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
5122 VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
5123 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
5128 subresourceBarrier(cbD, utexD->image,
5129 origLayout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
5130 origAccess, VK_ACCESS_TRANSFER_WRITE_BIT,
5131 origStage, VK_PIPELINE_STAGE_TRANSFER_BIT,
5135 VkImageBlit region = {};
5136 region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
5137 region.srcSubresource.mipLevel = uint32_t(level) - 1;
5138 region.srcSubresource.baseArrayLayer = uint32_t(layer);
5139 region.srcSubresource.layerCount = 1;
5141 region.srcOffsets[1].x = qMax(1, w);
5142 region.srcOffsets[1].y = qMax(1, h);
5143 region.srcOffsets[1].z = qMax(1, depth);
5145 region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
5146 region.dstSubresource.mipLevel = uint32_t(level);
5147 region.dstSubresource.baseArrayLayer = uint32_t(layer);
5148 region.dstSubresource.layerCount = 1;
5150 region.dstOffsets[1].x = qMax(1, w >> 1);
5151 region.dstOffsets[1].y = qMax(1, h >> 1);
5152 region.dstOffsets[1].z = qMax(1, depth >> 1);
5156 cmd.args.blitImage.src = utexD->image;
5157 cmd.args.blitImage.srcLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
5158 cmd.args.blitImage.dst = utexD->image;
5159 cmd.args.blitImage.dstLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
5160 cmd.args.blitImage.filter = VK_FILTER_LINEAR;
5161 cmd.args.blitImage.desc = region;
5169 subresourceBarrier(cbD, utexD->image,
5170 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, origLayout,
5171 VK_ACCESS_TRANSFER_READ_BIT, origAccess,
5172 VK_PIPELINE_STAGE_TRANSFER_BIT, origStage,
5174 0,
int(utexD->mipLevelCount) - 1);
5175 subresourceBarrier(cbD, utexD->image,
5176 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, origLayout,
5177 VK_ACCESS_TRANSFER_WRITE_BIT, origAccess,
5178 VK_PIPELINE_STAGE_TRANSFER_BIT, origStage,
5180 int(utexD->mipLevelCount) - 1, 1);
5192 if (bufD->pendingDynamicUpdates[slot].isEmpty())
5195 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
5197 VmaAllocation a = toVmaAllocation(bufD->allocations[slot]);
5201 VkResult err = vmaMapMemory(toVmaAllocator(allocator), a, &p);
5202 if (err != VK_SUCCESS) {
5203 qWarning(
"Failed to map buffer: %d", err);
5206 quint32 changeBegin = UINT32_MAX;
5207 quint32 changeEnd = 0;
5208 for (
const QVkBuffer::DynamicUpdate &u : std::as_const(bufD->pendingDynamicUpdates[slot])) {
5209 memcpy(
static_cast<
char *>(p) + u.offset, u.data.constData(), u.data.size());
5210 if (u.offset < changeBegin)
5211 changeBegin = u.offset;
5212 if (u.offset + u.data.size() > changeEnd)
5213 changeEnd = u.offset + u.data.size();
5215 if (changeBegin < UINT32_MAX && changeBegin < changeEnd)
5216 vmaFlushAllocation(toVmaAllocator(allocator), a, changeBegin, changeEnd - changeBegin);
5217 vmaUnmapMemory(toVmaAllocator(allocator), a);
5219 bufD->pendingDynamicUpdates[slot].clear();
5225 vmaDestroyBuffer(toVmaAllocator(allocator), e.buffer.buffers[i], toVmaAllocation(e.buffer.allocations[i]));
5226 vmaDestroyBuffer(toVmaAllocator(allocator), e.buffer.stagingBuffers[i], toVmaAllocation(e.buffer.stagingAllocations[i]));
5232 df->vkDestroyImageView(dev, e.renderBuffer.imageView,
nullptr);
5233 df->vkDestroyImage(dev, e.renderBuffer.image,
nullptr);
5234 df->vkFreeMemory(dev, e.renderBuffer.memory,
nullptr);
5239 df->vkDestroyImageView(dev, e.texture.imageView,
nullptr);
5240 vmaDestroyImage(toVmaAllocator(allocator), e.texture.image, toVmaAllocation(e.texture.allocation));
5242 vmaDestroyBuffer(toVmaAllocator(allocator), e.texture.stagingBuffers[i], toVmaAllocation(e.texture.stagingAllocations[i]));
5243 for (
int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i) {
5244 if (e.texture.extraImageViews[i])
5245 df->vkDestroyImageView(dev, e.texture.extraImageViews[i],
nullptr);
5251 df->vkDestroySampler(dev, e.sampler.sampler,
nullptr);
5256 qsizetype keepBegin = releaseQueue.size();
5257 for (qsizetype i = keepBegin - 1; i >= 0; --i) {
5259 if (forced || currentFrameSlot == e.lastActiveFrameSlot || e.lastActiveFrameSlot < 0) {
5262 df->vkDestroyPipeline(dev, e.pipelineState.pipeline,
nullptr);
5263 df->vkDestroyPipelineLayout(dev, e.pipelineState.layout,
nullptr);
5266 df->vkDestroyDescriptorSetLayout(dev, e.shaderResourceBindings.layout,
nullptr);
5267 if (e.shaderResourceBindings.poolIndex >= 0) {
5268 descriptorPools[e.shaderResourceBindings.poolIndex].refCount -= 1;
5269 Q_ASSERT(descriptorPools[e.shaderResourceBindings.poolIndex].refCount >= 0);
5276 qrhivk_releaseRenderBuffer(e, dev,
df);
5282 qrhivk_releaseSampler(e, dev,
df);
5285 df->vkDestroyFramebuffer(dev, e.textureRenderTarget.fb,
nullptr);
5287 df->vkDestroyImageView(dev, e.textureRenderTarget.rtv[att],
nullptr);
5288 df->vkDestroyImageView(dev, e.textureRenderTarget.resrtv[att],
nullptr);
5290 df->vkDestroyImageView(dev, e.textureRenderTarget.dsv,
nullptr);
5291 df->vkDestroyImageView(dev, e.textureRenderTarget.resdsv,
nullptr);
5292 df->vkDestroyImageView(dev, e.textureRenderTarget.shadingRateMapView,
nullptr);
5295 df->vkDestroyRenderPass(dev, e.renderPass.rp,
nullptr);
5298 vmaDestroyBuffer(toVmaAllocator(allocator), e.stagingBuffer.stagingBuffer, toVmaAllocation(e.stagingBuffer.stagingAllocation));
5300 case QRhiVulkan::DeferredReleaseEntry::SecondaryCommandBuffer:
5301 freeSecondaryCbs[e.lastActiveFrameSlot].append(e.secondaryCommandBuffer.cb);
5307 }
else if (--keepBegin != i) {
5308 releaseQueue[keepBegin] = std::move(releaseQueue[i]);
5312 releaseQueue.remove(0, keepBegin);
5317 QVarLengthArray<std::function<
void()>, 4> completedCallbacks;
5319 for (
int i = activeTextureReadbacks.size() - 1; i >= 0; --i) {
5321 if (forced || currentFrameSlot == readback.activeFrameSlot || readback.activeFrameSlot < 0) {
5322 readback.result->format = readback.format;
5323 readback.result->pixelSize = readback.rect.size();
5324 readback.result->data.resizeForOverwrite(readback.byteSize);
5326 if (isStencilTextureFormat(readback.format)) {
5334 const quint64 pixelCount =
5335 quint64(readback.rect.width()) * quint64(readback.rect.height());
5336 const quint64 depthPlaneByteSize = pixelCount * 4;
5338 planar.resizeForOverwrite(qsizetype(depthPlaneByteSize + pixelCount));
5339 VkResult err = vmaCopyAllocationToMemory(toVmaAllocator(allocator),
5340 toVmaAllocation(readback.stagingAlloc),
5341 0, planar.data(), size_t(planar.size()));
5342 if (err == VK_SUCCESS) {
5343 const quint32 *depthPlane =
reinterpret_cast<
const quint32 *>(planar.constData());
5344 const quint8 *stencilPlane =
reinterpret_cast<
const quint8 *>(planar.constData() + depthPlaneByteSize);
5345 char *dst = readback.result->data.data();
5346 if (readback.format == QRhiTexture::D32FS8) {
5349 for (quint32 px = 0; px < pixelCount; ++px) {
5350 const quint32 stencilWord = stencilPlane[px];
5351 memcpy(dst + px * 8, &depthPlane[px],
sizeof(quint32));
5352 memcpy(dst + px * 8 + 4, &stencilWord,
sizeof(quint32));
5357 for (quint32 px = 0; px < pixelCount; ++px) {
5360 const quint32 combined = ((depthPlane[px] & 0x00FFFFFFu) << 8) | stencilPlane[px];
5361 memcpy(dst + px * 4, &combined,
sizeof(quint32));
5365 qWarning(
"Failed to copy texture readback buffer of size %lld: %d",
5366 qint64(planar.size()), err);
5367 readback.result->data.clear();
5370 VkResult err = vmaCopyAllocationToMemory(toVmaAllocator(allocator),
5371 toVmaAllocation(readback.stagingAlloc),
5372 0, readback.result->data.data(), readback.byteSize);
5373 if (err != VK_SUCCESS) {
5374 qWarning(
"Failed to copy texture readback buffer of size %u: %d", readback.byteSize, err);
5375 readback.result->data.clear();
5376 }
else if (readback.format == QRhiTexture::D24) {
5381 char *p = readback.result->data.data();
5382 for (quint32 px = 0, count = readback.byteSize / 4; px < count; ++px)
5383 qToUnaligned((qFromUnaligned<quint32>(p + px * 4) & 0x00FFFFFFu) << 8, p + px * 4);
5387 vmaDestroyBuffer(toVmaAllocator(allocator), readback.stagingBuf, toVmaAllocation(readback.stagingAlloc));
5389 if (readback.result->completed)
5390 completedCallbacks.append(readback.result->completed);
5392 activeTextureReadbacks.remove(i);
5396 for (
int i = activeBufferReadbacks.size() - 1; i >= 0; --i) {
5398 if (forced || currentFrameSlot == readback.activeFrameSlot || readback.activeFrameSlot < 0) {
5399 readback.result->data.resizeForOverwrite(readback.byteSize);
5400 VkResult err = vmaCopyAllocationToMemory(toVmaAllocator(allocator),
5401 toVmaAllocation(readback.stagingAlloc),
5402 0, readback.result->data.data(), readback.byteSize);
5403 if (err != VK_SUCCESS) {
5404 qWarning(
"Failed to copy buffer readback buffer of size %d: %d", readback.byteSize, err);
5405 readback.result->data.clear();
5408 vmaDestroyBuffer(toVmaAllocator(allocator), readback.stagingBuf, toVmaAllocation(readback.stagingAlloc));
5410 if (readback.result->completed)
5411 completedCallbacks.append(readback.result->completed);
5413 activeBufferReadbacks.remove(i);
5417 for (
const auto &f : completedCallbacks)
5422 VkSampleCountFlagBits mask;
5424} qvk_sampleCounts[] = {
5426 { VK_SAMPLE_COUNT_1_BIT, 1 },
5427 { VK_SAMPLE_COUNT_2_BIT, 2 },
5428 { VK_SAMPLE_COUNT_4_BIT, 4 },
5429 { VK_SAMPLE_COUNT_8_BIT, 8 },
5430 { VK_SAMPLE_COUNT_16_BIT, 16 },
5431 { VK_SAMPLE_COUNT_32_BIT, 32 },
5432 { VK_SAMPLE_COUNT_64_BIT, 64 }
5437 const VkPhysicalDeviceLimits *limits = &physDevProperties.limits;
5438 VkSampleCountFlags color = limits->framebufferColorSampleCounts;
5439 VkSampleCountFlags depth = limits->framebufferDepthSampleCounts;
5440 VkSampleCountFlags stencil = limits->framebufferStencilSampleCounts;
5443 for (
const auto &qvk_sampleCount : qvk_sampleCounts) {
5444 if ((color & qvk_sampleCount.mask)
5445 && (depth & qvk_sampleCount.mask)
5446 && (stencil & qvk_sampleCount.mask))
5448 result.append(qvk_sampleCount.count);
5457 const int s = effectiveSampleCount(sampleCount);
5459 for (
const auto &qvk_sampleCount : qvk_sampleCounts) {
5460 if (qvk_sampleCount.count == s)
5461 return qvk_sampleCount.mask;
5464 Q_UNREACHABLE_RETURN(VK_SAMPLE_COUNT_1_BIT);
5469 QList<QSize> result;
5470#ifdef VK_KHR_fragment_shading_rate
5471 sampleCount = qMax(1, sampleCount);
5472 VkSampleCountFlagBits mask = VK_SAMPLE_COUNT_1_BIT;
5473 for (
const auto &qvk_sampleCount : qvk_sampleCounts) {
5474 if (qvk_sampleCount.count == sampleCount) {
5475 mask = qvk_sampleCount.mask;
5479 for (
const VkPhysicalDeviceFragmentShadingRateKHR &s : fragmentShadingRates) {
5480 if (s.sampleCounts & mask)
5481 result.append(QSize(
int(s.fragmentSize.width),
int(s.fragmentSize.height)));
5484 Q_UNUSED(sampleCount);
5485 result.append(QSize(1, 1));
5492 cbD->passResTrackers.emplace_back();
5497 cmd.args.transitionResources.trackerIndex = cbD->passResTrackers.size() - 1;
5504 for (
auto it = cbD->commands.begin(), end = cbD->commands.end(); it != end; ++it) {
5508 df->vkCmdCopyBuffer(cbD->cb, cmd.args.copyBuffer.src, cmd.args.copyBuffer.dst,
5509 1, &cmd.args.copyBuffer.desc);
5512 df->vkCmdFillBuffer(cbD->cb, cmd.args.fillBuffer.dst, cmd.args.fillBuffer.offset,
5513 cmd.args.fillBuffer.size, cmd.args.fillBuffer.data);
5516 df->vkCmdCopyBufferToImage(cbD->cb, cmd.args.copyBufferToImage.src, cmd.args.copyBufferToImage.dst,
5517 cmd.args.copyBufferToImage.dstLayout,
5518 uint32_t(cmd.args.copyBufferToImage.count),
5519 cbD->pools.bufferImageCopy.constData() + cmd.args.copyBufferToImage.bufferImageCopyIndex);
5522 df->vkCmdCopyImage(cbD->cb, cmd.args.copyImage.src, cmd.args.copyImage.srcLayout,
5523 cmd.args.copyImage.dst, cmd.args.copyImage.dstLayout,
5524 1, &cmd.args.copyImage.desc);
5527 df->vkCmdCopyImageToBuffer(cbD->cb, cmd.args.copyImageToBuffer.src, cmd.args.copyImageToBuffer.srcLayout,
5528 cmd.args.copyImageToBuffer.dst,
5529 uint32_t(cmd.args.copyImageToBuffer.count),
5530 cbD->pools.bufferImageCopy.constData() + cmd.args.copyImageToBuffer.bufferImageCopyIndex);
5533 df->vkCmdPipelineBarrier(cbD->cb, cmd.args.imageBarrier.srcStageMask, cmd.args.imageBarrier.dstStageMask,
5534 0, 0,
nullptr, 0,
nullptr,
5535 cmd.args.imageBarrier.count, cbD->pools.imageBarrier.constData() + cmd.args.imageBarrier.index);
5538 df->vkCmdPipelineBarrier(cbD->cb, cmd.args.bufferBarrier.srcStageMask, cmd.args.bufferBarrier.dstStageMask,
5540 cmd.args.bufferBarrier.count, cbD->pools.bufferBarrier.constData() + cmd.args.bufferBarrier.index,
5544 const auto &barrier = cmd.args.imageAndBufferBarrier;
5545 const VkBufferMemoryBarrier *bufferBarrierData = barrier.bufferCount
5546 ? cbD->pools.bufferBarrier.constData() + barrier.bufferIndex :
nullptr;
5547 const VkImageMemoryBarrier *imageBarrierData = barrier.imageCount
5548 ? cbD->pools.imageBarrier.constData() + barrier.imageIndex :
nullptr;
5549 df->vkCmdPipelineBarrier(cbD->cb, barrier.srcStageMask, barrier.dstStageMask,
5551 barrier.bufferCount, bufferBarrierData,
5552 barrier.imageCount, imageBarrierData);
5555 df->vkCmdBlitImage(cbD->cb, cmd.args.blitImage.src, cmd.args.blitImage.srcLayout,
5556 cmd.args.blitImage.dst, cmd.args.blitImage.dstLayout,
5557 1, &cmd.args.blitImage.desc,
5558 cmd.args.blitImage.filter);
5561 cmd.args.beginRenderPass.desc.pClearValues = cbD->pools.clearValue.constData() + cmd.args.beginRenderPass.clearValueIndex;
5562 df->vkCmdBeginRenderPass(cbD->cb, &cmd.args.beginRenderPass.desc,
5563 cmd.args.beginRenderPass.useSecondaryCb ? VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS
5564 : VK_SUBPASS_CONTENTS_INLINE);
5567 VkMemoryBarrier barrier = {};
5568 barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
5569 barrier.pNext =
nullptr;
5570 barrier.dstAccessMask = cmd.args.memoryBarrier.dstAccessMask;
5571 barrier.srcAccessMask = cmd.args.memoryBarrier.srcAccessMask;
5572 df->vkCmdPipelineBarrier(cbD->cb, cmd.args.memoryBarrier.srcStageMask, cmd.args.memoryBarrier.dstStageMask, cmd.args.memoryBarrier.dependencyFlags,
5578 df->vkCmdEndRenderPass(cbD->cb);
5581 df->vkCmdBindPipeline(cbD->cb, cmd.args.bindPipeline.bindPoint, cmd.args.bindPipeline.pipeline);
5585 const uint32_t *offsets =
nullptr;
5586 if (cmd.args.bindDescriptorSet.dynamicOffsetCount > 0)
5587 offsets = cbD->pools.dynamicOffset.constData() + cmd.args.bindDescriptorSet.dynamicOffsetIndex;
5588 df->vkCmdBindDescriptorSets(cbD->cb, cmd.args.bindDescriptorSet.bindPoint,
5589 cmd.args.bindDescriptorSet.pipelineLayout,
5590 0, 1, &cmd.args.bindDescriptorSet.descSet,
5591 uint32_t(cmd.args.bindDescriptorSet.dynamicOffsetCount),
5596 df->vkCmdBindVertexBuffers(cbD->cb, uint32_t(cmd.args.bindVertexBuffer.startBinding),
5597 uint32_t(cmd.args.bindVertexBuffer.count),
5598 cbD->pools.vertexBuffer.constData() + cmd.args.bindVertexBuffer.vertexBufferIndex,
5599 cbD->pools.vertexBufferOffset.constData() + cmd.args.bindVertexBuffer.vertexBufferOffsetIndex);
5602 df->vkCmdBindIndexBuffer(cbD->cb, cmd.args.bindIndexBuffer.buf,
5603 cmd.args.bindIndexBuffer.ofs, cmd.args.bindIndexBuffer.type);
5606 df->vkCmdSetViewport(cbD->cb, 0, 1, &cmd.args.setViewport.viewport);
5609 df->vkCmdSetScissor(cbD->cb, 0, 1, &cmd.args.setScissor.scissor);
5612 df->vkCmdSetBlendConstants(cbD->cb, cmd.args.setBlendConstants.c);
5615 df->vkCmdSetStencilReference(cbD->cb, VK_STENCIL_FRONT_AND_BACK, cmd.args.setStencilRef.ref);
5618 df->vkCmdPushConstants(cbD->cb,
5619 cmd.args.setPushConstants.layout,
5620 cmd.args.setPushConstants.stages,
5621 cmd.args.setPushConstants.offset,
5622 cmd.args.setPushConstants.size,
5623 cbD->pools.pushConstantData.constData() + cmd.args.setPushConstants.dataIndex);
5626 df->vkCmdDraw(cbD->cb, cmd.args.draw.vertexCount, cmd.args.draw.instanceCount,
5627 cmd.args.draw.firstVertex, cmd.args.draw.firstInstance);
5630 df->vkCmdDrawIndexed(cbD->cb, cmd.args.drawIndexed.indexCount, cmd.args.drawIndexed.instanceCount,
5631 cmd.args.drawIndexed.firstIndex, cmd.args.drawIndexed.vertexOffset,
5632 cmd.args.drawIndexed.firstInstance);
5635 df->vkCmdDrawIndirect(cbD->cb, cmd.args.drawIndirect.indirectBuffer,
5636 cmd.args.drawIndirect.indirectBufferOffset,
5637 cmd.args.drawIndirect.drawCount,
5638 cmd.args.drawIndirect.stride);
5641 df->vkCmdDrawIndexedIndirect(cbD->cb, cmd.args.drawIndexedIndirect.indirectBuffer,
5642 cmd.args.drawIndexedIndirect.indirectBufferOffset,
5643 cmd.args.drawIndexedIndirect.drawCount,
5644 cmd.args.drawIndexedIndirect.stride);
5646#ifdef VK_VERSION_1_2
5647 case QVkCommandBuffer::Command::DrawIndirectCount:
5648 vkCmdDrawIndirectCount(cbD->cb,
5649 cmd.args.drawIndirectCount.indirectBuffer,
5650 cmd.args.drawIndirectCount.indirectBufferOffset,
5651 cmd.args.drawIndirectCount.countBuffer,
5652 cmd.args.drawIndirectCount.countBufferOffset,
5653 cmd.args.drawIndirectCount.maxDrawCount,
5654 cmd.args.drawIndirectCount.stride);
5656 case QVkCommandBuffer::Command::DrawIndexedIndirectCount:
5657 vkCmdDrawIndexedIndirectCount(cbD->cb,
5658 cmd.args.drawIndexedIndirectCount.indirectBuffer,
5659 cmd.args.drawIndexedIndirectCount.indirectBufferOffset,
5660 cmd.args.drawIndexedIndirectCount.countBuffer,
5661 cmd.args.drawIndexedIndirectCount.countBufferOffset,
5662 cmd.args.drawIndexedIndirectCount.maxDrawCount,
5663 cmd.args.drawIndexedIndirectCount.stride);
5667#ifdef VK_EXT_debug_utils
5668 cmd.args.debugMarkerBegin.label.pLabelName =
5669 cbD->pools.debugMarkerData[cmd.args.debugMarkerBegin.labelNameIndex].constData();
5670 vkCmdBeginDebugUtilsLabelEXT(cbD->cb, &cmd.args.debugMarkerBegin.label);
5674#ifdef VK_EXT_debug_utils
5675 vkCmdEndDebugUtilsLabelEXT(cbD->cb);
5679#ifdef VK_EXT_debug_utils
5680 cmd.args.debugMarkerInsert.label.pLabelName =
5681 cbD->pools.debugMarkerData[cmd.args.debugMarkerInsert.labelNameIndex].constData();
5682 vkCmdInsertDebugUtilsLabelEXT(cbD->cb, &cmd.args.debugMarkerInsert.label);
5689 df->vkCmdDispatch(cbD->cb, uint32_t(cmd.args.dispatch.x), uint32_t(cmd.args.dispatch.y), uint32_t(cmd.args.dispatch.z));
5692 df->vkCmdDispatchIndirect(cbD->cb,
5693 cmd.args.dispatchIndirect.indirectBuffer,
5694 cmd.args.dispatchIndirect.indirectBufferOffset);
5697 df->vkCmdExecuteCommands(cbD->cb, 1, &cmd.args.executeSecondary.cb);
5701#ifdef VK_KHR_fragment_shading_rate
5702 VkFragmentShadingRateCombinerOpKHR op[2] = {
5703 VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR,
5704 VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR
5706 VkExtent2D size = { cmd.args.setShadingRate.w, cmd.args.setShadingRate.h };
5707 vkCmdSetFragmentShadingRateKHR(cbD->cb, &size, op);
5720 case QRhiPassResourceTracker::BufIndirectDraw:
5721 return VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
5722 case QRhiPassResourceTracker::BufVertexInput:
5723 return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
5724 case QRhiPassResourceTracker::BufIndexRead:
5725 return VK_ACCESS_INDEX_READ_BIT;
5726 case QRhiPassResourceTracker::BufUniformRead:
5727 return VK_ACCESS_UNIFORM_READ_BIT;
5728 case QRhiPassResourceTracker::BufStorageLoad:
5729 return VK_ACCESS_SHADER_READ_BIT;
5730 case QRhiPassResourceTracker::BufStorageStore:
5731 return VK_ACCESS_SHADER_WRITE_BIT;
5732 case QRhiPassResourceTracker::BufStorageLoadStore:
5733 return VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
5744 case QRhiPassResourceTracker::BufIndirectDrawStage:
5745 return VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
5746 case QRhiPassResourceTracker::BufVertexInputStage:
5747 return VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
5748 case QRhiPassResourceTracker::BufVertexStage:
5749 return VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
5750 case QRhiPassResourceTracker::BufTCStage:
5751 return VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT;
5752 case QRhiPassResourceTracker::BufTEStage:
5753 return VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT;
5754 case QRhiPassResourceTracker::BufFragmentStage:
5755 return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
5756 case QRhiPassResourceTracker::BufComputeStage:
5757 return VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
5758 case QRhiPassResourceTracker::BufGeometryStage:
5759 return VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT;
5770 u.access = VkAccessFlags(usage
.access);
5771 u.stage = VkPipelineStageFlags(usage
.stage);
5778 case QRhiPassResourceTracker::TexSample:
5779 return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
5780 case QRhiPassResourceTracker::TexColorOutput:
5781 return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
5782 case QRhiPassResourceTracker::TexDepthOutput:
5783 case QRhiPassResourceTracker::TexDepthResolveOutput:
5784 return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
5785 case QRhiPassResourceTracker::TexStorageLoad:
5786 case QRhiPassResourceTracker::TexStorageStore:
5787 case QRhiPassResourceTracker::TexStorageLoadStore:
5788 return VK_IMAGE_LAYOUT_GENERAL;
5789 case QRhiPassResourceTracker::TexShadingRate:
5790#ifdef VK_KHR_fragment_shading_rate
5791 return VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR;
5793 return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
5799 return VK_IMAGE_LAYOUT_GENERAL;
5805 case QRhiPassResourceTracker::TexSample:
5806 return VK_ACCESS_SHADER_READ_BIT;
5807 case QRhiPassResourceTracker::TexColorOutput:
5808 return VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
5809 case QRhiPassResourceTracker::TexDepthOutput:
5810 return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
5811 case QRhiPassResourceTracker::TexDepthResolveOutput:
5814 return VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
5815 case QRhiPassResourceTracker::TexStorageLoad:
5816 return VK_ACCESS_SHADER_READ_BIT;
5817 case QRhiPassResourceTracker::TexStorageStore:
5818 return VK_ACCESS_SHADER_WRITE_BIT;
5819 case QRhiPassResourceTracker::TexStorageLoadStore:
5820 return VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
5833 case QRhiPassResourceTracker::TexVertexStage:
5834 return VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
5835 case QRhiPassResourceTracker::TexTCStage:
5836 return VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT;
5837 case QRhiPassResourceTracker::TexTEStage:
5838 return VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT;
5839 case QRhiPassResourceTracker::TexFragmentStage:
5840 return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
5841 case QRhiPassResourceTracker::TexColorOutputStage:
5842 return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
5843 case QRhiPassResourceTracker::TexDepthOutputStage:
5844 return VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
5845 case QRhiPassResourceTracker::TexComputeStage:
5846 return VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
5847 case QRhiPassResourceTracker::TexGeometryStage:
5848 return VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT;
5859 u.layout = VkImageLayout(usage
.layout);
5860 u.access = VkAccessFlags(usage
.access);
5861 u.stage = VkPipelineStageFlags(usage
.stage);
5872 const VkAccessFlags newAccess = toVkAccess(access);
5873 const VkPipelineStageFlags newStage = toVkPipelineStage(stage);
5874 if (u.access == newAccess && u.stage == newStage) {
5875 if (!accessIsWrite(newAccess))
5879 u.access = newAccess;
5889 const VkAccessFlags newAccess = toVkAccess(access);
5890 const VkPipelineStageFlags newStage = toVkPipelineStage(stage);
5891 const VkImageLayout newLayout = toVkLayout(access);
5892 if (u.access == newAccess && u.stage == newStage && u.layout == newLayout) {
5893 if (!accessIsWrite(newAccess))
5897 u.layout = newLayout;
5898 u.access = newAccess;
5907 for (
const auto &[rhiB, trackedB]: tracker.buffers()) {
5908 QVkBuffer *bufD =
QRHI_RES(QVkBuffer, rhiB);
5909 VkAccessFlags access = toVkAccess(trackedB.access);
5910 VkPipelineStageFlags stage = toVkPipelineStage(trackedB.stage);
5911 QVkBuffer::UsageState s = toVkBufferUsageState(trackedB.stateAtPassBegin);
5914 if (s.access == access && s.stage == stage) {
5915 if (!accessIsWrite(access))
5918 VkBufferMemoryBarrier bufMemBarrier = {};
5919 bufMemBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
5920 bufMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
5921 bufMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
5922 bufMemBarrier.srcAccessMask = s.access;
5923 bufMemBarrier.dstAccessMask = access;
5924 bufMemBarrier.buffer = bufD->buffers[trackedB.slot];
5925 bufMemBarrier.size = VK_WHOLE_SIZE;
5926 df->vkCmdPipelineBarrier(cbD->cb, s.stage, stage, 0,
5932 for (
const auto &[rhiT, trackedT]: tracker.textures()) {
5933 QVkTexture *texD =
QRHI_RES(QVkTexture, rhiT);
5934 VkImageLayout layout = toVkLayout(trackedT.access);
5935 VkAccessFlags access = toVkAccess(trackedT.access);
5936 VkPipelineStageFlags stage = toVkPipelineStage(trackedT.stage);
5937 QVkTexture::UsageState s = toVkTextureUsageState(trackedT.stateAtPassBegin);
5938 if (s.access == access && s.stage == stage && s.layout == layout) {
5939 if (!accessIsWrite(access))
5942 VkImageMemoryBarrier barrier = {};
5943 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
5944 barrier.subresourceRange.aspectMask = aspectMaskForTextureFormat(texD->m_format);
5945 barrier.subresourceRange.baseMipLevel = 0;
5946 barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS;
5947 barrier.subresourceRange.baseArrayLayer = 0;
5948 barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
5949 barrier.oldLayout = s.layout;
5950 barrier.newLayout = layout;
5951 barrier.srcAccessMask = s.access;
5952 barrier.dstAccessMask = access;
5953 barrier.image = texD->image;
5954 VkPipelineStageFlags srcStage = s.stage;
5957 srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
5958 df->vkCmdPipelineBarrier(cbD->cb, srcStage, stage, 0,
5967 if (!vkGetPhysicalDeviceSurfaceCapabilitiesKHR
5968 || !vkGetPhysicalDeviceSurfaceFormatsKHR
5969 || !vkGetPhysicalDeviceSurfacePresentModesKHR)
5971 qWarning(
"Physical device surface queries not available");
5975 return new QVkSwapChain(
this);
5978QRhiBuffer *
QRhiVulkan::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
5980 return new QVkBuffer(
this, type, usage, size);
5985 return int(ubufAlign);
6008 static constexpr QMatrix4x4 m(1.0f, 0.0f, 0.0f, 0.0f,
6009 0.0f, -1.0f, 0.0f, 0.0f,
6010 0.0f, 0.0f, 0.5f, 0.5f,
6011 0.0f, 0.0f, 0.0f, 1.0f);
6020 if (format >= QRhiTexture::BC1 && format <= QRhiTexture::BC7) {
6021 if (!physDevFeatures.textureCompressionBC)
6025 if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ETC2_RGBA8) {
6026 if (!physDevFeatures.textureCompressionETC2)
6030 if (format >= QRhiTexture::ASTC_4x4 && format <= QRhiTexture::ASTC_12x12) {
6031 if (!physDevFeatures.textureCompressionASTC_LDR)
6035 VkFormat vkformat = toVkTextureFormat(format, flags);
6036 VkFormatProperties props;
6037 f->vkGetPhysicalDeviceFormatProperties(physDev, vkformat, &props);
6038 return (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0;
6044 case QRhi::MultisampleTexture:
6046 case QRhi::MultisampleRenderBuffer:
6048 case QRhi::DebugMarkers:
6049 return caps.debugUtils;
6050 case QRhi::Timestamps:
6051 return timestampValidBits != 0;
6052 case QRhi::Instancing:
6054 case QRhi::CustomInstanceStepRate:
6055 return caps.vertexAttribDivisor;
6056 case QRhi::PrimitiveRestart:
6058 case QRhi::NonDynamicUniformBuffers:
6060 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
6062 case QRhi::NPOTTextureRepeat:
6064 case QRhi::RedOrAlpha8IsRed:
6066 case QRhi::ElementIndexUint:
6069 return caps.compute;
6070 case QRhi::FragmentStoresAndAtomics:
6071 return physDevFeatures.fragmentStoresAndAtomics;
6072 case QRhi::WideLines:
6073 return caps.wideLines;
6074 case QRhi::VertexShaderPointSize:
6076 case QRhi::BaseVertex:
6078 case QRhi::BaseInstance:
6080 case QRhi::TriangleFanTopology:
6082 case QRhi::ReadBackNonUniformBuffer:
6084 case QRhi::ReadBackNonBaseMipLevel:
6086 case QRhi::TexelFetch:
6088 case QRhi::RenderToNonBaseMipLevel:
6090 case QRhi::IntAttributes:
6092 case QRhi::ScreenSpaceDerivatives:
6094 case QRhi::ReadBackAnyTextureFormat:
6096 case QRhi::PipelineCacheDataLoadSave:
6098 case QRhi::ImageDataStride:
6100 case QRhi::RenderBufferImport:
6102 case QRhi::ThreeDimensionalTextures:
6104 case QRhi::RenderTo3DTextureSlice:
6105 return caps.texture3DSliceAs2D;
6106 case QRhi::TextureArrays:
6108 case QRhi::Tessellation:
6109 return caps.tessellation;
6110 case QRhi::GeometryShader:
6111 return caps.geometryShader;
6112 case QRhi::TextureArrayRange:
6114 case QRhi::NonFillPolygonMode:
6115 return caps.nonFillPolygonMode;
6116 case QRhi::OneDimensionalTextures:
6118 case QRhi::OneDimensionalTextureMipmaps:
6120 case QRhi::HalfAttributes:
6122 case QRhi::RenderToOneDimensionalTexture:
6124 case QRhi::ThreeDimensionalTextureMipmaps:
6126 case QRhi::MultiView:
6127 return caps.multiView;
6128 case QRhi::TextureViewFormat:
6130 case QRhi::ResolveDepthStencil:
6131 return caps.renderPass2KHR && caps.depthStencilResolveKHR;
6132 case QRhi::VariableRateShading:
6133 return caps.renderPass2KHR && caps.perDrawShadingRate;
6134 case QRhi::VariableRateShadingMap:
6135 case QRhi::VariableRateShadingMapWithTexture:
6136 return caps.renderPass2KHR && caps.imageBasedShadingRate;
6137 case QRhi::DualSourceBlend:
6138 return caps.dualSrcBlend;
6139 case QRhi::BaseInstanceIndirect:
6140 return caps.drawIndirectFirstInstance;
6141 case QRhi::PerRenderTargetBlending:
6142 case QRhi::SampleVariables:
6144 case QRhi::InstanceIndexIncludesBaseInstance:
6146 case QRhi::DepthClamp:
6147 return caps.depthClamp;
6148 case QRhi::DrawIndirect:
6150 case QRhi::DrawIndirectMulti:
6151 return caps.drawIndirectMulti;
6152 case QRhi::ShaderDrawParameters:
6153 return caps.shaderDrawParameters;
6154 case QRhi::DispatchIndirect:
6156 case QRhi::PushConstants:
6158 case QRhi::DrawIndirectCount:
6159 return caps.drawIndirectCount;
6160 case QRhi::BufferToBufferCopy:
6162 case QRhi::StaticBuffersOnGpuTimeline:
6165 Q_UNREACHABLE_RETURN(
false);
6172 case QRhi::TextureSizeMin:
6174 case QRhi::TextureSizeMax:
6175 return int(physDevProperties.limits.maxImageDimension2D);
6176 case QRhi::MaxColorAttachments:
6177 return int(physDevProperties.limits.maxColorAttachments);
6178 case QRhi::FramesInFlight:
6180 case QRhi::MaxAsyncReadbackFrames:
6182 case QRhi::MaxThreadGroupsPerDimension:
6184 return int(qMin<uint32_t>(INT_MAX,
6185 qMin(physDevProperties.limits.maxComputeWorkGroupCount[0],
6186 qMin(physDevProperties.limits.maxComputeWorkGroupCount[1],
6187 physDevProperties.limits.maxComputeWorkGroupCount[2]))));
6188 case QRhi::MaxThreadsPerThreadGroup:
6189 return int(physDevProperties.limits.maxComputeWorkGroupInvocations);
6190 case QRhi::MaxThreadGroupX:
6191 return int(physDevProperties.limits.maxComputeWorkGroupSize[0]);
6192 case QRhi::MaxThreadGroupY:
6193 return int(physDevProperties.limits.maxComputeWorkGroupSize[1]);
6194 case QRhi::MaxThreadGroupZ:
6195 return int(physDevProperties.limits.maxComputeWorkGroupSize[2]);
6196 case QRhi::TextureArraySizeMax:
6197 return int(physDevProperties.limits.maxImageArrayLayers);
6198 case QRhi::MaxUniformBufferRange:
6199 return int(qMin<uint32_t>(INT_MAX, physDevProperties.limits.maxUniformBufferRange));
6200 case QRhi::MaxVertexInputs:
6201 return physDevProperties.limits.maxVertexInputAttributes;
6202 case QRhi::MaxVertexOutputs:
6203 return physDevProperties.limits.maxVertexOutputComponents / 4;
6204 case QRhi::MaxPushConstantsSize:
6205 return int(physDevProperties.limits.maxPushConstantsSize);
6206 case QRhi::MaxVertexStorageBuffers:
6207 case QRhi::MaxFragmentStorageBuffers:
6209 return int(qMin<uint32_t>(INT_MAX,
6210 physDevProperties.limits.maxPerStageDescriptorStorageBuffers));
6211 case QRhi::MaxStorageBufferBindings:
6212 case QRhi::MaxStorageImageBindings:
6214 case QRhi::ShadingRateImageTileSize:
6215 return caps.imageBasedShadingRateTileSize;
6217 Q_UNREACHABLE_RETURN(0);
6223 return &nativeHandlesStruct;
6228 return driverInfoStruct;
6234 result.totalPipelineCreationTime = totalPipelineCreationTime();
6236 VmaBudget budgets[VK_MAX_MEMORY_HEAPS];
6237 vmaGetHeapBudgets(toVmaAllocator(allocator), budgets);
6239 uint32_t count = toVmaAllocator(allocator)->GetMemoryHeapCount();
6240 for (uint32_t i = 0; i < count; ++i) {
6241 const VmaStatistics &stats(budgets[i].statistics);
6242 result.blockCount += stats.blockCount;
6243 result.allocCount += stats.allocationCount;
6244 result.usedBytes += stats.allocationBytes;
6245 result.unusedBytes += stats.blockBytes - stats.allocationBytes;
6259 QRhiVulkanQueueSubmitParams *sp =
static_cast<QRhiVulkanQueueSubmitParams *>(params);
6263 waitSemaphoresForQueueSubmit.clear();
6264 if (sp->waitSemaphoreCount)
6265 waitSemaphoresForQueueSubmit.append(sp->waitSemaphores, sp->waitSemaphoreCount);
6267 signalSemaphoresForQueueSubmit.clear();
6268 if (sp->signalSemaphoreCount)
6269 signalSemaphoresForQueueSubmit.append(sp->signalSemaphores, sp->signalSemaphoreCount);
6271 waitSemaphoresForPresent.clear();
6272 if (sp->presentWaitSemaphoreCount)
6273 waitSemaphoresForPresent.append(sp->presentWaitSemaphores, sp->presentWaitSemaphoreCount);
6303 if (!pipelineCache || !rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
6306 size_t dataSize = 0;
6307 VkResult err =
df->vkGetPipelineCacheData(dev, pipelineCache, &dataSize,
nullptr);
6308 if (err != VK_SUCCESS) {
6309 qCDebug(QRHI_LOG_INFO,
"Failed to get pipeline cache data size: %d", err);
6310 return QByteArray();
6313 const size_t dataOffset = headerSize + VK_UUID_SIZE;
6314 data.resize(dataOffset + dataSize);
6315 err =
df->vkGetPipelineCacheData(dev, pipelineCache, &dataSize, data.data() + dataOffset);
6316 if (err != VK_SUCCESS) {
6317 qCDebug(QRHI_LOG_INFO,
"Failed to get pipeline cache data of %d bytes: %d",
int(dataSize), err);
6318 return QByteArray();
6322 header.rhiId = pipelineCacheRhiId();
6323 header.arch = quint32(
sizeof(
void*));
6324 header.driverVersion = physDevProperties.driverVersion;
6325 header.vendorId = physDevProperties.vendorID;
6326 header.deviceId = physDevProperties.deviceID;
6327 header.dataSize = quint32(dataSize);
6328 header.uuidSize = VK_UUID_SIZE;
6329 header.reserved = 0;
6330 memcpy(data.data(), &header, headerSize);
6331 memcpy(data.data() + headerSize, physDevProperties.pipelineCacheUUID, VK_UUID_SIZE);
6342 if (data.size() < qsizetype(headerSize)) {
6343 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob size");
6347 memcpy(&header, data.constData(), headerSize);
6349 const quint32 rhiId = pipelineCacheRhiId();
6350 if (header.rhiId != rhiId) {
6351 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: The data is for a different QRhi version or backend (%u, %u)",
6352 rhiId, header.rhiId);
6355 const quint32 arch = quint32(
sizeof(
void*));
6356 if (header.arch != arch) {
6357 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Architecture does not match (%u, %u)",
6361 if (header.driverVersion != physDevProperties.driverVersion) {
6362 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: driverVersion does not match (%u, %u)",
6363 physDevProperties.driverVersion, header.driverVersion);
6366 if (header.vendorId != physDevProperties.vendorID) {
6367 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: vendorID does not match (%u, %u)",
6368 physDevProperties.vendorID, header.vendorId);
6371 if (header.deviceId != physDevProperties.deviceID) {
6372 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: deviceID does not match (%u, %u)",
6373 physDevProperties.deviceID, header.deviceId);
6376 if (header.uuidSize != VK_UUID_SIZE) {
6377 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: VK_UUID_SIZE does not match (%u, %u)",
6378 quint32(VK_UUID_SIZE), header.uuidSize);
6382 if (data.size() < qsizetype(headerSize + VK_UUID_SIZE)) {
6383 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob, no uuid");
6386 if (memcmp(data.constData() + headerSize, physDevProperties.pipelineCacheUUID, VK_UUID_SIZE)) {
6387 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: pipelineCacheUUID does not match");
6391 const size_t dataOffset = headerSize + VK_UUID_SIZE;
6392 if (quint64(data.size()) < quint64(dataOffset) + header.dataSize) {
6393 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob, data missing");
6397 if (pipelineCache) {
6398 df->vkDestroyPipelineCache(dev, pipelineCache,
nullptr);
6399 pipelineCache = VK_NULL_HANDLE;
6402 if (ensurePipelineCache(data.constData() + dataOffset, header.dataSize)) {
6403 qCDebug(QRHI_LOG_INFO,
"Created pipeline cache with initial data of %d bytes",
6404 int(header.dataSize));
6406 qCDebug(QRHI_LOG_INFO,
"Failed to create pipeline cache with initial data specified");
6410QRhiRenderBuffer *
QRhiVulkan::createRenderBuffer(QRhiRenderBuffer::Type type,
const QSize &pixelSize,
6411 int sampleCount, QRhiRenderBuffer::Flags flags,
6412 QRhiTexture::Format backingFormatHint)
6414 return new QVkRenderBuffer(
this, type, pixelSize, sampleCount, flags, backingFormatHint);
6418 const QSize &pixelSize,
int depth,
int arraySize,
6419 int sampleCount, QRhiTexture::Flags flags)
6421 return new QVkTexture(
this, format, pixelSize, depth, arraySize, sampleCount, flags);
6425 QRhiSampler::Filter mipmapMode,
6426 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
6428 return new QVkSampler(
this, magFilter, minFilter, mipmapMode, u, v, w);
6433 return new QVkShadingRateMap(
this);
6437 QRhiTextureRenderTarget::Flags flags)
6444 return new QVkGraphicsPipeline(
this);
6449 return new QVkComputePipeline(
this);
6454 return new QVkShaderResourceBindings(
this);
6460 Q_ASSERT(psD->pipeline);
6466 df->vkCmdBindPipeline(cbD->activeSecondaryCbStack.last(), VK_PIPELINE_BIND_POINT_GRAPHICS, psD->pipeline);
6470 cmd.args.bindPipeline.bindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
6471 cmd.args.bindPipeline.pipeline = psD->pipeline;
6474 cbD->currentGraphicsPipeline = ps;
6475 cbD->currentComputePipeline =
nullptr;
6485 if (psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)) {
6486 if (!cbD->stencilRefValid)
6487 recordStencilRef(cbD, cbD->currentStencilRef);
6497 int dynamicOffsetCount,
6498 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
6508 srb = gfxPsD->m_shaderResourceBindings;
6510 srb = compPsD->m_shaderResourceBindings;
6514 auto &descSetBd(srbD->boundResourceData[currentFrameSlot]);
6515 bool rewriteDescSet =
false;
6516 bool addWriteBarrier =
false;
6517 VkPipelineStageFlags writeBarrierSrcStageMask = 0;
6518 VkPipelineStageFlags writeBarrierDstStageMask = 0;
6522 for (
int i = 0, ie = srbD->sortedBindings.size(); i != ie; ++i) {
6523 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings[i]);
6525 switch (b->type()) {
6526 case QRhiShaderResourceBinding::UniformBuffer:
6529 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
6530 sanityCheckResourceOwnership(bufD);
6532 if (bufD->m_type == QRhiBuffer::Dynamic)
6536 trackedRegisterBuffer(&passResTracker, bufD, bufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0,
6538 QRhiPassResourceTracker::toPassTrackerBufferStage(b->stage));
6544 if (bufD
->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
6545 rewriteDescSet =
true;
6546 bd.ubuf.id = bufD->m_id;
6551 case QRhiShaderResourceBinding::SampledTexture:
6552 case QRhiShaderResourceBinding::Texture:
6553 case QRhiShaderResourceBinding::Sampler:
6555 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
6556 if (bd.stex.d.size() != data->count()) {
6557 bd.stex.d.resize(data->count());
6558 rewriteDescSet =
true;
6560 for (
int elem = 0; elem < data->count(); ++elem) {
6566 Q_ASSERT(texD || samplerD);
6567 sanityCheckResourceOwnership(texD);
6568 sanityCheckResourceOwnership(samplerD);
6577 const quint64 texId = texD ? texD->m_id : 0;
6579 const quint64 samplerId = samplerD ? samplerD->m_id : 0;
6580 const uint samplerGen = samplerD ? samplerD
->generation : 0;
6581 if (texGen != bd.stex.d[elem].texGeneration
6582 || texId != bd.stex.d[elem].texId
6583 || samplerGen != bd.stex.d[elem].samplerGeneration
6584 || samplerId != bd.stex.d[elem].samplerId)
6586 rewriteDescSet =
true;
6587 bd.stex.d[elem].texId = texId;
6588 bd.stex.d[elem].texGeneration = texGen;
6589 bd.stex.d[elem].samplerId = samplerId;
6590 bd.stex.d[elem].samplerGeneration = samplerGen;
6595 case QRhiShaderResourceBinding::ImageLoad:
6596 case QRhiShaderResourceBinding::ImageStore:
6597 case QRhiShaderResourceBinding::ImageLoadStore:
6600 sanityCheckResourceOwnership(texD);
6601 Q_ASSERT(texD->m_flags.testFlag(QRhiTexture::UsedWithLoadStore));
6604 if (b->type() == QRhiShaderResourceBinding::ImageLoad)
6606 else if (b->type() == QRhiShaderResourceBinding::ImageStore)
6611 const auto stage = QRhiPassResourceTracker::toPassTrackerTextureStage(b->stage);
6612 const auto prevAccess = passResTracker
.textures().find(texD);
6613 if (prevAccess != passResTracker
.textures().end()) {
6617 addWriteBarrier =
true;
6618 writeBarrierDstStageMask |= toVkPipelineStage(stage);
6619 writeBarrierSrcStageMask |= toVkPipelineStage(tex.stage);
6627 if (texD
->generation != bd.simage.generation || texD->m_id != bd.simage.id) {
6628 rewriteDescSet =
true;
6629 bd.simage.id = texD->m_id;
6634 case QRhiShaderResourceBinding::BufferLoad:
6635 case QRhiShaderResourceBinding::BufferStore:
6636 case QRhiShaderResourceBinding::BufferLoadStore:
6639 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::StorageBuffer));
6640 sanityCheckResourceOwnership(bufD);
6642 if (bufD->m_type == QRhiBuffer::Dynamic)
6647 if (b->type() == QRhiShaderResourceBinding::BufferLoad)
6649 else if (b->type() == QRhiShaderResourceBinding::BufferStore)
6654 const auto stage = QRhiPassResourceTracker::toPassTrackerBufferStage(b->stage);
6655 const auto prevAccess = passResTracker
.buffers().find(bufD);
6656 if (prevAccess != passResTracker
.buffers().end()) {
6660 addWriteBarrier =
true;
6661 writeBarrierDstStageMask |= toVkPipelineStage(stage);
6662 writeBarrierSrcStageMask |= toVkPipelineStage(buf.stage);
6665 trackedRegisterBuffer(&passResTracker, bufD, bufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0,
6669 if (bufD
->generation != bd.sbuf.generation || bufD->m_id != bd.sbuf.id) {
6670 rewriteDescSet =
true;
6671 bd.sbuf.id = bufD->m_id;
6682 if (addWriteBarrier) {
6683 VkDependencyFlags dependencyFlags = cbD->recordingPass == QVkCommandBuffer::RenderPass ? VK_DEPENDENCY_BY_REGION_BIT : 0;
6684#ifdef VK_VERSION_1_1
6685 auto *rpd = cbD->currentTarget ?
static_cast<QVkRenderPassDescriptor*>(cbD->currentTarget->renderPassDescriptor()) :
nullptr;
6686 if (rpd && rpd->multiViewCount >= 2)
6687 dependencyFlags |= VK_DEPENDENCY_VIEW_LOCAL_BIT;
6690 VkMemoryBarrier barrier = {};
6691 barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
6692 barrier.pNext =
nullptr;
6693 barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
6694 barrier.srcAccessMask = barrier.dstAccessMask;
6695 df->vkCmdPipelineBarrier(cbD->activeSecondaryCbStack.last(), writeBarrierSrcStageMask, writeBarrierDstStageMask, dependencyFlags,
6702 cmd.args.memoryBarrier.dependencyFlags = dependencyFlags;
6703 cmd.args.memoryBarrier.dstStageMask = writeBarrierDstStageMask;
6704 cmd.args.memoryBarrier.srcStageMask = writeBarrierSrcStageMask;
6705 cmd.args.memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
6706 cmd.args.memoryBarrier.srcAccessMask = cmd.args.memoryBarrier.dstAccessMask;
6712 updateShaderResourceBindings(srb);
6716 const bool forceRebind = cbD->currentDescSetSlot != currentFrameSlot
6717 || !srbD->sortedDynamicOffsetBindingNumbers.isEmpty();
6719 const bool srbChanged = gfxPsD ? (cbD->currentGraphicsSrb != srb) : (cbD->currentComputeSrb != srb);
6722 QVarLengthArray<uint32_t, 4> dynOfs;
6727 for (
int bindingNumber : std::as_const(srbD->sortedDynamicOffsetBindingNumbers)) {
6728 uint32_t offset = 0;
6729 for (
int i = 0; i < dynamicOffsetCount; ++i) {
6730 const QRhiCommandBuffer::DynamicOffset &bindingOffsetPair(dynamicOffsets[i]);
6731 if (bindingOffsetPair.first == bindingNumber) {
6732 offset = bindingOffsetPair.second;
6736 dynOfs.append(offset);
6740 df->vkCmdBindDescriptorSets(cbD->activeSecondaryCbStack.last(),
6741 gfxPsD ? VK_PIPELINE_BIND_POINT_GRAPHICS : VK_PIPELINE_BIND_POINT_COMPUTE,
6742 gfxPsD ? gfxPsD->layout : compPsD->layout,
6743 0, 1, &srbD->descSets[currentFrameSlot],
6744 uint32_t(dynOfs.size()),
6745 dynOfs.size() ? dynOfs.constData() :
nullptr);
6749 cmd.args.bindDescriptorSet.bindPoint = gfxPsD ? VK_PIPELINE_BIND_POINT_GRAPHICS
6750 : VK_PIPELINE_BIND_POINT_COMPUTE;
6751 cmd.args.bindDescriptorSet.pipelineLayout = gfxPsD ? gfxPsD->layout : compPsD->layout;
6752 cmd.args.bindDescriptorSet.descSet = srbD->descSets[currentFrameSlot];
6753 cmd.args.bindDescriptorSet.dynamicOffsetCount = dynOfs.size();
6754 cmd.args.bindDescriptorSet.dynamicOffsetIndex = cbD->pools.dynamicOffset.size();
6755 cbD->pools.dynamicOffset.append(dynOfs.constData(), dynOfs.size());
6759 cbD->currentGraphicsSrb = srb;
6760 cbD->currentComputeSrb =
nullptr;
6762 cbD->currentGraphicsSrb =
nullptr;
6763 cbD->currentComputeSrb = srb;
6773 int startBinding,
int bindingCount,
const QRhiCommandBuffer::VertexInput *bindings,
6774 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
6780 bool needsBindVBuf =
false;
6781 for (
int i = 0; i < bindingCount; ++i) {
6782 const int inputSlot = startBinding + i;
6784 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
6786 if (bufD->m_type == QRhiBuffer::Dynamic)
6789 const VkBuffer vkvertexbuf = bufD->buffers[bufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0];
6790 if (cbD->currentVertexBuffers[inputSlot] != vkvertexbuf
6791 || cbD->currentVertexOffsets[inputSlot] != bindings[i].second)
6793 needsBindVBuf =
true;
6794 cbD->currentVertexBuffers[inputSlot] = vkvertexbuf;
6795 cbD->currentVertexOffsets[inputSlot] = bindings[i].second;
6799 if (needsBindVBuf) {
6800 QVarLengthArray<VkBuffer, 4> bufs;
6801 QVarLengthArray<VkDeviceSize, 4> ofs;
6802 for (
int i = 0; i < bindingCount; ++i) {
6804 const int slot = bufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
6805 bufs.append(bufD->buffers[slot]);
6806 ofs.append(bindings[i].second);
6813 df->vkCmdBindVertexBuffers(cbD->activeSecondaryCbStack.last(), uint32_t(startBinding),
6814 uint32_t(bufs.size()), bufs.constData(), ofs.constData());
6818 cmd.args.bindVertexBuffer.startBinding = startBinding;
6819 cmd.args.bindVertexBuffer.count = bufs.size();
6820 cmd.args.bindVertexBuffer.vertexBufferIndex = cbD->pools.vertexBuffer.size();
6821 cbD->pools.vertexBuffer.append(bufs.constData(), bufs.size());
6822 cmd.args.bindVertexBuffer.vertexBufferOffsetIndex = cbD->pools.vertexBufferOffset.size();
6823 cbD->pools.vertexBufferOffset.append(ofs.constData(), ofs.size());
6829 Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
6831 if (ibufD->m_type == QRhiBuffer::Dynamic)
6834 const int slot = ibufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
6835 const VkBuffer vkindexbuf = ibufD->buffers[slot];
6836 const VkIndexType type = indexFormat == QRhiCommandBuffer::IndexUInt16 ? VK_INDEX_TYPE_UINT16
6837 : VK_INDEX_TYPE_UINT32;
6839 if (cbD->currentIndexBuffer != vkindexbuf
6840 || cbD->currentIndexOffset != indexOffset
6841 || cbD->currentIndexFormat != type)
6843 cbD->currentIndexBuffer = vkindexbuf;
6844 cbD->currentIndexOffset = indexOffset;
6845 cbD->currentIndexFormat = type;
6848 df->vkCmdBindIndexBuffer(cbD->activeSecondaryCbStack.last(), vkindexbuf, indexOffset, type);
6852 cmd.args.bindIndexBuffer.buf = vkindexbuf;
6853 cmd.args.bindIndexBuffer.ofs = indexOffset;
6854 cmd.args.bindIndexBuffer.type = type;
6868 const QSize outputSize = cbD->currentTarget->pixelSize();
6869 std::array<
float, 4> vp = cbD->currentViewport.viewport();
6870 float x = 0, y = 0, w = 0, h = 0;
6872 if (qFuzzyIsNull(vp[2]) && qFuzzyIsNull(vp[3])) {
6875 w = outputSize.width();
6876 h = outputSize.height();
6879 qrhi_toTopLeftRenderTargetRect<
Bounded>(outputSize, vp, &x, &y, &w, &h);
6883 VkRect2D *s = &cmd.args.setScissor.scissor;
6884 s->offset.x = int32_t(x);
6885 s->offset.y = int32_t(y);
6886 s->extent.width = uint32_t(w);
6887 s->extent.height = uint32_t(h);
6890 df->vkCmdSetScissor(cbD->activeSecondaryCbStack.last(), 0, 1, s);
6891 cbD->commands.unget();
6901 const QSize outputSize = cbD->currentTarget->pixelSize();
6905 if (!qrhi_toTopLeftRenderTargetRect<
UnBounded>(outputSize, viewport.viewport(), &x, &y, &w, &h))
6909 VkViewport *vp = &cmd.args.setViewport.viewport;
6914 vp->minDepth = viewport.minDepth();
6915 vp->maxDepth = viewport.maxDepth();
6918 df->vkCmdSetViewport(cbD->activeSecondaryCbStack.last(), 0, 1, vp);
6919 cbD->commands.unget();
6924 cbD->currentViewport = viewport;
6925 if (cbD->currentGraphicsPipeline
6926 && !cbD->currentGraphicsPipeline->flags().testFlag(QRhiGraphicsPipeline::UsesScissor))
6936 Q_ASSERT(!cbD->currentGraphicsPipeline
6938 ->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor));
6939 const QSize outputSize = cbD->currentTarget->pixelSize();
6943 if (!qrhi_toTopLeftRenderTargetRect<
Bounded>(outputSize, scissor.scissor(), &x, &y, &w, &h))
6947 VkRect2D *s = &cmd.args.setScissor.scissor;
6950 s->extent.width = uint32_t(w);
6951 s->extent.height = uint32_t(h);
6954 df->vkCmdSetScissor(cbD->activeSecondaryCbStack.last(), 0, 1, s);
6955 cbD->commands.unget();
6969 float constants[] = {
float(c.redF()),
float(c.greenF()),
float(c.blueF()),
float(c.alphaF()) };
6970 df->vkCmdSetBlendConstants(cbD->activeSecondaryCbStack.last(), constants);
6974 cmd.args.setBlendConstants.c[0] = c.redF();
6975 cmd.args.setBlendConstants.c[1] = c.greenF();
6976 cmd.args.setBlendConstants.c[2] = c.blueF();
6977 cmd.args.setBlendConstants.c[3] = c.alphaF();
6984 df->vkCmdSetStencilReference(cbD->activeSecondaryCbStack.last(), VK_STENCIL_FRONT_AND_BACK, refValue);
6988 cmd.args.setStencilRef.ref = refValue;
6998 recordStencilRef(cbD, refValue);
6999 cbD->currentStencilRef = refValue;
7007 VkPipelineLayout layout = VK_NULL_HANDLE;
7008 VkShaderStageFlags stages = 0;
7011 layout = psD->layout;
7012 stages = psD->pushConstantStages;
7016 layout = psD->layout;
7017 stages = psD->pushConstantStages;
7020 if (!layout || !stages) {
7021 qWarning(
"No pipeline with a push constant block is active; setPushConstants ignored");
7026 df->vkCmdPushConstants(cbD->activeSecondaryCbStack.last(), layout, stages, offset, size, data);
7028 const int dataIndex = cbD->pools.pushConstantData.size();
7029 cbD->pools.pushConstantData.append(
static_cast<
const char *>(data), size);
7032 cmd.args.setPushConstants.layout = layout;
7033 cmd.args.setPushConstants.stages = stages;
7034 cmd.args.setPushConstants.offset = offset;
7035 cmd.args.setPushConstants.size = size;
7036 cmd.args.setPushConstants.dataIndex = dataIndex;
7042#ifdef VK_KHR_fragment_shading_rate
7043 if (!vkCmdSetFragmentShadingRateKHR)
7046 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7047 Q_ASSERT(cbD->recordingPass == QVkCommandBuffer::RenderPass);
7048 Q_ASSERT(!cbD->currentGraphicsPipeline || QRHI_RES(QVkGraphicsPipeline, cbD->currentGraphicsPipeline)->m_flags.testFlag(QRhiGraphicsPipeline::UsesShadingRate));
7050 VkFragmentShadingRateCombinerOpKHR ops[2] = {
7051 VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR,
7052 VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR
7054 VkExtent2D size = { uint32_t(coarsePixelSize.width()), uint32_t(coarsePixelSize.height()) };
7055 if (cbD->passUsesSecondaryCb) {
7056 vkCmdSetFragmentShadingRateKHR(cbD->activeSecondaryCbStack.last(), &size, ops);
7058 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7059 cmd.cmd = QVkCommandBuffer::Command::SetShadingRate;
7060 cmd.args.setShadingRate.w = size.width;
7061 cmd.args.setShadingRate.h = size.height;
7063 if (coarsePixelSize.width() != 1 || coarsePixelSize.height() != 1)
7064 cbD->hasShadingRateSet =
true;
7067 Q_UNUSED(coarsePixelSize);
7072 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
7078 df->vkCmdDraw(cbD->activeSecondaryCbStack.last(), vertexCount, instanceCount, firstVertex, firstInstance);
7082 cmd.args.draw.vertexCount = vertexCount;
7083 cmd.args.draw.instanceCount = instanceCount;
7084 cmd.args.draw.firstVertex = firstVertex;
7085 cmd.args.draw.firstInstance = firstInstance;
7090 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
7096 df->vkCmdDrawIndexed(cbD->activeSecondaryCbStack.last(), indexCount, instanceCount,
7097 firstIndex, vertexOffset, firstInstance);
7101 cmd.args.drawIndexed.indexCount = indexCount;
7102 cmd.args.drawIndexed.instanceCount = instanceCount;
7103 cmd.args.drawIndexed.firstIndex = firstIndex;
7104 cmd.args.drawIndexed.vertexOffset = vertexOffset;
7105 cmd.args.drawIndexed.firstInstance = firstInstance;
7110 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
7118 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
7120 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
7124 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
7127 if (caps.drawIndirectMulti) {
7128 df->vkCmdDrawIndirect(cbD->activeSecondaryCbStack.last(),
7129 indirectBufVk, indirectBufferOffset,
7132 VkDeviceSize offset = indirectBufferOffset;
7133 for (quint32 i = 0; i < drawCount; ++i) {
7134 df->vkCmdDrawIndirect(cbD->activeSecondaryCbStack.last(),
7135 indirectBufVk, offset,
7141 if (caps.drawIndirectMulti) {
7144 cmd.args.drawIndirect.indirectBuffer = indirectBufVk;
7145 cmd.args.drawIndirect.indirectBufferOffset = indirectBufferOffset;
7146 cmd.args.drawIndirect.drawCount = drawCount;
7147 cmd.args.drawIndirect.stride = stride;
7149 VkDeviceSize offset = indirectBufferOffset;
7150 for (quint32 i = 0; i < drawCount; ++i) {
7153 cmd.args.drawIndirect.indirectBuffer = indirectBufVk;
7154 cmd.args.drawIndirect.indirectBufferOffset = offset;
7155 cmd.args.drawIndirect.drawCount = 1;
7156 cmd.args.drawIndirect.stride = stride;
7164 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
7172 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
7174 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
7178 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
7181 if (caps.drawIndirectMulti) {
7182 df->vkCmdDrawIndexedIndirect(cbD->activeSecondaryCbStack.last(),
7183 indirectBufVk, indirectBufferOffset,
7186 VkDeviceSize offset = indirectBufferOffset;
7187 for (quint32 i = 0; i < drawCount; ++i) {
7188 df->vkCmdDrawIndexedIndirect(cbD->activeSecondaryCbStack.last(),
7189 indirectBufVk, offset,
7195 if (caps.drawIndirectMulti) {
7198 cmd.args.drawIndexedIndirect.indirectBuffer = indirectBufVk;
7199 cmd.args.drawIndexedIndirect.indirectBufferOffset = indirectBufferOffset;
7200 cmd.args.drawIndexedIndirect.drawCount = drawCount;
7201 cmd.args.drawIndexedIndirect.stride = stride;
7203 VkDeviceSize offset = indirectBufferOffset;
7204 for (quint32 i = 0; i < drawCount; ++i) {
7207 cmd.args.drawIndexedIndirect.indirectBuffer = indirectBufVk;
7208 cmd.args.drawIndexedIndirect.indirectBufferOffset = offset;
7209 cmd.args.drawIndexedIndirect.drawCount = 1;
7210 cmd.args.drawIndexedIndirect.stride = stride;
7219#ifdef VK_EXT_debug_utils
7220 if (!debugMarkers || !caps.debugUtils)
7223 VkDebugUtilsLabelEXT label = {};
7224 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
7226 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7227 if (cbD->recordingPass != QVkCommandBuffer::NoPass && cbD->passUsesSecondaryCb) {
7228 label.pLabelName = name.constData();
7229 vkCmdBeginDebugUtilsLabelEXT(cbD->activeSecondaryCbStack.last(), &label);
7231 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7232 cmd.cmd = QVkCommandBuffer::Command::DebugMarkerBegin;
7233 cmd.args.debugMarkerBegin.label = label;
7234 cmd.args.debugMarkerBegin.labelNameIndex = cbD->pools.debugMarkerData.size();
7235 cbD->pools.debugMarkerData.append(name);
7245#ifdef VK_EXT_debug_utils
7246 if (!debugMarkers || !caps.debugUtils)
7249 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7250 if (cbD->recordingPass != QVkCommandBuffer::NoPass && cbD->passUsesSecondaryCb) {
7251 vkCmdEndDebugUtilsLabelEXT(cbD->activeSecondaryCbStack.last());
7253 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7254 cmd.cmd = QVkCommandBuffer::Command::DebugMarkerEnd;
7263#ifdef VK_EXT_debug_utils
7264 if (!debugMarkers || !caps.debugUtils)
7267 VkDebugUtilsLabelEXT label = {};
7268 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
7270 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7271 if (cbD->recordingPass != QVkCommandBuffer::NoPass && cbD->passUsesSecondaryCb) {
7272 label.pLabelName = msg.constData();
7273 vkCmdInsertDebugUtilsLabelEXT(cbD->activeSecondaryCbStack.last(), &label);
7275 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7276 cmd.cmd = QVkCommandBuffer::Command::DebugMarkerInsert;
7277 cmd.args.debugMarkerInsert.label = label;
7278 cmd.args.debugMarkerInsert.labelNameIndex = cbD->pools.debugMarkerData.size();
7279 cbD->pools.debugMarkerData.append(msg);
7289 return QRHI_RES(QVkCommandBuffer, cb)->nativeHandles();
7294 Q_ASSERT(cbD->currentTarget);
7297 switch (cbD->currentTarget->resourceType()) {
7298 case QRhiResource::SwapChainRenderTarget:
7301 case QRhiResource::TextureRenderTarget:
7333 qWarning(
"beginExternal() within a pass is only supported with secondary command buffers. "
7334 "This can be enabled by passing QRhiCommandBuffer::ExternalContent to beginPass().");
7338 VkCommandBuffer secondaryCb = cbD->activeSecondaryCbStack.last();
7339 cbD->activeSecondaryCbStack.removeLast();
7340 endAndEnqueueSecondaryCommandBuffer(secondaryCb, cbD);
7342 VkCommandBuffer extCb = startSecondaryCommandBuffer(maybeRenderTargetData(cbD));
7344 cbD->activeSecondaryCbStack.append(extCb);
7356 VkCommandBuffer extCb = cbD->activeSecondaryCbStack.last();
7357 cbD->activeSecondaryCbStack.removeLast();
7358 endAndEnqueueSecondaryCommandBuffer(extCb, cbD);
7359 cbD->activeSecondaryCbStack.append(startSecondaryCommandBuffer(maybeRenderTargetData(cbD)));
7373 if (!debugMarkers || name.isEmpty())
7376 QByteArray decoratedName = name;
7378 decoratedName +=
'/';
7379 decoratedName += QByteArray::number(slot);
7381 vmaSetAllocationName(toVmaAllocator(allocator), toVmaAllocation(allocation), decoratedName.constData());
7386#ifdef VK_EXT_debug_utils
7387 if (!debugMarkers || !caps.debugUtils || name.isEmpty())
7390 VkDebugUtilsObjectNameInfoEXT nameInfo = {};
7391 nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
7392 nameInfo.objectType = type;
7393 nameInfo.objectHandle = object;
7394 QByteArray decoratedName = name;
7396 decoratedName +=
'/';
7397 decoratedName += QByteArray::number(slot);
7399 nameInfo.pObjectName = decoratedName.constData();
7400 vkSetDebugUtilsObjectNameEXT(dev, &nameInfo);
7412 if (usage.testFlag(QRhiBuffer::VertexBuffer))
7413 u |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
7414 if (usage.testFlag(QRhiBuffer::IndexBuffer))
7415 u |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
7416 if (usage.testFlag(QRhiBuffer::UniformBuffer))
7417 u |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
7418 if (usage.testFlag(QRhiBuffer::StorageBuffer))
7419 u |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
7420 if (usage.testFlag(QRhiBuffer::IndirectBuffer))
7421 u |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
7422 return VkBufferUsageFlagBits(u);
7428 case QRhiSampler::Nearest:
7429 return VK_FILTER_NEAREST;
7430 case QRhiSampler::Linear:
7431 return VK_FILTER_LINEAR;
7433 Q_UNREACHABLE_RETURN(VK_FILTER_NEAREST);
7440 case QRhiSampler::None:
7441 return VK_SAMPLER_MIPMAP_MODE_NEAREST;
7442 case QRhiSampler::Nearest:
7443 return VK_SAMPLER_MIPMAP_MODE_NEAREST;
7444 case QRhiSampler::Linear:
7445 return VK_SAMPLER_MIPMAP_MODE_LINEAR;
7447 Q_UNREACHABLE_RETURN(VK_SAMPLER_MIPMAP_MODE_NEAREST);
7454 case QRhiSampler::Repeat:
7455 return VK_SAMPLER_ADDRESS_MODE_REPEAT;
7456 case QRhiSampler::ClampToEdge:
7457 return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
7458 case QRhiSampler::Mirror:
7459 return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
7461 Q_UNREACHABLE_RETURN(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE);
7468 case QRhiShaderStage::Vertex:
7469 return VK_SHADER_STAGE_VERTEX_BIT;
7470 case QRhiShaderStage::TessellationControl:
7471 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
7472 case QRhiShaderStage::TessellationEvaluation:
7473 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
7474 case QRhiShaderStage::Fragment:
7475 return VK_SHADER_STAGE_FRAGMENT_BIT;
7476 case QRhiShaderStage::Compute:
7477 return VK_SHADER_STAGE_COMPUTE_BIT;
7478 case QRhiShaderStage::Geometry:
7479 return VK_SHADER_STAGE_GEOMETRY_BIT;
7481 Q_UNREACHABLE_RETURN(VK_SHADER_STAGE_VERTEX_BIT);
7488 case QRhiVertexInputAttribute::Float4:
7489 return VK_FORMAT_R32G32B32A32_SFLOAT;
7490 case QRhiVertexInputAttribute::Float3:
7491 return VK_FORMAT_R32G32B32_SFLOAT;
7492 case QRhiVertexInputAttribute::Float2:
7493 return VK_FORMAT_R32G32_SFLOAT;
7494 case QRhiVertexInputAttribute::Float:
7495 return VK_FORMAT_R32_SFLOAT;
7496 case QRhiVertexInputAttribute::UNormByte4:
7497 return VK_FORMAT_R8G8B8A8_UNORM;
7498 case QRhiVertexInputAttribute::UNormByte2:
7499 return VK_FORMAT_R8G8_UNORM;
7500 case QRhiVertexInputAttribute::UNormByte:
7501 return VK_FORMAT_R8_UNORM;
7502 case QRhiVertexInputAttribute::UInt4:
7503 return VK_FORMAT_R32G32B32A32_UINT;
7504 case QRhiVertexInputAttribute::UInt3:
7505 return VK_FORMAT_R32G32B32_UINT;
7506 case QRhiVertexInputAttribute::UInt2:
7507 return VK_FORMAT_R32G32_UINT;
7508 case QRhiVertexInputAttribute::UInt:
7509 return VK_FORMAT_R32_UINT;
7510 case QRhiVertexInputAttribute::SInt4:
7511 return VK_FORMAT_R32G32B32A32_SINT;
7512 case QRhiVertexInputAttribute::SInt3:
7513 return VK_FORMAT_R32G32B32_SINT;
7514 case QRhiVertexInputAttribute::SInt2:
7515 return VK_FORMAT_R32G32_SINT;
7516 case QRhiVertexInputAttribute::SInt:
7517 return VK_FORMAT_R32_SINT;
7518 case QRhiVertexInputAttribute::Half4:
7519 return VK_FORMAT_R16G16B16A16_SFLOAT;
7520 case QRhiVertexInputAttribute::Half3:
7521 return VK_FORMAT_R16G16B16_SFLOAT;
7522 case QRhiVertexInputAttribute::Half2:
7523 return VK_FORMAT_R16G16_SFLOAT;
7524 case QRhiVertexInputAttribute::Half:
7525 return VK_FORMAT_R16_SFLOAT;
7526 case QRhiVertexInputAttribute::UShort4:
7527 return VK_FORMAT_R16G16B16A16_UINT;
7528 case QRhiVertexInputAttribute::UShort3:
7529 return VK_FORMAT_R16G16B16_UINT;
7530 case QRhiVertexInputAttribute::UShort2:
7531 return VK_FORMAT_R16G16_UINT;
7532 case QRhiVertexInputAttribute::UShort:
7533 return VK_FORMAT_R16_UINT;
7534 case QRhiVertexInputAttribute::SShort4:
7535 return VK_FORMAT_R16G16B16A16_SINT;
7536 case QRhiVertexInputAttribute::SShort3:
7537 return VK_FORMAT_R16G16B16_SINT;
7538 case QRhiVertexInputAttribute::SShort2:
7539 return VK_FORMAT_R16G16_SINT;
7540 case QRhiVertexInputAttribute::SShort:
7541 return VK_FORMAT_R16_SINT;
7543 Q_UNREACHABLE_RETURN(VK_FORMAT_R32G32B32A32_SFLOAT);
7550 case QRhiGraphicsPipeline::Triangles:
7551 return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
7552 case QRhiGraphicsPipeline::TriangleStrip:
7553 return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
7554 case QRhiGraphicsPipeline::TriangleFan:
7555 return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN;
7556 case QRhiGraphicsPipeline::Lines:
7557 return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
7558 case QRhiGraphicsPipeline::LineStrip:
7559 return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
7560 case QRhiGraphicsPipeline::Points:
7561 return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
7562 case QRhiGraphicsPipeline::Patches:
7563 return VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
7565 Q_UNREACHABLE_RETURN(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
7572 case QRhiGraphicsPipeline::None:
7573 return VK_CULL_MODE_NONE;
7574 case QRhiGraphicsPipeline::Front:
7575 return VK_CULL_MODE_FRONT_BIT;
7576 case QRhiGraphicsPipeline::Back:
7577 return VK_CULL_MODE_BACK_BIT;
7579 Q_UNREACHABLE_RETURN(VK_CULL_MODE_NONE);
7586 case QRhiGraphicsPipeline::CCW:
7587 return VK_FRONT_FACE_COUNTER_CLOCKWISE;
7588 case QRhiGraphicsPipeline::CW:
7589 return VK_FRONT_FACE_CLOCKWISE;
7591 Q_UNREACHABLE_RETURN(VK_FRONT_FACE_COUNTER_CLOCKWISE);
7598 if (c.testFlag(QRhiGraphicsPipeline::R))
7599 f |= VK_COLOR_COMPONENT_R_BIT;
7600 if (c.testFlag(QRhiGraphicsPipeline::G))
7601 f |= VK_COLOR_COMPONENT_G_BIT;
7602 if (c.testFlag(QRhiGraphicsPipeline::B))
7603 f |= VK_COLOR_COMPONENT_B_BIT;
7604 if (c.testFlag(QRhiGraphicsPipeline::A))
7605 f |= VK_COLOR_COMPONENT_A_BIT;
7606 return VkColorComponentFlags(f);
7612 case QRhiGraphicsPipeline::Zero:
7613 return VK_BLEND_FACTOR_ZERO;
7614 case QRhiGraphicsPipeline::One:
7615 return VK_BLEND_FACTOR_ONE;
7616 case QRhiGraphicsPipeline::SrcColor:
7617 return VK_BLEND_FACTOR_SRC_COLOR;
7618 case QRhiGraphicsPipeline::OneMinusSrcColor:
7619 return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
7620 case QRhiGraphicsPipeline::DstColor:
7621 return VK_BLEND_FACTOR_DST_COLOR;
7622 case QRhiGraphicsPipeline::OneMinusDstColor:
7623 return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR;
7624 case QRhiGraphicsPipeline::SrcAlpha:
7625 return VK_BLEND_FACTOR_SRC_ALPHA;
7626 case QRhiGraphicsPipeline::OneMinusSrcAlpha:
7627 return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
7628 case QRhiGraphicsPipeline::DstAlpha:
7629 return VK_BLEND_FACTOR_DST_ALPHA;
7630 case QRhiGraphicsPipeline::OneMinusDstAlpha:
7631 return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
7632 case QRhiGraphicsPipeline::ConstantColor:
7633 return VK_BLEND_FACTOR_CONSTANT_COLOR;
7634 case QRhiGraphicsPipeline::OneMinusConstantColor:
7635 return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR;
7636 case QRhiGraphicsPipeline::ConstantAlpha:
7637 return VK_BLEND_FACTOR_CONSTANT_ALPHA;
7638 case QRhiGraphicsPipeline::OneMinusConstantAlpha:
7639 return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA;
7640 case QRhiGraphicsPipeline::SrcAlphaSaturate:
7641 return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE;
7642 case QRhiGraphicsPipeline::Src1Color:
7643 return VK_BLEND_FACTOR_SRC1_COLOR;
7644 case QRhiGraphicsPipeline::OneMinusSrc1Color:
7645 return VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR;
7646 case QRhiGraphicsPipeline::Src1Alpha:
7647 return VK_BLEND_FACTOR_SRC1_ALPHA;
7648 case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
7649 return VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
7651 Q_UNREACHABLE_RETURN(VK_BLEND_FACTOR_ZERO);
7658 case QRhiGraphicsPipeline::Add:
7659 return VK_BLEND_OP_ADD;
7660 case QRhiGraphicsPipeline::Subtract:
7661 return VK_BLEND_OP_SUBTRACT;
7662 case QRhiGraphicsPipeline::ReverseSubtract:
7663 return VK_BLEND_OP_REVERSE_SUBTRACT;
7664 case QRhiGraphicsPipeline::Min:
7665 return VK_BLEND_OP_MIN;
7666 case QRhiGraphicsPipeline::Max:
7667 return VK_BLEND_OP_MAX;
7669 Q_UNREACHABLE_RETURN(VK_BLEND_OP_ADD);
7676 case QRhiGraphicsPipeline::Never:
7677 return VK_COMPARE_OP_NEVER;
7678 case QRhiGraphicsPipeline::Less:
7679 return VK_COMPARE_OP_LESS;
7680 case QRhiGraphicsPipeline::Equal:
7681 return VK_COMPARE_OP_EQUAL;
7682 case QRhiGraphicsPipeline::LessOrEqual:
7683 return VK_COMPARE_OP_LESS_OR_EQUAL;
7684 case QRhiGraphicsPipeline::Greater:
7685 return VK_COMPARE_OP_GREATER;
7686 case QRhiGraphicsPipeline::NotEqual:
7687 return VK_COMPARE_OP_NOT_EQUAL;
7688 case QRhiGraphicsPipeline::GreaterOrEqual:
7689 return VK_COMPARE_OP_GREATER_OR_EQUAL;
7690 case QRhiGraphicsPipeline::Always:
7691 return VK_COMPARE_OP_ALWAYS;
7693 Q_UNREACHABLE_RETURN(VK_COMPARE_OP_ALWAYS);
7700 case QRhiGraphicsPipeline::StencilZero:
7701 return VK_STENCIL_OP_ZERO;
7702 case QRhiGraphicsPipeline::Keep:
7703 return VK_STENCIL_OP_KEEP;
7704 case QRhiGraphicsPipeline::Replace:
7705 return VK_STENCIL_OP_REPLACE;
7706 case QRhiGraphicsPipeline::IncrementAndClamp:
7707 return VK_STENCIL_OP_INCREMENT_AND_CLAMP;
7708 case QRhiGraphicsPipeline::DecrementAndClamp:
7709 return VK_STENCIL_OP_DECREMENT_AND_CLAMP;
7710 case QRhiGraphicsPipeline::Invert:
7711 return VK_STENCIL_OP_INVERT;
7712 case QRhiGraphicsPipeline::IncrementAndWrap:
7713 return VK_STENCIL_OP_INCREMENT_AND_WRAP;
7714 case QRhiGraphicsPipeline::DecrementAndWrap:
7715 return VK_STENCIL_OP_DECREMENT_AND_WRAP;
7717 Q_UNREACHABLE_RETURN(VK_STENCIL_OP_KEEP);
7724 case QRhiGraphicsPipeline::Fill:
7725 return VK_POLYGON_MODE_FILL;
7726 case QRhiGraphicsPipeline::Line:
7727 return VK_POLYGON_MODE_LINE;
7729 Q_UNREACHABLE_RETURN(VK_POLYGON_MODE_FILL);
7735 dst->failOp = toVkStencilOp(src.failOp);
7736 dst->passOp = toVkStencilOp(src.passOp);
7737 dst->depthFailOp = toVkStencilOp(src.depthFailOp);
7738 dst->compareOp = toVkCompareOp(src.compareOp);
7743 switch (b->type()) {
7744 case QRhiShaderResourceBinding::UniformBuffer:
7745 return b->ubuf().hasDynamicOffset ? VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC
7746 : VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
7748 case QRhiShaderResourceBinding::SampledTexture:
7749 return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
7751 case QRhiShaderResourceBinding::Texture:
7752 return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
7754 case QRhiShaderResourceBinding::Sampler:
7755 return VK_DESCRIPTOR_TYPE_SAMPLER;
7757 case QRhiShaderResourceBinding::ImageLoad:
7758 case QRhiShaderResourceBinding::ImageStore:
7759 case QRhiShaderResourceBinding::ImageLoadStore:
7760 return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
7762 case QRhiShaderResourceBinding::BufferLoad:
7763 case QRhiShaderResourceBinding::BufferStore:
7764 case QRhiShaderResourceBinding::BufferLoadStore:
7765 return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
7768 Q_UNREACHABLE_RETURN(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
7775 if (stage.testFlag(QRhiShaderResourceBinding::VertexStage))
7776 s |= VK_SHADER_STAGE_VERTEX_BIT;
7777 if (stage.testFlag(QRhiShaderResourceBinding::FragmentStage))
7778 s |= VK_SHADER_STAGE_FRAGMENT_BIT;
7779 if (stage.testFlag(QRhiShaderResourceBinding::ComputeStage))
7780 s |= VK_SHADER_STAGE_COMPUTE_BIT;
7781 if (stage.testFlag(QRhiShaderResourceBinding::TessellationControlStage))
7782 s |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
7783 if (stage.testFlag(QRhiShaderResourceBinding::TessellationEvaluationStage))
7784 s |= VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
7785 if (stage.testFlag(QRhiShaderResourceBinding::GeometryStage))
7786 s |= VK_SHADER_STAGE_GEOMETRY_BIT;
7787 return VkShaderStageFlags(s);
7793 case QRhiSampler::Never:
7794 return VK_COMPARE_OP_NEVER;
7795 case QRhiSampler::Less:
7796 return VK_COMPARE_OP_LESS;
7797 case QRhiSampler::Equal:
7798 return VK_COMPARE_OP_EQUAL;
7799 case QRhiSampler::LessOrEqual:
7800 return VK_COMPARE_OP_LESS_OR_EQUAL;
7801 case QRhiSampler::Greater:
7802 return VK_COMPARE_OP_GREATER;
7803 case QRhiSampler::NotEqual:
7804 return VK_COMPARE_OP_NOT_EQUAL;
7805 case QRhiSampler::GreaterOrEqual:
7806 return VK_COMPARE_OP_GREATER_OR_EQUAL;
7807 case QRhiSampler::Always:
7808 return VK_COMPARE_OP_ALWAYS;
7810 Q_UNREACHABLE_RETURN(VK_COMPARE_OP_NEVER);
7818 buffers[i] = stagingBuffers[i] = VK_NULL_HANDLE;
7838 e.buffer.buffers[i] = buffers[i];
7840 e.buffer.stagingBuffers[i] = stagingBuffers[i];
7843 buffers[i] = VK_NULL_HANDLE;
7845 stagingBuffers[i] = VK_NULL_HANDLE;
7847 pendingDynamicUpdates[i].clear();
7855 rhiD->releaseQueue.append(e);
7856 rhiD->unregisterResource(
this);
7865 if (m_usage.testFlag(QRhiBuffer::StorageBuffer) && m_type == Dynamic) {
7866 qWarning(
"StorageBuffer cannot be combined with Dynamic");
7870 const quint32 nonZeroSize = m_size <= 0 ? 256 : m_size;
7872 VkBufferCreateInfo bufferInfo = {};
7873 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
7874 bufferInfo.size = nonZeroSize;
7875 bufferInfo.usage = toVkBufferUsage(m_usage);
7877 VmaAllocationCreateInfo allocInfo = {};
7879 if (m_type == Dynamic) {
7884 allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
7887 allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
7889 allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
7890 bufferInfo.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
7894 VkResult err = VK_SUCCESS;
7896 buffers[i] = VK_NULL_HANDLE;
7898 usageState[i].access = usageState[i].stage = 0;
7899 if (i == 0 || m_type == Dynamic) {
7900 VmaAllocation allocation;
7901 err = vmaCreateBuffer(toVmaAllocator(rhiD->allocator), &bufferInfo, &allocInfo, &buffers[i], &allocation,
nullptr);
7902 if (err != VK_SUCCESS)
7905 rhiD->setAllocationName(allocation, m_objectName, m_type == Dynamic ? i : -1);
7906 rhiD->setObjectName(uint64_t(buffers[i]), VK_OBJECT_TYPE_BUFFER, m_objectName,
7907 m_type == Dynamic ? i : -1);
7911 if (err != VK_SUCCESS) {
7912 qWarning(
"Failed to create buffer of size %u: %d", nonZeroSize, err);
7913 rhiD->printExtraErrorInfo(err);
7919 rhiD->registerResource(
this);
7925 if (m_type == Dynamic) {
7931 b.objects[i] = &buffers[i];
7936 return { { &buffers[0] }, 1 };
7946 Q_ASSERT(m_type == Dynamic);
7948 Q_ASSERT(rhiD->inFrame);
7949 const int slot = rhiD->currentFrameSlot;
7951 VmaAllocation a = toVmaAllocation(allocations[slot]);
7952 VkResult err = vmaMapMemory(toVmaAllocator(rhiD->allocator), a, &p);
7953 if (err != VK_SUCCESS) {
7954 qWarning(
"Failed to map buffer: %d", err);
7957 return static_cast<
char *>(p);
7963 const int slot = rhiD->currentFrameSlot;
7964 VmaAllocation a = toVmaAllocation(allocations[slot]);
7965 vmaFlushAllocation(toVmaAllocator(rhiD->allocator), a, 0, m_size);
7966 vmaUnmapMemory(toVmaAllocator(rhiD->allocator), a);
7970 int sampleCount, Flags flags,
7971 QRhiTexture::Format backingFormatHint)
7984 if (!memory && !backingTexture)
7991 e.renderBuffer.memory = memory;
7992 e.renderBuffer.image = image;
7993 e.renderBuffer.imageView = imageView;
7995 memory = VK_NULL_HANDLE;
7996 image = VK_NULL_HANDLE;
7997 imageView = VK_NULL_HANDLE;
8007 rhiD->releaseQueue.append(e);
8008 rhiD->unregisterResource(
this);
8014 if (memory || backingTexture)
8017 if (m_pixelSize.isEmpty())
8021 samples = rhiD->effectiveSampleCountBits(m_sampleCount);
8024 case QRhiRenderBuffer::Color:
8032 QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource));
8040 vkformat = backingTexture->vkformat;
8043 case QRhiRenderBuffer::DepthStencil:
8044 vkformat = rhiD->optimalDepthStencilFormat();
8045 if (!rhiD->createTransientImage(vkformat,
8047 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
8048 VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
8057 rhiD->setObjectName(uint64_t(image), VK_OBJECT_TYPE_IMAGE, m_objectName);
8066 rhiD->registerResource(
this);
8072 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
8073 return m_backingFormatHint;
8075 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
8079 int arraySize,
int sampleCount, Flags flags)
8083 stagingBuffers[i] = VK_NULL_HANDLE;
8086 for (
int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i)
8087 perLevelImageViews[i] = VK_NULL_HANDLE;
8104 e.texture.image = owns ? image : VK_NULL_HANDLE;
8105 e.texture.imageView = imageView;
8109 e.texture.stagingBuffers[i] = stagingBuffers[i];
8112 stagingBuffers[i] = VK_NULL_HANDLE;
8116 for (
int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i) {
8117 e.texture.extraImageViews[i] = perLevelImageViews[i];
8118 perLevelImageViews[i] = VK_NULL_HANDLE;
8121 image = VK_NULL_HANDLE;
8122 imageView = VK_NULL_HANDLE;
8127 rhiD->releaseQueue.append(e);
8128 rhiD->unregisterResource(
this);
8138 vkformat = toVkTextureFormat(m_format, m_flags);
8139 if (m_writeViewFormat.format != UnknownFormat)
8140 viewFormat = toVkTextureFormat(m_writeViewFormat.format, m_writeViewFormat.srgb ? sRGB : Flags());
8142 viewFormat = vkformat;
8143 if (m_readViewFormat.format != UnknownFormat)
8144 viewFormatForSampling = toVkTextureFormat(m_readViewFormat.format, m_readViewFormat.srgb ? sRGB : Flags());
8146 viewFormatForSampling = vkformat;
8148 VkFormatProperties props;
8149 rhiD
->f->vkGetPhysicalDeviceFormatProperties(rhiD->physDev, vkformat, &props);
8150 const bool canSampleOptimal = (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT);
8151 if (!canSampleOptimal) {
8152 qWarning(
"Texture sampling with optimal tiling for format %d not supported", vkformat);
8156 const bool isCube = m_flags.testFlag(CubeMap);
8157 const bool isArray = m_flags.testFlag(TextureArray);
8158 const bool is3D = m_flags.testFlag(ThreeDimensional);
8159 const bool is1D = m_flags.testFlag(OneDimensional);
8160 const bool hasMipMaps = m_flags.testFlag(MipMapped);
8162 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
8163 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
8165 mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1);
8166 const int maxLevels = QRhi::MAX_MIP_LEVELS;
8168 qWarning(
"Too many mip levels (%d, max is %d), truncating mip chain",
mipLevelCount, maxLevels);
8171 samples = rhiD->effectiveSampleCountBits(m_sampleCount);
8172 if (samples > VK_SAMPLE_COUNT_1_BIT) {
8174 qWarning(
"Cubemap texture cannot be multisample");
8178 qWarning(
"3D texture cannot be multisample");
8182 qWarning(
"Multisample texture cannot have mipmaps");
8186 if (isCube && is3D) {
8187 qWarning(
"Texture cannot be both cube and 3D");
8190 if (isArray && is3D) {
8191 qWarning(
"Texture cannot be both array and 3D");
8194 if (isCube && is1D) {
8195 qWarning(
"Texture cannot be both cube and 1D");
8199 qWarning(
"Texture cannot be both 1D and 3D");
8202 if (m_depth > 1 && !is3D) {
8203 qWarning(
"Texture cannot have a depth of %d when it is not 3D", m_depth);
8206 if (m_arraySize > 0 && !isArray) {
8207 qWarning(
"Texture cannot have an array size of %d when it is not an array", m_arraySize);
8210 if (m_arraySize < 1 && isArray) {
8211 qWarning(
"Texture is an array but array size is %d", m_arraySize);
8215 usageState.layout = VK_IMAGE_LAYOUT_UNDEFINED;
8216 usageState.access = 0;
8217 usageState.stage = 0;
8219 if (!rhiD->textureFormatInfo(m_format, size,
nullptr,
nullptr,
nullptr))
8223 *adjustedSize = size;
8232 const auto aspectMask = aspectMaskForTextureFormat(m_format);
8233 const bool isCube = m_flags.testFlag(CubeMap);
8234 const bool isArray = m_flags.testFlag(TextureArray);
8235 const bool is3D = m_flags.testFlag(ThreeDimensional);
8236 const bool is1D = m_flags.testFlag(OneDimensional);
8238 VkImageViewCreateInfo viewInfo = {};
8239 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
8240 viewInfo.image = image;
8241 viewInfo.viewType = isCube
8242 ? VK_IMAGE_VIEW_TYPE_CUBE
8243 : (is3D ? VK_IMAGE_VIEW_TYPE_3D
8244 : (is1D ? (isArray ? VK_IMAGE_VIEW_TYPE_1D_ARRAY : VK_IMAGE_VIEW_TYPE_1D)
8245 : (isArray ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D)));
8246 viewInfo.format = viewFormatForSampling;
8247 viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
8248 viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
8249 viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
8250 viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
8251 viewInfo.subresourceRange.aspectMask = aspectMask;
8254 viewInfo.subresourceRange.aspectMask &= ~VK_IMAGE_ASPECT_STENCIL_BIT;
8256 if (isArray && m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
8257 viewInfo.subresourceRange.baseArrayLayer = uint32_t(m_arrayRangeStart);
8258 viewInfo.subresourceRange.layerCount = uint32_t(m_arrayRangeLength);
8260 viewInfo.subresourceRange.layerCount = isCube ? 6 : (isArray ? qMax(0, m_arraySize) : 1);
8263 VkResult err = rhiD
->df->vkCreateImageView(rhiD->dev, &viewInfo,
nullptr, &imageView);
8264 if (err != VK_SUCCESS) {
8265 qWarning(
"Failed to create image view: %d", err);
8278 if (!prepareCreate(&size))
8282 const bool isRenderTarget = m_flags.testFlag(QRhiTexture::RenderTarget);
8283 const bool isDepth = isDepthTextureFormat(m_format);
8284 const bool isCube = m_flags.testFlag(CubeMap);
8285 const bool isArray = m_flags.testFlag(TextureArray);
8286 const bool is3D = m_flags.testFlag(ThreeDimensional);
8287 const bool is1D = m_flags.testFlag(OneDimensional);
8289 VkImageCreateInfo imageInfo = {};
8290 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
8291 imageInfo.flags = 0;
8293 imageInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
8294 if (viewFormat != vkformat || viewFormatForSampling != vkformat)
8295 imageInfo.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
8297 if (is3D && isRenderTarget) {
8303 if (!rhiD->caps.texture3DSliceAs2D)
8304 qWarning(
"QRhiVulkan: Rendering to 3D texture slice may not be functional without API 1.1 on the VkInstance");
8305#ifdef VK_VERSION_1_1
8306 imageInfo.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
8308 imageInfo.flags |= 0x00000020;
8312 imageInfo.imageType = is1D ? VK_IMAGE_TYPE_1D : is3D ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D;
8313 imageInfo.format = vkformat;
8314 imageInfo.extent.width = uint32_t(size.width());
8315 imageInfo.extent.height = uint32_t(size.height());
8316 imageInfo.extent.depth = is3D ? qMax(1, m_depth) : 1;
8318 imageInfo.arrayLayers = isCube ? 6 : (isArray ? qMax(0, m_arraySize) : 1);
8319 imageInfo.samples = samples;
8320 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
8323 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
8325 imageInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
8326 if (isRenderTarget) {
8328 imageInfo.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
8330 imageInfo.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
8332 if (m_flags.testFlag(QRhiTexture::UsedAsTransferSource))
8333 imageInfo.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
8334 if (m_flags.testFlag(QRhiTexture::UsedWithGenerateMips))
8335 imageInfo.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
8336 if (m_flags.testFlag(QRhiTexture::UsedWithLoadStore))
8337 imageInfo.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
8338#ifdef VK_KHR_fragment_shading_rate
8339 if (m_flags.testFlag(QRhiTexture::UsedAsShadingRateMap) && rhiD->caps.imageBasedShadingRate)
8340 imageInfo.usage |= VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR;
8343 VmaAllocationCreateInfo allocInfo = {};
8344 allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
8346 VmaAllocation allocation;
8347 VkResult err = vmaCreateImage(toVmaAllocator(rhiD->allocator), &imageInfo, &allocInfo, &image, &allocation,
nullptr);
8348 if (err != VK_SUCCESS) {
8349 qWarning(
"Failed to create image (with VkImageCreateInfo %ux%u depth %u vkformat 0x%X mips %u layers %u vksamples 0x%X): %d",
8350 imageInfo.extent.width, imageInfo.extent.height, imageInfo.extent.depth,
8351 int(imageInfo.format),
8352 imageInfo.mipLevels,
8353 imageInfo.arrayLayers,
8354 int(imageInfo.samples),
8356 rhiD->printExtraErrorInfo(err);
8360 rhiD->setAllocationName(allocation, m_objectName);
8365 rhiD->setObjectName(uint64_t(image), VK_OBJECT_TYPE_IMAGE, m_objectName);
8368 rhiD->registerResource(
this);
8374 VkImage img = VkImage(src.object);
8378 if (!prepareCreate())
8386 usageState.layout = VkImageLayout(src.layout);
8390 rhiD->registerResource(
this);
8396 return {quint64(image), usageState.layout};
8401 usageState.layout = VkImageLayout(layout);
8407 if (perLevelImageViews[level] != VK_NULL_HANDLE)
8408 return perLevelImageViews[level];
8410 const VkImageAspectFlags aspectMask = aspectMaskForTextureFormat(m_format);
8411 const bool isCube = m_flags.testFlag(CubeMap);
8412 const bool isArray = m_flags.testFlag(TextureArray);
8413 const bool is3D = m_flags.testFlag(ThreeDimensional);
8414 const bool is1D = m_flags.testFlag(OneDimensional);
8416 VkImageViewCreateInfo viewInfo = {};
8417 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
8418 viewInfo.image = image;
8419 viewInfo.viewType = isCube
8420 ? VK_IMAGE_VIEW_TYPE_CUBE
8421 : (is3D ? VK_IMAGE_VIEW_TYPE_3D
8422 : (is1D ? (isArray ? VK_IMAGE_VIEW_TYPE_1D_ARRAY : VK_IMAGE_VIEW_TYPE_1D)
8423 : (isArray ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D)));
8424 viewInfo.format = viewFormat;
8425 viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
8426 viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
8427 viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
8428 viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
8429 viewInfo.subresourceRange.aspectMask = aspectMask;
8430 viewInfo.subresourceRange.baseMipLevel = uint32_t(level);
8431 viewInfo.subresourceRange.levelCount = 1;
8432 viewInfo.subresourceRange.baseArrayLayer = 0;
8433 viewInfo.subresourceRange.layerCount = isCube ? 6 : (isArray ? qMax(0, m_arraySize) : 1);
8435 VkImageView v = VK_NULL_HANDLE;
8437 VkResult err = rhiD
->df->vkCreateImageView(rhiD->dev, &viewInfo,
nullptr, &v);
8438 if (err != VK_SUCCESS) {
8439 qWarning(
"Failed to create image view: %d", err);
8440 return VK_NULL_HANDLE;
8443 perLevelImageViews[level] = v;
8448 AddressMode u, AddressMode v, AddressMode w)
8467 e.sampler.sampler = sampler;
8468 sampler = VK_NULL_HANDLE;
8472 rhiD->releaseQueue.append(e);
8473 rhiD->unregisterResource(
this);
8482 VkSamplerCreateInfo samplerInfo = {};
8483 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
8484 samplerInfo.magFilter = toVkFilter(m_magFilter);
8485 samplerInfo.minFilter = toVkFilter(m_minFilter);
8486 samplerInfo.mipmapMode = toVkMipmapMode(m_mipmapMode);
8487 samplerInfo.addressModeU = toVkAddressMode(m_addressU);
8488 samplerInfo.addressModeV = toVkAddressMode(m_addressV);
8489 samplerInfo.addressModeW = toVkAddressMode(m_addressW);
8490 samplerInfo.maxAnisotropy = 1.0f;
8491 samplerInfo.compareEnable = m_compareOp != Never;
8492 samplerInfo.compareOp = toVkTextureCompareOp(m_compareOp);
8493 samplerInfo.maxLod = m_mipmapMode == None ? 0.25f : 1000.0f;
8496 VkResult err = rhiD
->df->vkCreateSampler(rhiD->dev, &samplerInfo,
nullptr, &sampler);
8497 if (err != VK_SUCCESS) {
8498 qWarning(
"Failed to create sampler: %d", err);
8504 rhiD->registerResource(
this);
8511 serializedFormatData.reserve(64);
8525 rp = VK_NULL_HANDLE;
8533 e.renderPass.rp = rp;
8535 rp = VK_NULL_HANDLE;
8539 rhiD->releaseQueue.append(e);
8540 rhiD->unregisterResource(
this);
8546 return a.format == b.format
8547 && a.samples == b.samples
8548 && a.loadOp == b.loadOp
8549 && a.storeOp == b.storeOp
8550 && a.stencilLoadOp == b.stencilLoadOp
8551 && a.stencilStoreOp == b.stencilStoreOp
8552 && a.initialLayout == b.initialLayout
8553 && a.finalLayout == b.finalLayout;
8566 if (attDescs.size() != o->attDescs.size())
8568 if (colorRefs.size() != o->colorRefs.size())
8570 if (resolveRefs.size() != o->resolveRefs.size())
8576 if (multiViewCount != o->multiViewCount)
8581 for (
int i = 0, ie = colorRefs.size(); i != ie; ++i) {
8582 const uint32_t attIdx = colorRefs[i].attachment;
8583 if (attIdx != o->colorRefs[i].attachment)
8585 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8590 const uint32_t attIdx = dsRef.attachment;
8591 if (attIdx != o->dsRef.attachment)
8593 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8597 for (
int i = 0, ie = resolveRefs.size(); i != ie; ++i) {
8598 const uint32_t attIdx = resolveRefs[i].attachment;
8599 if (attIdx != o->resolveRefs[i].attachment)
8601 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8606 const uint32_t attIdx = dsResolveRef.attachment;
8607 if (attIdx != o->dsResolveRef.attachment)
8609 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8614 const uint32_t attIdx = shadingRateRef.attachment;
8615 if (attIdx != o->shadingRateRef.attachment)
8617 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8628 serializedFormatData.clear();
8629 auto p =
std::back_inserter(serializedFormatData);
8631 *p++ = attDescs.size();
8632 *p++ = colorRefs.size();
8633 *p++ = resolveRefs.size();
8637 *p++ = multiViewCount;
8639 auto serializeAttachmentData = [
this, &p](uint32_t attIdx) {
8640 const bool used = attIdx != VK_ATTACHMENT_UNUSED;
8641 const VkAttachmentDescription *a = used ? &attDescs[attIdx] :
nullptr;
8642 *p++ = used ? a->format : 0;
8643 *p++ = used ? a->samples : 0;
8644 *p++ = used ? a->loadOp : 0;
8645 *p++ = used ? a->storeOp : 0;
8646 *p++ = used ? a->stencilLoadOp : 0;
8647 *p++ = used ? a->stencilStoreOp : 0;
8648 *p++ = used ? a->initialLayout : 0;
8649 *p++ = used ? a->finalLayout : 0;
8652 for (
int i = 0, ie = colorRefs.size(); i != ie; ++i) {
8653 const uint32_t attIdx = colorRefs[i].attachment;
8655 serializeAttachmentData(attIdx);
8659 const uint32_t attIdx = dsRef.attachment;
8661 serializeAttachmentData(attIdx);
8664 for (
int i = 0, ie = resolveRefs.size(); i != ie; ++i) {
8665 const uint32_t attIdx = resolveRefs[i].attachment;
8667 serializeAttachmentData(attIdx);
8671 const uint32_t attIdx = dsResolveRef.attachment;
8673 serializeAttachmentData(attIdx);
8677 const uint32_t attIdx = shadingRateRef.attachment;
8679 serializeAttachmentData(attIdx);
8688 rpD->attDescs = attDescs;
8689 rpD->colorRefs = colorRefs;
8690 rpD->resolveRefs = resolveRefs;
8691 rpD->subpassDeps = subpassDeps;
8695 rpD->multiViewCount = multiViewCount;
8697 rpD->dsResolveRef = dsResolveRef;
8698 rpD->shadingRateRef = shadingRateRef;
8700 VkRenderPassCreateInfo rpInfo;
8701 VkSubpassDescription subpassDesc;
8702 fillRenderPassCreateInfo(&rpInfo, &subpassDesc, rpD);
8706 if (!multiViewHelper.prepare(&rpInfo, multiViewCount, rhiD->caps.multiView)) {
8711#ifdef VK_KHR_create_renderpass2
8712 if (rhiD->caps.renderPass2KHR) {
8714 VkRenderPassCreateInfo2KHR rpInfo2;
8715 RenderPass2SetupHelper rp2Helper(rhiD);
8716 if (!rp2Helper.prepare(&rpInfo2, &rpInfo, rpD, multiViewCount)) {
8720 VkResult err = rhiD->vkCreateRenderPass2KHR(rhiD->dev, &rpInfo2,
nullptr, &rpD->rp);
8721 if (err != VK_SUCCESS) {
8722 qWarning(
"Failed to create renderpass (using VkRenderPassCreateInfo2KHR): %d", err);
8729 VkResult err = rhiD
->df->vkCreateRenderPass(rhiD->dev, &rpInfo,
nullptr, &rpD->rp);
8730 if (err != VK_SUCCESS) {
8731 qWarning(
"Failed to create renderpass: %d", err);
8738 rhiD->registerResource(rpD);
8744 return serializedFormatData;
8749 nativeHandlesStruct.renderPass = rp;
8750 return &nativeHandlesStruct;
8808 return d.sampleCount;
8812 const QRhiTextureRenderTargetDescription &desc,
8817 rtv[att] = VK_NULL_HANDLE;
8818 resrtv[att] = VK_NULL_HANDLE;
8836 e.textureRenderTarget.fb = d.fb;
8837 d.fb = VK_NULL_HANDLE;
8840 e.textureRenderTarget.rtv[att] = rtv[att];
8841 e.textureRenderTarget.resrtv[att] = resrtv[att];
8842 rtv[att] = VK_NULL_HANDLE;
8843 resrtv[att] = VK_NULL_HANDLE;
8846 e.textureRenderTarget.dsv = dsv;
8847 dsv = VK_NULL_HANDLE;
8848 e.textureRenderTarget.resdsv = resdsv;
8849 resdsv = VK_NULL_HANDLE;
8851 e.textureRenderTarget.shadingRateMapView = shadingRateMapView;
8852 shadingRateMapView = VK_NULL_HANDLE;
8856 rhiD->releaseQueue.append(e);
8857 rhiD->unregisterResource(
this);
8867 if (!rhiD->createOffscreenRenderPass(rp,
8868 m_desc.cbeginColorAttachments(),
8869 m_desc.cendColorAttachments(),
8870 m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents),
8871 m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents),
8872 m_desc.depthTexture() && !m_flags.testFlag(DoNotStoreDepthStencilContents) && !m_desc.depthResolveTexture(),
8873 m_desc.depthStencilBuffer(),
8874 m_desc.depthTexture(),
8875 m_desc.depthResolveTexture(),
8876 m_desc.depthLayer(),
8877 m_desc.shadingRateMap()))
8885 rhiD->registerResource(rp);
8894 Q_ASSERT(m_desc.colorAttachmentCount() > 0 || m_desc.depthTexture());
8895 Q_ASSERT(!m_desc.depthStencilBuffer() || !m_desc.depthTexture());
8896 const bool hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
8899 QVarLengthArray<VkImageView, 8> views;
8900 d.multiViewCount = 0;
8902 d.colorAttCount = 0;
8904 for (
auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
8905 d.colorAttCount += 1;
8908 Q_ASSERT(texD || rbD);
8910 Q_ASSERT(texD->flags().testFlag(QRhiTexture::RenderTarget));
8911 const bool is1D = texD->flags().testFlag(QRhiTexture::OneDimensional);
8912 const bool isMultiView = it->multiViewCount() >= 2;
8913 if (isMultiView && d.multiViewCount == 0)
8914 d.multiViewCount = it->multiViewCount();
8915 VkImageViewCreateInfo viewInfo = {};
8916 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
8917 viewInfo.image = texD->image;
8918 viewInfo.viewType = is1D ? VK_IMAGE_VIEW_TYPE_1D
8919 : (isMultiView ? VK_IMAGE_VIEW_TYPE_2D_ARRAY
8920 : VK_IMAGE_VIEW_TYPE_2D);
8921 viewInfo.format = texD->viewFormat;
8922 viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
8923 viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
8924 viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
8925 viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
8926 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
8927 viewInfo.subresourceRange.baseMipLevel = uint32_t(it->level());
8928 viewInfo.subresourceRange.levelCount = 1;
8929 viewInfo.subresourceRange.baseArrayLayer = uint32_t(it->layer());
8930 viewInfo.subresourceRange.layerCount = uint32_t(isMultiView ? it->multiViewCount() : 1);
8931 VkResult err = rhiD
->df->vkCreateImageView(rhiD->dev, &viewInfo,
nullptr, &rtv[attIndex]);
8932 if (err != VK_SUCCESS) {
8933 qWarning(
"Failed to create render target image view: %d", err);
8936 views.append(rtv[attIndex]);
8937 if (attIndex == 0) {
8938 d.pixelSize = rhiD->q->sizeForMipLevel(it->level(), texD->pixelSize());
8939 d.sampleCount = texD->samples;
8944 if (attIndex == 0) {
8945 d.pixelSize = rbD->pixelSize();
8946 d.sampleCount = rbD->samples;
8952 if (hasDepthStencil) {
8953 if (m_desc.depthTexture()) {
8956 VkImageViewCreateInfo viewInfo = {};
8957 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
8958 viewInfo.image = depthTexD->image;
8959 viewInfo.viewType = d.multiViewCount > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D;
8960 viewInfo.format = depthTexD->viewFormat;
8961 viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
8962 viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
8963 viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
8964 viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
8965 viewInfo.subresourceRange.aspectMask = aspectMaskForTextureFormat(depthTexD->format());
8966 viewInfo.subresourceRange.levelCount = 1;
8967 if (m_desc.depthLayer() >= 0 && depthTexD->arraySize() >= 2) {
8968 viewInfo.subresourceRange.baseArrayLayer = uint32_t(m_desc.depthLayer());
8969 viewInfo.subresourceRange.layerCount = 1;
8972 viewInfo.subresourceRange.layerCount = qMax<uint32_t>(1, d.multiViewCount);
8973 VkResult err = rhiD
->df->vkCreateImageView(rhiD->dev, &viewInfo,
nullptr, &dsv);
8974 if (err != VK_SUCCESS) {
8975 qWarning(
"Failed to create depth-stencil image view for rt: %d", err);
8979 if (d.colorAttCount == 0) {
8980 d.pixelSize = depthTexD->pixelSize();
8981 d.sampleCount = depthTexD->samples;
8985 views.append(depthRbD->imageView);
8986 if (d.colorAttCount == 0) {
8987 d.pixelSize = depthRbD->pixelSize();
8988 d.sampleCount = depthRbD->samples;
8996 d.resolveAttCount = 0;
8998 Q_ASSERT(d.multiViewCount == 0 || d.multiViewCount >= 2);
8999 for (
auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
9000 if (it->resolveTexture()) {
9002 Q_ASSERT(resTexD->flags().testFlag(QRhiTexture::RenderTarget));
9003 d.resolveAttCount += 1;
9005 VkImageViewCreateInfo viewInfo = {};
9006 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
9007 viewInfo.image = resTexD->image;
9008 viewInfo.viewType = d.multiViewCount ? VK_IMAGE_VIEW_TYPE_2D_ARRAY
9009 : VK_IMAGE_VIEW_TYPE_2D;
9010 viewInfo.format = resTexD->viewFormat;
9011 viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
9012 viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
9013 viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
9014 viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
9015 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
9016 viewInfo.subresourceRange.baseMipLevel = uint32_t(it->resolveLevel());
9017 viewInfo.subresourceRange.levelCount = 1;
9018 viewInfo.subresourceRange.baseArrayLayer = uint32_t(it->resolveLayer());
9019 viewInfo.subresourceRange.layerCount = qMax<uint32_t>(1, d.multiViewCount);
9020 VkResult err = rhiD
->df->vkCreateImageView(rhiD->dev, &viewInfo,
nullptr, &resrtv[attIndex]);
9021 if (err != VK_SUCCESS) {
9022 qWarning(
"Failed to create render target resolve image view: %d", err);
9025 views.append(resrtv[attIndex]);
9029 if (m_desc.depthResolveTexture()) {
9031 Q_ASSERT(resTexD->flags().testFlag(QRhiTexture::RenderTarget));
9033 VkImageViewCreateInfo viewInfo = {};
9034 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
9035 viewInfo.image = resTexD->image;
9036 viewInfo.viewType = d.multiViewCount ? VK_IMAGE_VIEW_TYPE_2D_ARRAY
9037 : VK_IMAGE_VIEW_TYPE_2D;
9038 viewInfo.format = resTexD->viewFormat;
9039 viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
9040 viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
9041 viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
9042 viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
9043 viewInfo.subresourceRange.aspectMask = aspectMaskForTextureFormat(resTexD->format());
9044 viewInfo.subresourceRange.baseMipLevel = 0;
9045 viewInfo.subresourceRange.levelCount = 1;
9046 viewInfo.subresourceRange.baseArrayLayer = 0;
9047 viewInfo.subresourceRange.layerCount = qMax<uint32_t>(1, d.multiViewCount);
9048 VkResult err = rhiD
->df->vkCreateImageView(rhiD->dev, &viewInfo,
nullptr, &resdsv);
9049 if (err != VK_SUCCESS) {
9050 qWarning(
"Failed to create render target depth resolve image view: %d", err);
9053 views.append(resdsv);
9054 d.dsResolveAttCount = 1;
9056 d.dsResolveAttCount = 0;
9059 if (m_desc.shadingRateMap() && rhiD->caps.renderPass2KHR && rhiD->caps.imageBasedShadingRate) {
9061 Q_ASSERT(texD->flags().testFlag(QRhiTexture::UsedAsShadingRateMap));
9063 VkImageViewCreateInfo viewInfo = {};
9064 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
9065 viewInfo.image = texD->image;
9066 viewInfo.viewType = d.multiViewCount ? VK_IMAGE_VIEW_TYPE_2D_ARRAY
9067 : VK_IMAGE_VIEW_TYPE_2D;
9068 viewInfo.format = texD->viewFormat;
9069 viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
9070 viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
9071 viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
9072 viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
9073 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
9074 viewInfo.subresourceRange.baseMipLevel = 0;
9075 viewInfo.subresourceRange.levelCount = 1;
9076 viewInfo.subresourceRange.baseArrayLayer = 0;
9077 viewInfo.subresourceRange.layerCount = qMax<uint32_t>(1, d.multiViewCount);
9078 VkResult err = rhiD
->df->vkCreateImageView(rhiD->dev, &viewInfo,
nullptr, &shadingRateMapView);
9079 if (err != VK_SUCCESS) {
9080 qWarning(
"Failed to create render target shading rate map view: %d", err);
9083 views.append(shadingRateMapView);
9084 d.shadingRateAttCount = 1;
9086 d.shadingRateAttCount = 0;
9089 if (!m_renderPassDesc)
9090 qWarning(
"QVkTextureRenderTarget: No renderpass descriptor set. See newCompatibleRenderPassDescriptor() and setRenderPassDescriptor().");
9092 d.rp =
QRHI_RES(QVkRenderPassDescriptor, m_renderPassDesc);
9093 Q_ASSERT(d.rp && d.rp->rp);
9095 VkFramebufferCreateInfo fbInfo = {};
9096 fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
9097 fbInfo.renderPass = d.rp->rp;
9098 fbInfo.attachmentCount = uint32_t(views.count());
9099 fbInfo.pAttachments = views.constData();
9100 fbInfo.width = uint32_t(d.pixelSize.width());
9101 fbInfo.height = uint32_t(d.pixelSize.height());
9104 VkResult err = rhiD
->df->vkCreateFramebuffer(rhiD->dev, &fbInfo,
nullptr, &d.fb);
9105 if (err != VK_SUCCESS) {
9106 qWarning(
"Failed to create framebuffer: %d", err);
9110 QRhiRenderTargetAttachmentTracker::updateResIdList<QVkTexture, QVkRenderBuffer>(m_desc, &d.currentResIdList);
9113 rhiD->registerResource(
this);
9119 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QVkTexture, QVkRenderBuffer>(m_desc, d.currentResIdList))
9132 return d.sampleCount;
9150 sortedBindings.clear();
9151 sortedDynamicOffsetBindingNumbers.clear();
9157 e.shaderResourceBindings.poolIndex =
poolIndex;
9158 e.shaderResourceBindings.layout = layout;
9161 layout = VK_NULL_HANDLE;
9162 for (
int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i)
9163 descSets[i] = VK_NULL_HANDLE;
9167 rhiD->releaseQueue.append(e);
9168 rhiD->unregisterResource(
this);
9178 if (!rhiD->sanityCheckShaderResourceBindings(
this))
9181 rhiD->updateLayoutDesc(
this);
9183 for (
int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i)
9184 descSets[i] = VK_NULL_HANDLE;
9186 sortedBindings.clear();
9187 std::copy(m_bindings.cbegin(), m_bindings.cend(),
std::back_inserter(sortedBindings));
9188 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
9190 sortedDynamicOffsetBindingNumbers.clear();
9191 for (
const QRhiShaderResourceBinding &binding : std::as_const(sortedBindings)) {
9192 const QRhiShaderResourceBinding::Data *b = QRhiImplementation::shaderResourceBindingData(binding);
9193 if (b->type() == QRhiShaderResourceBinding::UniformBuffer && b->ubuf().buf) {
9194 if (b->ubuf().hasDynamicOffset)
9195 sortedDynamicOffsetBindingNumbers.append(b->binding);
9199 QVarLengthArray<VkDescriptorSetLayoutBinding, BINDING_PREALLOC> vkbindings;
9200 vkbindings.reserve(sortedBindings.size());
9201 for (
const QRhiShaderResourceBinding &binding : std::as_const(sortedBindings)) {
9202 const QRhiShaderResourceBinding::Data *b = QRhiImplementation::shaderResourceBindingData(binding);
9203 VkDescriptorSetLayoutBinding &vkbinding = vkbindings.emplace_back();
9204 vkbinding.binding = uint32_t(b->binding);
9205 vkbinding.descriptorType = toVkDescriptorType(b);
9206 if (b->type() == QRhiShaderResourceBinding::SampledTexture || b->type() == QRhiShaderResourceBinding::Texture)
9207 vkbinding.descriptorCount = b->stex().count();
9209 vkbinding.descriptorCount = 1;
9210 vkbinding.stageFlags = toVkShaderStageFlags(b->stage);
9213 VkDescriptorSetLayoutCreateInfo layoutInfo = {};
9214 layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
9215 layoutInfo.bindingCount = uint32_t(vkbindings.size());
9216 layoutInfo.pBindings = vkbindings.constData();
9218 VkResult err = rhiD
->df->vkCreateDescriptorSetLayout(rhiD->dev, &layoutInfo,
nullptr, &layout);
9219 if (err != VK_SUCCESS) {
9220 qWarning(
"Failed to create descriptor set layout: %d", err);
9223 rhiD->setObjectName(uint64_t(layout), VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, m_objectName);
9225 VkDescriptorSetAllocateInfo allocInfo = {};
9226 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
9230 layouts[i] = layout;
9231 allocInfo.pSetLayouts = layouts;
9232 if (!rhiD->allocateDescriptorSet(&allocInfo, descSets, &
poolIndex))
9236 boundResourceData[i].resize(sortedBindings.size());
9237 for (BoundResourceData &bd : boundResourceData[i])
9242 rhiD->setObjectName(uint64_t(descSets[i]), VK_OBJECT_TYPE_DESCRIPTOR_SET, m_objectName, i);
9246 rhiD->registerResource(
this);
9252 sortedBindings.clear();
9253 std::copy(m_bindings.cbegin(), m_bindings.cend(),
std::back_inserter(sortedBindings));
9254 if (!flags.testFlag(BindingsAreSorted))
9255 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
9257 sortedDynamicOffsetBindingNumbers.clear();
9258 for (
const QRhiShaderResourceBinding &binding : std::as_const(sortedBindings)) {
9259 const QRhiShaderResourceBinding::Data *b = QRhiImplementation::shaderResourceBindingData(binding);
9260 if (b->type() == QRhiShaderResourceBinding::UniformBuffer && b->ubuf().buf) {
9261 if (b->ubuf().hasDynamicOffset)
9262 sortedDynamicOffsetBindingNumbers.append(b->binding);
9276 Q_ASSERT(boundResourceData[i].size() == sortedBindings.size());
9277 for (BoundResourceData &bd : boundResourceData[i])
9296 if (!pipeline && !layout)
9303 e.pipelineState.pipeline = pipeline;
9304 e.pipelineState.layout = layout;
9306 pipeline = VK_NULL_HANDLE;
9307 layout = VK_NULL_HANDLE;
9311 rhiD->releaseQueue.append(e);
9312 rhiD->unregisterResource(
this);
9318 if (pipeline || layout)
9322 rhiD->pipelineCreationStart();
9323 if (!rhiD->sanityCheckGraphicsPipeline(
this))
9326 if (!rhiD->ensurePipelineCache())
9329 VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
9330 pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
9331 pipelineLayoutInfo.setLayoutCount = 1;
9333 Q_ASSERT(m_shaderResourceBindings && srbD->layout);
9334 pipelineLayoutInfo.pSetLayouts = &srbD->layout;
9335 VkPushConstantRange pushConstantRange = {};
9336 for (
const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
9337 for (
const QShaderDescription::PushConstantBlock &block : shaderStage.shader().description().pushConstantBlocks()) {
9338 pushConstantRange.stageFlags |= toVkShaderStage(shaderStage.type());
9339 pushConstantRange.size = qMax(pushConstantRange.size, uint32_t((block.size + 3) & ~3));
9342 if (pushConstantRange.size) {
9343 pipelineLayoutInfo.pushConstantRangeCount = 1;
9344 pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange;
9346 pushConstantStages = pushConstantRange.stageFlags;
9347 VkResult err = rhiD->df->vkCreatePipelineLayout(rhiD->dev, &pipelineLayoutInfo,
nullptr, &layout);
9348 if (err != VK_SUCCESS) {
9349 qWarning(
"Failed to create pipeline layout: %d", err);
9352 auto pipelineLayoutCleanup = qScopeGuard([
this, rhiD] {
9353 rhiD->df->vkDestroyPipelineLayout(rhiD->dev, layout,
nullptr);
9354 layout = VK_NULL_HANDLE;
9357 VkGraphicsPipelineCreateInfo pipelineInfo = {};
9358 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
9360 QVarLengthArray<VkShaderModule, 4> shaders;
9361 auto shaderModuleCleanup = qScopeGuard([rhiD, &shaders] {
9362 for (VkShaderModule shader : shaders)
9363 rhiD->df->vkDestroyShaderModule(rhiD->dev, shader,
nullptr);
9365 QVarLengthArray<VkPipelineShaderStageCreateInfo, 4> shaderStageCreateInfos;
9366 QVarLengthArray<QByteArray, 4> entryPointNames;
9367 for (
const QRhiShaderStage &shaderStage : m_shaderStages) {
9368 const QShader bakedShader = shaderStage.shader();
9369 const QShaderCode spirv = bakedShader.shader({ QShader::SpirvShader, 100, shaderStage.shaderVariant() });
9370 if (spirv.shader().isEmpty()) {
9371 qWarning() <<
"No SPIR-V 1.0 shader code found in baked shader" << bakedShader;
9374 VkShaderModule shader = rhiD->createShader(spirv.shader());
9376 shaders.append(shader);
9377 VkPipelineShaderStageCreateInfo shaderInfo = {};
9378 shaderInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
9379 shaderInfo.stage = toVkShaderStage(shaderStage.type());
9380 shaderInfo.module = shader;
9381 entryPointNames.append(spirv.entryPoint());
9382 shaderInfo.pName =
nullptr;
9383 shaderStageCreateInfos.append(shaderInfo);
9388 for (qsizetype i = 0, ie = shaders.count(); i != ie; ++i)
9389 shaderStageCreateInfos[i].pName = entryPointNames[i].constData();
9391 pipelineInfo.stageCount = uint32_t(shaderStageCreateInfos.size());
9392 pipelineInfo.pStages = shaderStageCreateInfos.constData();
9394 QVarLengthArray<VkVertexInputBindingDescription, 4> vertexBindings;
9395#ifdef VK_EXT_vertex_attribute_divisor
9396 QVarLengthArray<VkVertexInputBindingDivisorDescriptionEXT> nonOneStepRates;
9398 int bindingIndex = 0;
9399 for (
auto it = m_vertexInputLayout.cbeginBindings(), itEnd = m_vertexInputLayout.cendBindings();
9400 it != itEnd; ++it, ++bindingIndex)
9402 VkVertexInputBindingDescription bindingInfo = {
9403 uint32_t(bindingIndex),
9405 it->classification() == QRhiVertexInputBinding::PerVertex
9406 ? VK_VERTEX_INPUT_RATE_VERTEX : VK_VERTEX_INPUT_RATE_INSTANCE
9408 if (it->classification() == QRhiVertexInputBinding::PerInstance && it->instanceStepRate() != 1) {
9409#ifdef VK_EXT_vertex_attribute_divisor
9410 if (rhiD->caps.vertexAttribDivisor) {
9411 nonOneStepRates.append({ uint32_t(bindingIndex), it->instanceStepRate() });
9415 qWarning(
"QRhiVulkan: Instance step rates other than 1 not supported without "
9416 "VK_EXT_vertex_attribute_divisor on the device and "
9417 "VK_KHR_get_physical_device_properties2 on the instance");
9420 vertexBindings.append(bindingInfo);
9422 QVarLengthArray<VkVertexInputAttributeDescription, 4> vertexAttributes;
9423 for (
auto it = m_vertexInputLayout.cbeginAttributes(), itEnd = m_vertexInputLayout.cendAttributes();
9426 VkVertexInputAttributeDescription attributeInfo = {
9427 uint32_t(it->location()),
9428 uint32_t(it->binding()),
9429 toVkAttributeFormat(it->format()),
9432 vertexAttributes.append(attributeInfo);
9434 VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
9435 vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
9436 vertexInputInfo.vertexBindingDescriptionCount = uint32_t(vertexBindings.size());
9437 vertexInputInfo.pVertexBindingDescriptions = vertexBindings.constData();
9438 vertexInputInfo.vertexAttributeDescriptionCount = uint32_t(vertexAttributes.size());
9439 vertexInputInfo.pVertexAttributeDescriptions = vertexAttributes.constData();
9440#ifdef VK_EXT_vertex_attribute_divisor
9441 VkPipelineVertexInputDivisorStateCreateInfoEXT divisorInfo = {};
9442 if (!nonOneStepRates.isEmpty()) {
9443 divisorInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT;
9444 divisorInfo.vertexBindingDivisorCount = uint32_t(nonOneStepRates.size());
9445 divisorInfo.pVertexBindingDivisors = nonOneStepRates.constData();
9446 vertexInputInfo.pNext = &divisorInfo;
9449 pipelineInfo.pVertexInputState = &vertexInputInfo;
9451 QVarLengthArray<VkDynamicState, 8> dynEnable;
9452 dynEnable << VK_DYNAMIC_STATE_VIEWPORT;
9453 dynEnable << VK_DYNAMIC_STATE_SCISSOR;
9454 if (m_flags.testFlag(QRhiGraphicsPipeline::UsesBlendConstants))
9455 dynEnable << VK_DYNAMIC_STATE_BLEND_CONSTANTS;
9456 if (m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef))
9457 dynEnable << VK_DYNAMIC_STATE_STENCIL_REFERENCE;
9458#ifdef VK_KHR_fragment_shading_rate
9459 if (m_flags.testFlag(QRhiGraphicsPipeline::UsesShadingRate) && rhiD->caps.perDrawShadingRate)
9460 dynEnable << VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR;
9463 VkPipelineDynamicStateCreateInfo dynamicInfo = {};
9464 dynamicInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
9465 dynamicInfo.dynamicStateCount = uint32_t(dynEnable.size());
9466 dynamicInfo.pDynamicStates = dynEnable.constData();
9467 pipelineInfo.pDynamicState = &dynamicInfo;
9469 VkPipelineViewportStateCreateInfo viewportInfo = {};
9470 viewportInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
9471 viewportInfo.viewportCount = viewportInfo.scissorCount = 1;
9472 pipelineInfo.pViewportState = &viewportInfo;
9474 VkPipelineInputAssemblyStateCreateInfo inputAsmInfo = {};
9475 inputAsmInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
9476 inputAsmInfo.topology = toVkTopology(m_topology);
9477 inputAsmInfo.primitiveRestartEnable = (m_topology == TriangleStrip || m_topology == LineStrip);
9478 pipelineInfo.pInputAssemblyState = &inputAsmInfo;
9480 VkPipelineTessellationStateCreateInfo tessInfo = {};
9481#ifdef VK_VERSION_1_1
9482 VkPipelineTessellationDomainOriginStateCreateInfo originInfo = {};
9484 if (m_topology == Patches) {
9485 tessInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO;
9486 tessInfo.patchControlPoints = uint32_t(qMax(1, m_patchControlPointCount));
9493#ifdef VK_VERSION_1_1
9494 if (rhiD->caps.apiVersion >= QVersionNumber(1, 1)) {
9495 originInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO;
9496 originInfo.domainOrigin = VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT;
9497 tessInfo.pNext = &originInfo;
9499 qWarning(
"Proper tessellation support requires Vulkan 1.1 or newer, leaving domain origin unset");
9502 qWarning(
"QRhi was built without Vulkan 1.1 headers, this is not sufficient for proper tessellation support");
9505 pipelineInfo.pTessellationState = &tessInfo;
9508 VkPipelineRasterizationStateCreateInfo rastInfo = {};
9509 rastInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
9510 if (m_depthClamp && rhiD->caps.depthClamp)
9511 rastInfo.depthClampEnable = m_depthClamp;
9512 rastInfo.cullMode = toVkCullMode(m_cullMode);
9513 rastInfo.frontFace = toVkFrontFace(m_frontFace);
9514 if (m_depthBias != 0 || !qFuzzyIsNull(m_slopeScaledDepthBias)) {
9515 rastInfo.depthBiasEnable =
true;
9516 rastInfo.depthBiasConstantFactor =
float(m_depthBias);
9517 rastInfo.depthBiasSlopeFactor = m_slopeScaledDepthBias;
9519 rastInfo.lineWidth = rhiD->caps.wideLines ? m_lineWidth : 1.0f;
9520 rastInfo.polygonMode = toVkPolygonMode(m_polygonMode);
9521 pipelineInfo.pRasterizationState = &rastInfo;
9523 VkPipelineMultisampleStateCreateInfo msInfo = {};
9524 msInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
9525 msInfo.rasterizationSamples = rhiD->effectiveSampleCountBits(m_sampleCount);
9526 pipelineInfo.pMultisampleState = &msInfo;
9528 VkPipelineDepthStencilStateCreateInfo dsInfo = {};
9529 dsInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
9530 dsInfo.depthTestEnable = m_depthTest;
9531 dsInfo.depthWriteEnable = m_depthWrite;
9532 dsInfo.depthCompareOp = toVkCompareOp(m_depthOp);
9533 dsInfo.stencilTestEnable = m_stencilTest;
9534 if (m_stencilTest) {
9535 fillVkStencilOpState(&dsInfo.front, m_stencilFront);
9536 dsInfo.front.compareMask = m_stencilReadMask;
9537 dsInfo.front.writeMask = m_stencilWriteMask;
9538 fillVkStencilOpState(&dsInfo.back, m_stencilBack);
9539 dsInfo.back.compareMask = m_stencilReadMask;
9540 dsInfo.back.writeMask = m_stencilWriteMask;
9542 pipelineInfo.pDepthStencilState = &dsInfo;
9544 VkPipelineColorBlendStateCreateInfo blendInfo = {};
9545 blendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
9546 QVarLengthArray<VkPipelineColorBlendAttachmentState, 4> vktargetBlends;
9547 for (
const QRhiGraphicsPipeline::TargetBlend &b : std::as_const(m_targetBlends)) {
9548 VkPipelineColorBlendAttachmentState blend = {};
9549 blend.blendEnable = b.enable;
9550 blend.srcColorBlendFactor = toVkBlendFactor(b.srcColor);
9551 blend.dstColorBlendFactor = toVkBlendFactor(b.dstColor);
9552 blend.colorBlendOp = toVkBlendOp(b.opColor);
9553 blend.srcAlphaBlendFactor = toVkBlendFactor(b.srcAlpha);
9554 blend.dstAlphaBlendFactor = toVkBlendFactor(b.dstAlpha);
9555 blend.alphaBlendOp = toVkBlendOp(b.opAlpha);
9556 blend.colorWriteMask = toVkColorComponents(b.colorWrite);
9557 vktargetBlends.append(blend);
9559 if (vktargetBlends.isEmpty()) {
9560 VkPipelineColorBlendAttachmentState blend = {};
9561 blend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT
9562 | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
9563 vktargetBlends.append(blend);
9565 blendInfo.attachmentCount = uint32_t(vktargetBlends.size());
9566 blendInfo.pAttachments = vktargetBlends.constData();
9567 pipelineInfo.pColorBlendState = &blendInfo;
9569 pipelineInfo.layout = layout;
9571 Q_ASSERT(m_renderPassDesc &&
QRHI_RES(
const QVkRenderPassDescriptor, m_renderPassDesc)->rp);
9572 pipelineInfo.renderPass =
QRHI_RES(
const QVkRenderPassDescriptor, m_renderPassDesc)->rp;
9574 err = rhiD->df->vkCreateGraphicsPipelines(rhiD->dev, rhiD->pipelineCache, 1, &pipelineInfo,
nullptr, &pipeline);
9576 if (err != VK_SUCCESS) {
9577 qWarning(
"Failed to create graphics pipeline: %d", err);
9580 pipelineLayoutCleanup.dismiss();
9582 rhiD->setObjectName(uint64_t(pipeline), VK_OBJECT_TYPE_PIPELINE, m_objectName);
9584 rhiD->pipelineCreationEnd();
9585 lastActiveFrameSlot = -1;
9587 rhiD->registerResource(
this);
9591QVkComputePipeline::QVkComputePipeline(QRhiImplementation *rhi)
9592 : QRhiComputePipeline(rhi)
9596QVkComputePipeline::~QVkComputePipeline()
9601void QVkComputePipeline::destroy()
9603 if (!pipeline && !layout)
9606 QRhiVulkan::DeferredReleaseEntry e;
9607 e.type = QRhiVulkan::DeferredReleaseEntry::Pipeline;
9608 e.lastActiveFrameSlot = lastActiveFrameSlot;
9610 e.pipelineState.pipeline = pipeline;
9611 e.pipelineState.layout = layout;
9613 pipeline = VK_NULL_HANDLE;
9614 layout = VK_NULL_HANDLE;
9618 rhiD->releaseQueue.append(e);
9619 rhiD->unregisterResource(
this);
9623bool QVkComputePipeline::create()
9625 if (pipeline || layout)
9629 rhiD->pipelineCreationStart();
9630 if (!rhiD->ensurePipelineCache())
9633 VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
9634 pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
9635 pipelineLayoutInfo.setLayoutCount = 1;
9636 QVkShaderResourceBindings *srbD =
QRHI_RES(QVkShaderResourceBindings, m_shaderResourceBindings);
9637 Q_ASSERT(m_shaderResourceBindings && srbD->layout);
9638 pipelineLayoutInfo.pSetLayouts = &srbD->layout;
9639 VkPushConstantRange pushConstantRange = {};
9640 for (
const QShaderDescription::PushConstantBlock &block : m_shaderStage.shader().description().pushConstantBlocks()) {
9641 pushConstantRange.stageFlags |= VK_SHADER_STAGE_COMPUTE_BIT;
9642 pushConstantRange.size = qMax(pushConstantRange.size, uint32_t((block.size + 3) & ~3));
9644 if (pushConstantRange.size) {
9645 pipelineLayoutInfo.pushConstantRangeCount = 1;
9646 pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange;
9648 pushConstantStages = pushConstantRange.stageFlags;
9649 VkResult err = rhiD->df->vkCreatePipelineLayout(rhiD->dev, &pipelineLayoutInfo,
nullptr, &layout);
9650 if (err != VK_SUCCESS) {
9651 qWarning(
"Failed to create pipeline layout: %d", err);
9654 auto pipelineLayoutCleanup = qScopeGuard([
this, rhiD] {
9655 rhiD->df->vkDestroyPipelineLayout(rhiD->dev, layout,
nullptr);
9656 layout = VK_NULL_HANDLE;
9659 VkComputePipelineCreateInfo pipelineInfo = {};
9660 pipelineInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
9661 pipelineInfo.layout = layout;
9663 if (m_shaderStage.type() != QRhiShaderStage::Compute) {
9664 qWarning(
"Compute pipeline requires a compute shader stage");
9667 const QShader bakedShader = m_shaderStage.shader();
9668 const QShaderCode spirv = bakedShader.shader({ QShader::SpirvShader, 100, m_shaderStage.shaderVariant() });
9669 if (spirv.shader().isEmpty()) {
9670 qWarning() <<
"No SPIR-V 1.0 shader code found in baked shader" << bakedShader;
9673 if (bakedShader.stage() != QShader::ComputeStage) {
9674 qWarning() << bakedShader <<
"is not a compute shader";
9677 VkShaderModule shader = rhiD->createShader(spirv.shader());
9680 auto shaderModuleCleanup = qScopeGuard([rhiD, shader] {
9681 rhiD->df->vkDestroyShaderModule(rhiD->dev, shader,
nullptr);
9683 VkPipelineShaderStageCreateInfo shaderInfo = {};
9684 shaderInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
9685 shaderInfo.stage = VK_SHADER_STAGE_COMPUTE_BIT;
9686 shaderInfo.module = shader;
9687 const QByteArray entryPointName = spirv.entryPoint();
9688 shaderInfo.pName = entryPointName.constData();
9689 pipelineInfo.stage = shaderInfo;
9691 err = rhiD->df->vkCreateComputePipelines(rhiD->dev, rhiD->pipelineCache, 1, &pipelineInfo,
nullptr, &pipeline);
9692 if (err != VK_SUCCESS) {
9693 qWarning(
"Failed to create graphics pipeline: %d", err);
9696 pipelineLayoutCleanup.dismiss();
9698 rhiD->setObjectName(uint64_t(pipeline), VK_OBJECT_TYPE_PIPELINE, m_objectName);
9700 rhiD->pipelineCreationEnd();
9701 lastActiveFrameSlot = -1;
9703 rhiD->registerResource(
this);
9707QVkCommandBuffer::QVkCommandBuffer(QRhiImplementation *rhi)
9708 : QRhiCommandBuffer(rhi)
9713QVkCommandBuffer::~QVkCommandBuffer()
9718void QVkCommandBuffer::destroy()
9723const QRhiNativeHandles *QVkCommandBuffer::nativeHandles()
9731 if (recordingPass == QVkCommandBuffer::NoPass) {
9732 nativeHandlesStruct.commandBuffer = cb;
9734 if (passUsesSecondaryCb && !activeSecondaryCbStack.isEmpty())
9735 nativeHandlesStruct.commandBuffer = activeSecondaryCbStack.last();
9737 nativeHandlesStruct.commandBuffer = cb;
9740 return &nativeHandlesStruct;
9743QVkSwapChain::QVkSwapChain(QRhiImplementation *rhi)
9744 : QRhiSwapChain(rhi),
9745 rtWrapper(rhi,
this),
9746 rtWrapperRight(rhi,
this),
9751QVkSwapChain::~QVkSwapChain()
9756void QVkSwapChain::destroy()
9758 if (sc == VK_NULL_HANDLE)
9763 rhiD->swapchains.remove(
this);
9764 rhiD->releaseSwapChainResources(
this);
9767 for (
int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
9768 QVkSwapChain::FrameResources &frame(frameRes[i]);
9769 frame.cmdBuf = VK_NULL_HANDLE;
9770 frame.timestampQueryIndex = -1;
9773 surface = lastConnectedSurface = VK_NULL_HANDLE;
9776 rhiD->unregisterResource(
this);
9779QRhiCommandBuffer *QVkSwapChain::currentFrameCommandBuffer()
9784QRhiRenderTarget *QVkSwapChain::currentFrameRenderTarget()
9789QRhiRenderTarget *QVkSwapChain::currentFrameRenderTarget(StereoTargetBuffer targetBuffer)
9791 return !stereo || targetBuffer == StereoTargetBuffer::LeftBuffer ? &rtWrapper : &rtWrapperRight;
9794QSize QVkSwapChain::surfacePixelSize()
9796 if (!ensureSurface())
9801 VkSurfaceCapabilitiesKHR surfaceCaps = {};
9803 rhiD->vkGetPhysicalDeviceSurfaceCapabilitiesKHR(rhiD->physDev, surface, &surfaceCaps);
9804 VkExtent2D bufferSize = surfaceCaps.currentExtent;
9805 if (bufferSize.width == uint32_t(-1)) {
9806 Q_ASSERT(bufferSize.height == uint32_t(-1));
9807 return m_window->size() * m_window->devicePixelRatio();
9809 return QSize(
int(bufferSize.width),
int(bufferSize.height));
9812static inline bool hdrFormatMatchesVkSurfaceFormat(QRhiSwapChain::Format f,
const VkSurfaceFormatKHR &s)
9815 case QRhiSwapChain::HDRExtendedSrgbLinear:
9816 return s.format == VK_FORMAT_R16G16B16A16_SFLOAT
9817 && s.colorSpace == VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT;
9818 case QRhiSwapChain::HDR10:
9819 return s.format == VK_FORMAT_A2B10G10R10_UNORM_PACK32
9820 && s.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT;
9821 case QRhiSwapChain::HDRExtendedDisplayP3Linear:
9822 return s.format == VK_FORMAT_R16G16B16A16_SFLOAT
9823 && s.colorSpace == VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT;
9830bool QVkSwapChain::isFormatSupported(Format f)
9836 qWarning(
"Attempted to call isFormatSupported() without a window set");
9841 VkSurfaceKHR surf = QVulkanInstance::surfaceForWindow(m_window);
9844 uint32_t formatCount = 0;
9845 rhiD->vkGetPhysicalDeviceSurfaceFormatsKHR(rhiD->physDev, surf, &formatCount,
nullptr);
9846 QVarLengthArray<VkSurfaceFormatKHR, 8> formats(formatCount);
9848 rhiD->vkGetPhysicalDeviceSurfaceFormatsKHR(rhiD->physDev, surf, &formatCount, formats.data());
9849 for (uint32_t i = 0; i < formatCount; ++i) {
9850 if (hdrFormatMatchesVkSurfaceFormat(f, formats[i]))
9858QRhiSwapChainHdrInfo QVkSwapChain::hdrInfo()
9860 QRhiSwapChainHdrInfo info = QRhiSwapChain::hdrInfo();
9862 QRHI_RES_RHI(QRhiVulkan);
9864 if (m_window && rhiD->adapterLuidValid)
9865 info = rhiD->dxgiHdrInfo->queryHdrInfo(m_window);
9870QRhiRenderPassDescriptor *QVkSwapChain::newCompatibleRenderPassDescriptor()
9874 if (!ensureSurface())
9878 QVkRenderPassDescriptor *rp =
new QVkRenderPassDescriptor(m_rhi);
9879 if (!rhiD->createDefaultRenderPass(rp,
9880 m_depthStencil !=
nullptr,
9890 rp->updateSerializedFormat();
9891 rhiD->registerResource(rp);
9895static inline bool isSrgbFormat(VkFormat format)
9898 case VK_FORMAT_R8_SRGB:
9899 case VK_FORMAT_R8G8_SRGB:
9900 case VK_FORMAT_R8G8B8_SRGB:
9901 case VK_FORMAT_B8G8R8_SRGB:
9902 case VK_FORMAT_R8G8B8A8_SRGB:
9903 case VK_FORMAT_B8G8R8A8_SRGB:
9904 case VK_FORMAT_A8B8G8R8_SRGB_PACK32:
9911bool QVkSwapChain::ensureSurface()
9919 VkSurfaceKHR surf = QVulkanInstance::surfaceForWindow(m_window);
9921 qWarning(
"Failed to get surface for window");
9924 if (surface == surf)
9930 if (!rhiD->inst->supportsPresent(rhiD->physDev, rhiD->gfxQueueFamilyIdx, m_window)) {
9931 qWarning(
"Presenting not supported on this window");
9935 quint32 formatCount = 0;
9936 rhiD->vkGetPhysicalDeviceSurfaceFormatsKHR(rhiD->physDev, surface, &formatCount,
nullptr);
9937 QList<VkSurfaceFormatKHR> formats(formatCount);
9938 rhiD->vkGetPhysicalDeviceSurfaceFormatsKHR(rhiD->physDev, surface, &formatCount,
9942 colorFormat = formats.constFirst().format;
9943 colorSpace = formats.constFirst().colorSpace;
9946 const bool srgbRequested = m_flags.testFlag(sRGB);
9947 bool foundBestFormat =
false;
9948 if (m_format == SDR) {
9949 for (
int i = 0; i <
int(formatCount); ++i) {
9951 if (srgbRequested) {
9952 ok = defaultSrgbColorFormat == formats[i].format;
9954 ok = defaultColorFormat == formats[i].format;
9957 foundBestFormat =
true;
9958 colorFormat = formats[i].format;
9959 colorSpace = formats[i].colorSpace;
9966 if (!foundBestFormat && (m_format != SDR || srgbRequested)) {
9967 for (
int i = 0; i <
int(formatCount); ++i) {
9969 if (m_format != SDR) {
9970 ok = hdrFormatMatchesVkSurfaceFormat(m_format, formats[i]);
9971 }
else if (srgbRequested) {
9972 ok = isSrgbFormat(formats[i].format);
9975 colorFormat = formats[i].format;
9976 colorSpace = formats[i].colorSpace;
9983 if (m_format != SDR) {
9984 VkSurfaceFormatKHR format{};
9985 format.format = colorFormat;
9986 format.colorSpace = colorSpace;
9987 if (!hdrFormatMatchesVkSurfaceFormat(m_format, format)) {
9988 qWarning(
"Failed to select a suitable VkFormat for HDR, using format %d as fallback",
9992 if (srgbRequested && !isSrgbFormat(colorFormat)) {
9993 qWarning(
"Failed to select a suitable VkFormat for sRGB, using format %d as fallback",
9998#if QT_CONFIG(wayland)
10003 const bool hasPassThrough =
10004 std::any_of(formats.begin(), formats.end(), [
this](
const VkSurfaceFormatKHR &fmt) {
10005 return fmt.format == colorFormat
10006 && fmt.colorSpace == VK_COLOR_SPACE_PASS_THROUGH_EXT;
10008 if (hasPassThrough) {
10009 colorSpace = VK_COLOR_SPACE_PASS_THROUGH_EXT;
10013 samples = rhiD->effectiveSampleCountBits(m_sampleCount);
10015 quint32 presModeCount = 0;
10016 rhiD->vkGetPhysicalDeviceSurfacePresentModesKHR(rhiD->physDev, surface, &presModeCount,
nullptr);
10017 supportedPresentationModes.resize(presModeCount);
10018 rhiD->vkGetPhysicalDeviceSurfacePresentModesKHR(rhiD->physDev, surface, &presModeCount,
10019 supportedPresentationModes.data());
10024bool QVkSwapChain::createOrResize()
10027 const bool needsRegistration = !window || window != m_window;
10034 if (window && window != m_window)
10038 pixelSize = surfacePixelSize();
10040 if (!rhiD->recreateSwapChain(
this)) {
10041 qWarning(
"Failed to create new swapchain");
10045 if (needsRegistration || !rhiD->swapchains.contains(
this))
10046 rhiD->swapchains.insert(
this);
10048 if (m_depthStencil && m_depthStencil->sampleCount() != m_sampleCount) {
10049 qWarning(
"Depth-stencil buffer's sampleCount (%d) does not match color buffers' sample count (%d). Expect problems.",
10050 m_depthStencil->sampleCount(), m_sampleCount);
10052 if (m_depthStencil && m_depthStencil->pixelSize() != pixelSize) {
10053 if (m_depthStencil->flags().testFlag(QRhiRenderBuffer::UsedWithSwapChainOnly)) {
10054 m_depthStencil->setPixelSize(pixelSize);
10055 if (!m_depthStencil->create())
10056 qWarning(
"Failed to rebuild swapchain's associated depth-stencil buffer for size %dx%d",
10057 pixelSize.width(), pixelSize.height());
10059 qWarning(
"Depth-stencil buffer's size (%dx%d) does not match the surface size (%dx%d). Expect problems.",
10060 m_depthStencil->pixelSize().width(), m_depthStencil->pixelSize().height(),
10061 pixelSize.width(), pixelSize.height());
10065 if (!m_renderPassDesc)
10066 qWarning(
"QVkSwapChain: No renderpass descriptor set. See newCompatibleRenderPassDescriptor() and setRenderPassDescriptor().");
10068 rtWrapper.setRenderPassDescriptor(m_renderPassDesc);
10069 rtWrapper.d.rp =
QRHI_RES(QVkRenderPassDescriptor, m_renderPassDesc);
10070 Q_ASSERT(rtWrapper.d.rp && rtWrapper.d.rp->rp);
10072 rtWrapper.d.pixelSize = pixelSize;
10073 rtWrapper.d.dpr =
float(window->devicePixelRatio());
10074 rtWrapper.d.sampleCount = samples;
10075 rtWrapper.d.colorAttCount = 1;
10076 if (m_depthStencil) {
10077 rtWrapper.d.dsAttCount = 1;
10078 ds =
QRHI_RES(QVkRenderBuffer, m_depthStencil);
10080 rtWrapper.d.dsAttCount = 0;
10083 rtWrapper.d.dsResolveAttCount = 0;
10084 if (samples > VK_SAMPLE_COUNT_1_BIT)
10085 rtWrapper.d.resolveAttCount = 1;
10087 rtWrapper.d.resolveAttCount = 0;
10089 if (shadingRateMapView)
10090 rtWrapper.d.shadingRateAttCount = 1;
10092 rtWrapper.d.shadingRateAttCount = 0;
10094 for (
int i = 0; i < bufferCount; ++i) {
10095 QVkSwapChain::ImageResources &image(imageRes[i]);
10097 QVarLengthArray<VkImageView, 4> views;
10098 views.append(samples > VK_SAMPLE_COUNT_1_BIT ? image.msaaImageView : image.imageView);
10100 views.append(ds->imageView);
10101 if (samples > VK_SAMPLE_COUNT_1_BIT)
10102 views.append(image.imageView);
10103 if (shadingRateMapView)
10104 views.append(shadingRateMapView);
10106 VkFramebufferCreateInfo fbInfo = {};
10107 fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
10108 fbInfo.renderPass = rtWrapper.d.rp->rp;
10109 fbInfo.attachmentCount = uint32_t(views.count());
10110 fbInfo.pAttachments = views.constData();
10111 fbInfo.width = uint32_t(pixelSize.width());
10112 fbInfo.height = uint32_t(pixelSize.height());
10115 VkResult err = rhiD->df->vkCreateFramebuffer(rhiD->dev, &fbInfo,
nullptr, &image.fb);
10116 if (err != VK_SUCCESS) {
10117 qWarning(
"Failed to create framebuffer: %d", err);
10123 rtWrapperRight.setRenderPassDescriptor(
10125 rtWrapperRight.d.rp =
QRHI_RES(QVkRenderPassDescriptor, m_renderPassDesc);
10126 Q_ASSERT(rtWrapperRight.d.rp && rtWrapperRight.d.rp->rp);
10128 rtWrapperRight.d.pixelSize = pixelSize;
10129 rtWrapperRight.d.dpr =
float(window->devicePixelRatio());
10130 rtWrapperRight.d.sampleCount = samples;
10131 rtWrapperRight.d.colorAttCount = 1;
10132 if (m_depthStencil) {
10133 rtWrapperRight.d.dsAttCount = 1;
10134 ds =
QRHI_RES(QVkRenderBuffer, m_depthStencil);
10136 rtWrapperRight.d.dsAttCount = 0;
10139 rtWrapperRight.d.dsResolveAttCount = 0;
10140 if (samples > VK_SAMPLE_COUNT_1_BIT)
10141 rtWrapperRight.d.resolveAttCount = 1;
10143 rtWrapperRight.d.resolveAttCount = 0;
10145 for (
int i = 0; i < bufferCount; ++i) {
10146 QVkSwapChain::ImageResources &image(imageRes[i + bufferCount]);
10148 QVarLengthArray<VkImageView, 4> views;
10149 views.append(samples > VK_SAMPLE_COUNT_1_BIT ? image.msaaImageView : image.imageView);
10151 views.append(ds->imageView);
10152 if (samples > VK_SAMPLE_COUNT_1_BIT)
10153 views.append(image.imageView);
10154 if (shadingRateMapView)
10155 views.append(shadingRateMapView);
10157 VkFramebufferCreateInfo fbInfo = {};
10158 fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
10159 fbInfo.renderPass = rtWrapperRight.d.rp->rp;
10160 fbInfo.attachmentCount = uint32_t(views.count());
10161 fbInfo.pAttachments = views.constData();
10162 fbInfo.width = uint32_t(pixelSize.width());
10163 fbInfo.height = uint32_t(pixelSize.height());
10166 VkResult err = rhiD->df->vkCreateFramebuffer(rhiD->dev, &fbInfo,
nullptr, &image.fb);
10167 if (err != VK_SUCCESS) {
10168 qWarning(
"Failed to create framebuffer: %d", err);
10176 if (needsRegistration)
10177 rhiD->registerResource(
this);
10179 m_currentPixelSize = pixelSize;
const QRhiPassResourceMap< QRhiTexture *, Texture, 12 > & textures() const
void registerBuffer(QRhiBuffer *buf, int slot, BufferAccess *access, BufferStage *stage, const UsageState &state)
void registerTexture(QRhiTexture *tex, TextureAccess *access, TextureStage *stage, const UsageState &state)
const QRhiPassResourceMap< QRhiBuffer *, Buffer, 12 > & buffers() const
static QRhiResourceUpdateBatchPrivate * get(QRhiResourceUpdateBatch *b)
void recordTransitionPassResources(QVkCommandBuffer *cbD, const QRhiPassResourceTracker &tracker)
VkCommandBuffer startSecondaryCommandBuffer(QVkRenderTargetData *rtD=nullptr)
QRhiSwapChain * createSwapChain() override
void debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg) override
int resourceLimit(QRhi::ResourceLimit limit) const override
bool isDeviceLost() const override
void prepareUploadSubres(QVkTexture *texD, int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc, size_t *curOfs, void *mp, BufferImageCopyList *copyInfos)
void executeDeferredReleases(bool forced=false)
uint32_t chooseTransientImageMemType(VkImage img, uint32_t startIndex)
QRhi::FrameOpResult finish() override
QRhiTextureRenderTarget * createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc, QRhiTextureRenderTarget::Flags flags) override
bool createTransientImage(VkFormat format, const QSize &pixelSize, VkImageUsageFlags usage, VkImageAspectFlags aspectMask, VkSampleCountFlagBits samples, VkDeviceMemory *mem, VkImage *images, VkImageView *views, int count)
void setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor) override
void releaseCachedResources() override
QVkSwapChain * currentSwapChain
void collectComputeBarriers(QVkCommandBuffer *cbD, QVarLengthArray< VkImageMemoryBarrier, 8 > *imageBarriers, QVarLengthArray< VkBufferMemoryBarrier, 8 > *bufferBarriers)
QRhiVulkan(QRhiVulkanInitParams *params, QRhiVulkanNativeHandles *importParams=nullptr)
void draw(QRhiCommandBuffer *cb, quint32 vertexCount, quint32 instanceCount, quint32 firstVertex, quint32 firstInstance) override
void setStencilRef(QRhiCommandBuffer *cb, quint32 refValue) override
void endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
QList< int > supportedSampleCounts() const override
QRhi::FrameOpResult endOffscreenFrame(QRhi::EndFrameFlags flags) override
void updateShaderResourceBindings(QRhiShaderResourceBindings *srb)
void setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data) override
void dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset) override
double elapsedSecondsFromTimestamp(quint64 timestamp[2], bool *ok)
QRhi::FrameOpResult beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags) override
void drawIndexedIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
void trackedBufferBarrier(QVkCommandBuffer *cbD, QVkBuffer *bufD, int slot, VkAccessFlags access, VkPipelineStageFlags stage)
QRhi::FrameOpResult waitCommandCompletion(int frameSlot)
void endExternal(QRhiCommandBuffer *cb) override
void dispatch(QRhiCommandBuffer *cb, int x, int y, int z) override
bool allocateDescriptorSet(VkDescriptorSetAllocateInfo *allocInfo, VkDescriptorSet *result, int *resultPoolIndex)
bool isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const override
void drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
VkResult createDescriptorPool(VkDescriptorPool *pool)
void prepareNewFrame(QRhiCommandBuffer *cb)
void subresourceBarrier(QVkCommandBuffer *cbD, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, VkAccessFlags srcAccess, VkAccessFlags dstAccess, VkPipelineStageFlags srcStage, VkPipelineStageFlags dstStage, int startLayer, int layerCount, int startLevel, int levelCount)
QList< QSize > supportedShadingRates(int sampleCount) const override
void printExtraErrorInfo(VkResult err)
void setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps) override
QRhi::FrameOpResult beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags) override
QRhi::FrameOpResult startPrimaryCommandBuffer(VkCommandBuffer *cb)
double lastCompletedGpuTime(QRhiCommandBuffer *cb) override
void recordStencilRef(QVkCommandBuffer *cbD, quint32 refValue)
void trackedRegisterTexture(QRhiPassResourceTracker *passResTracker, QVkTexture *texD, QRhiPassResourceTracker::TextureAccess access, QRhiPassResourceTracker::TextureStage stage)
bool releaseCachedResourcesCalledBeforeFrameStart
QRhiGraphicsPipeline * createGraphicsPipeline() override
QRhiComputePipeline * createComputePipeline() override
void setAllocationName(QVkAlloc allocation, const QByteArray &name, int slot=-1)
QRhiTexture * createTexture(QRhiTexture::Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, QRhiTexture::Flags flags) override
void debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name) override
const QRhiNativeHandles * nativeHandles(QRhiCommandBuffer *cb) override
bool recreateSwapChain(QRhiSwapChain *swapChain)
Q_DECL_COLD_FUNCTION void printDeviceLossErrorInfo() const
bool ensurePipelineCache(const void *initialData=nullptr, size_t initialDataSize=0)
void resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
void depthStencilExplicitBarrier(QVkCommandBuffer *cbD, QVkRenderBuffer *rbD)
void trackedImageBarrier(QVkCommandBuffer *cbD, QVkTexture *texD, VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stage)
VkShaderModule createShader(const QByteArray &spirv)
void enqueueTransitionPassResources(QVkCommandBuffer *cbD)
void beginComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
bool create(QRhi::Flags flags) override
QVulkanDeviceFunctions * df
void setObjectName(uint64_t object, VkObjectType type, const QByteArray &name, int slot=-1)
bool isFeatureSupported(QRhi::Feature feature) const override
void recordPrimaryCommandBuffer(QVkCommandBuffer *cbD)
bool isYUpInFramebuffer() const override
void setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize) override
void debugMarkEnd(QRhiCommandBuffer *cb) override
QRhiSampler * createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter, QRhiSampler::Filter mipmapMode, QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w) override
void releaseSwapChainResources(QRhiSwapChain *swapChain)
bool createOffscreenRenderPass(QVkRenderPassDescriptor *rpD, const QRhiColorAttachment *colorAttachmentsBegin, const QRhiColorAttachment *colorAttachmentsEnd, bool preserveColor, bool preserveDs, bool storeDs, QRhiRenderBuffer *depthStencilBuffer, QRhiTexture *depthTexture, QRhiTexture *depthResolveTexture, int depthLayer, QRhiShadingRateMap *shadingRateMap)
void drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount, quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance) override
VkDeviceSize subresUploadByteSize(const QRhiTextureSubresourceUploadDescription &subresDesc) const
void endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
void trackedRegisterBuffer(QRhiPassResourceTracker *passResTracker, QVkBuffer *bufD, int slot, QRhiPassResourceTracker::BufferAccess access, QRhiPassResourceTracker::BufferStage stage)
VkFormat optimalDepthStencilFormat()
QRhiStats statistics() override
void setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps) override
void drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
void activateTextureRenderTarget(QVkCommandBuffer *cbD, QVkTextureRenderTarget *rtD)
void executeBufferHostWritesForSlot(QVkBuffer *bufD, int slot)
void setDefaultScissor(QVkCommandBuffer *cbD)
bool isYUpInNDC() const override
const QRhiNativeHandles * nativeHandles() override
QRhiShadingRateMap * createShadingRateMap() override
void setPipelineCacheData(const QByteArray &data) override
void setVertexInput(QRhiCommandBuffer *cb, int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings, QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat) override
QRhiShaderResourceBindings * createShaderResourceBindings() override
void finishActiveReadbacks(bool forced=false)
void ensureCommandPoolForNewFrame()
QByteArray pipelineCacheData() override
void endAndEnqueueSecondaryCommandBuffer(VkCommandBuffer cb, QVkCommandBuffer *cbD)
void beginPass(QRhiCommandBuffer *cb, QRhiRenderTarget *rt, const QColor &colorClearValue, const QRhiDepthStencilClearValue &depthStencilClearValue, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
void drawIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
void setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) override
bool isClipDepthZeroToOne() const override
void enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdateBatch *resourceUpdates)
void setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb, int dynamicOffsetCount, const QRhiCommandBuffer::DynamicOffset *dynamicOffsets) override
QMatrix4x4 clipSpaceCorrMatrix() const override
int ubufAlignment() const override
QRhiDriverInfo driverInfo() const override
void beginExternal(QRhiCommandBuffer *cb) override
void setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport) override
bool createDefaultRenderPass(QVkRenderPassDescriptor *rpD, bool hasDepthStencil, VkSampleCountFlagBits samples, VkFormat colorFormat, QRhiShadingRateMap *shadingRateMap)
QRhi::FrameOpResult endAndSubmitPrimaryCommandBuffer(VkCommandBuffer cb, VkFence cmdFence, VkSemaphore *waitSem, VkSemaphore *signalSem)
QRhi::FrameOpResult endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags) override
VkSampleCountFlagBits effectiveSampleCountBits(int sampleCount)
bool makeThreadLocalNativeContextCurrent() override
QRhiDriverInfo info() const override
Combined button and popup list for selecting options.
static VkPolygonMode toVkPolygonMode(QRhiGraphicsPipeline::PolygonMode mode)
static VkCullModeFlags toVkCullMode(QRhiGraphicsPipeline::CullMode c)
static bool accessIsWrite(VkAccessFlags access)
static VkCompareOp toVkTextureCompareOp(QRhiSampler::CompareOp op)
static QVulkanInstance * globalVulkanInstance
static VkBufferUsageFlagBits toVkBufferUsage(QRhiBuffer::UsageFlags usage)
static QRhiTexture::Format swapchainReadbackTextureFormat(VkFormat format, QRhiTexture::Flags *flags)
static VkStencilOp toVkStencilOp(QRhiGraphicsPipeline::StencilOp op)
static bool qvk_debug_filter(QVulkanInstance::DebugMessageSeverityFlags severity, QVulkanInstance::DebugMessageTypeFlags type, const void *callbackData)
static QVkBuffer::UsageState toVkBufferUsageState(QRhiPassResourceTracker::UsageState usage)
static bool attachmentDescriptionEquals(const VkAttachmentDescription &a, const VkAttachmentDescription &b)
static VkPipelineStageFlags toVkPipelineStage(QRhiPassResourceTracker::TextureStage stage)
static VkAccessFlags toVkAccess(QRhiPassResourceTracker::BufferAccess access)
static VkImageLayout toVkLayout(QRhiPassResourceTracker::TextureAccess access)
static VkFormat toVkAttributeFormat(QRhiVertexInputAttribute::Format format)
static QVkTexture::UsageState toVkTextureUsageState(QRhiPassResourceTracker::UsageState usage)
static VkPipelineStageFlags toVkPipelineStage(QRhiPassResourceTracker::BufferStage stage)
static QRhiDriverInfo::DeviceType toRhiDeviceType(VkPhysicalDeviceType type)
static QRhiPassResourceTracker::UsageState toPassTrackerUsageState(const QVkBuffer::UsageState &bufUsage)
static VkColorComponentFlags toVkColorComponents(QRhiGraphicsPipeline::ColorMask c)
static VkFilter toVkFilter(QRhiSampler::Filter f)
static VkPrimitiveTopology toVkTopology(QRhiGraphicsPipeline::Topology t)
static void qrhivk_releaseTexture(const QRhiVulkan::DeferredReleaseEntry &e, VkDevice dev, QVulkanDeviceFunctions *df, void *allocator)
static void qrhivk_releaseBuffer(const QRhiVulkan::DeferredReleaseEntry &e, void *allocator)
static VkAccessFlags toVkAccess(QRhiPassResourceTracker::TextureAccess access)
static VmaAllocator toVmaAllocator(QVkAllocator a)
static VkSamplerAddressMode toVkAddressMode(QRhiSampler::AddressMode m)
static constexpr bool isDepthTextureFormat(QRhiTexture::Format format)
static void fillVkStencilOpState(VkStencilOpState *dst, const QRhiGraphicsPipeline::StencilOpState &src)
static VkShaderStageFlags toVkShaderStageFlags(QRhiShaderResourceBinding::StageFlags stage)
static constexpr VkImageAspectFlags aspectMaskForTextureFormat(QRhiTexture::Format format)
static VkDescriptorType toVkDescriptorType(const QRhiShaderResourceBinding::Data *b)
static VkBlendFactor toVkBlendFactor(QRhiGraphicsPipeline::BlendFactor f)
static void fillDriverInfo(QRhiDriverInfo *info, const VkPhysicalDeviceProperties &physDevProperties)
static VkBlendOp toVkBlendOp(QRhiGraphicsPipeline::BlendOp op)
static void qrhivk_releaseRenderBuffer(const QRhiVulkan::DeferredReleaseEntry &e, VkDevice dev, QVulkanDeviceFunctions *df)
static VkFrontFace toVkFrontFace(QRhiGraphicsPipeline::FrontFace f)
void qrhivk_accumulateComputeResource(T *writtenResources, QRhiResource *resource, QRhiShaderResourceBinding::Type bindingType, int loadTypeVal, int storeTypeVal, int loadStoreTypeVal)
static VkFormat toVkTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
static VkCompareOp toVkCompareOp(QRhiGraphicsPipeline::CompareOp op)
static void fillRenderPassCreateInfo(VkRenderPassCreateInfo *rpInfo, VkSubpassDescription *subpassDesc, QVkRenderPassDescriptor *rpD)
static VkSamplerMipmapMode toVkMipmapMode(QRhiSampler::Filter f)
static void qrhivk_releaseSampler(const QRhiVulkan::DeferredReleaseEntry &e, VkDevice dev, QVulkanDeviceFunctions *df)
static constexpr bool isStencilTextureFormat(QRhiTexture::Format format)
static QVkRenderTargetData * maybeRenderTargetData(QVkCommandBuffer *cbD)
static QRhiPassResourceTracker::UsageState toPassTrackerUsageState(const QVkTexture::UsageState &texUsage)
static VmaAllocation toVmaAllocation(QVkAlloc a)
static void addToChain(T *head, void *entry)
static void addSelfDependency(QVkRenderPassDescriptor *rpD)
static VkShaderStageFlagBits toVkShaderStage(QRhiShaderStage::Type type)
static const int QVK_MAX_ACTIVE_TIMESTAMP_PAIRS
static const int QVK_DESC_SETS_PER_POOL
static const int QVK_FRAMES_IN_FLIGHT
bool prepare(VkRenderPassCreateInfo *rpInfo, int multiViewCount, bool multiViewCap)
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QVkBuffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
QVkAlloc allocations[QVK_FRAMES_IN_FLIGHT]
QVkAlloc stagingAllocations[QVK_FRAMES_IN_FLIGHT]
void endFullDynamicBufferUpdateForCurrentFrame() override
To be called when the entire contents of the buffer data has been updated in the memory block returne...
QRhiBuffer::NativeBuffer nativeBuffer() override
bool create() override
Creates the corresponding native graphics resources.
char * beginFullDynamicBufferUpdateForCurrentFrame() override
@ TransitionPassResources
@ DrawIndexedIndirectCount
uint currentSrbGeneration
int currentPassResTrackerIndex
uint currentPipelineGeneration
QVkGraphicsPipeline(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool create() override
Creates the corresponding native graphics resources.
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QVkRenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize, int sampleCount, Flags flags, QRhiTexture::Format backingFormatHint)
QRhiTexture::Format backingFormat() const override
bool create() override
Creates the corresponding native graphics resources.
QVkTexture * backingTexture
const QRhiNativeHandles * nativeHandles() override
void updateSerializedFormat()
bool hasDepthStencilResolve
~QVkRenderPassDescriptor()
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QVector< quint32 > serializedFormat() const override
QVkRenderPassDescriptor(QRhiImplementation *rhi)
bool isCompatible(const QRhiRenderPassDescriptor *other) const override
QVkRenderPassDescriptor * rp
static const int MAX_COLOR_ATTACHMENTS
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QVkSampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode, AddressMode u, AddressMode v, AddressMode w)
void updateResources(UpdateFlags flags) override
QVkShaderResourceBindings(QRhiImplementation *rhi)
bool create() override
Creates the corresponding resource binding set.
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
~QVkShaderResourceBindings()
bool createFrom(QRhiTexture *src) override
Sets up the shading rate map to use the texture src as the image containing the per-tile shading rate...
QVkShadingRateMap(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QSize pixelSize() const override
int sampleCount() const override
float devicePixelRatio() const override
~QVkSwapChainRenderTarget()
QVkSwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
@ ScImageUseTransferSource
QVkTextureRenderTarget(QRhiImplementation *rhi, const QRhiTextureRenderTargetDescription &desc, Flags flags)
~QVkTextureRenderTarget()
float devicePixelRatio() const override
bool create() override
Creates the corresponding native graphics resources.
int sampleCount() const override
QSize pixelSize() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() override
bool create() override
Creates the corresponding native graphics resources.
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
VkImageView perLevelImageViewForLoadStore(int level)
QVkAlloc stagingAllocations[QVK_FRAMES_IN_FLIGHT]
bool createFrom(NativeTexture src) override
Similar to create(), except that no new native textures are created.
void setNativeLayout(int layout) override
With some graphics APIs, such as Vulkan, integrating custom rendering code that uses the graphics API...
QVkTexture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, Flags flags)
NativeTexture nativeTexture() override
bool prepareCreate(QSize *adjustedSize=nullptr)