Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qrhivulkan.cpp
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qrhivulkan_p.h"
6#include <qpa/qplatformvulkaninstance.h>
7
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")
15QT_END_NAMESPACE
16#define VMA_ASSERT(expr) Q_ASSERT(expr)
17#ifdef QT_DEBUG
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__)
21#endif
22template<typename... Args>
23static void debugVmaLeak(const char *format, Args&&... args)
24{
25#ifndef QT_NO_DEBUG
26 // debug builds: just do it always
27 static bool leakCheck = true;
28#else
29 // release builds: opt-in
30 static bool leakCheck = QT_PREPEND_NAMESPACE(qEnvironmentVariableIntValue)("QT_RHI_LEAK_CHECK");
31#endif
32 if (leakCheck)
33 QT_PREPEND_NAMESPACE(qWarning)(QT_PREPEND_NAMESPACE(QRHI_LOG_VMA), format, std::forward<Args>(args)...);
34}
35#define VMA_LEAK_LOG_FORMAT(format, ...) debugVmaLeak(format, __VA_ARGS__)
36QT_WARNING_PUSH
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")
42#endif
43#include "vk_mem_alloc.h"
44QT_WARNING_POP
45
46#include <qmath.h>
47#include <QVulkanFunctions>
48#include <QtGui/qwindow.h>
49#include <private/qvulkandefaultinstance_p.h>
50
51#include <QtCore/q20memory.h>
52#include <QtCore/qendian.h>
53#include <limits>
54#include <optional>
55#include <utility>
56
57QT_BEGIN_NAMESPACE
58
59/*
60 Vulkan 1.0 backend. Provides a double-buffered swapchain that throttles the
61 rendering thread to vsync. Textures and "static" buffers are device local,
62 and a separate, host visible staging buffer is used to upload data to them.
63 "Dynamic" buffers are in host visible memory and are duplicated (since there
64 can be 2 frames in flight). This is handled transparently to the application.
65
66 Barriers are generated automatically for each render or compute pass, based
67 on the resources that are used in that pass (in QRhiShaderResourceBindings,
68 vertex inputs, etc.). This implies deferring the recording of the command
69 buffer since the barriers have to be placed at the right place (before the
70 pass), and that can only be done once we know all the things the pass does.
71
72 This in turn has implications for integrating external commands
73 (beginExternal() - direct Vulkan calls - endExternal()) because that is
74 incompatible with this approach by nature. Therefore we support another mode
75 of operation, where each render or compute pass uses one or more secondary
76 command buffers (recorded right away), with each beginExternal() leading to
77 closing the current secondary cb, creating a new secondary cb for the
78 external content, and then starting yet another one in endExternal() for
79 whatever comes afterwards in the pass. This way the primary command buffer
80 only has vkCmdExecuteCommand(s) within a renderpass instance
81 (Begin-EndRenderPass). (i.e. our only subpass is then
82 VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS instead of
83 VK_SUBPASS_CONTENTS_INLINE)
84
85 The command buffer management mode is decided on a per frame basis,
86 controlled by the ExternalContentsInPass flag of beginFrame().
87*/
88
89/*!
90 \class QRhiVulkanInitParams
91 \inmodule QtGuiPrivate
92 \inheaderfile rhi/qrhi.h
93 \since 6.6
94 \brief Vulkan specific initialization parameters.
95
96 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
97 for details.
98
99 A Vulkan-based QRhi needs at minimum a valid QVulkanInstance. It is up to
100 the user to ensure this is available and initialized. This is typically
101 done in main() similarly to the following:
102
103 \badcode
104 int main(int argc, char **argv)
105 {
106 ...
107
108 QVulkanInstance inst;
109 inst.setLayers({ "VK_LAYER_KHRONOS_validation" }); // for debugging only, not for release builds
110 inst.setExtensions(QRhiVulkanInitParams::preferredInstanceExtensions());
111 if (!inst.create())
112 qFatal("Vulkan not available");
113
114 ...
115 }
116 \endcode
117
118 This example enables the
119 \l{https://github.com/KhronosGroup/Vulkan-ValidationLayers}{Vulkan
120 validation layers}, when they are available, and also enables the
121 instance-level extensions QRhi reports as desirable (such as,
122 VK_KHR_get_physical_device_properties2), as long as they are supported by
123 the Vulkan implementation at run time.
124
125 The former is optional, and is useful during the development phase
126 QVulkanInstance conveniently redirects messages and warnings to qDebug.
127 Avoid enabling it in production builds, however. The latter is strongly
128 recommended, and is important in order to make certain features functional
129 (for example, QRhi::CustomInstanceStepRate).
130
131 Once this is done, a Vulkan-based QRhi can be created by passing the
132 instance and a QWindow with its surface type set to
133 QSurface::VulkanSurface:
134
135 \badcode
136 QRhiVulkanInitParams params;
137 params.inst = vulkanInstance;
138 params.window = window;
139 rhi = QRhi::create(QRhi::Vulkan, &params);
140 \endcode
141
142 The window is optional and can be omitted. This is not recommended however
143 because there is then no way to ensure presenting is supported while
144 choosing a graphics queue.
145
146 \note Even when a window is specified, QRhiSwapChain objects can be created
147 for other windows as well, as long as they all have their
148 QWindow::surfaceType() set to QSurface::VulkanSurface.
149
150 To request additional extensions to be enabled on the Vulkan device, list them
151 in deviceExtensions. This can be relevant when integrating with native Vulkan
152 rendering code.
153
154 It is expected that the backend's desired list of instance extensions will
155 be queried by calling the static function preferredInstanceExtensions()
156 before initializing a QVulkanInstance. The returned list can be safely
157 passed to QVulkanInstance::setExtensions() as-is, because unsupported
158 extensions are filtered out automatically. If this is not done, certain
159 features, such as QRhi::CustomInstanceStepRate may be reported as
160 unsupported even when the Vulkan implementation on the system has support
161 for the relevant functionality.
162
163 For full functionality the QVulkanInstance needs to have API 1.1 enabled,
164 when available. This means calling QVulkanInstance::setApiVersion() with
165 1.1 or higher whenever QVulkanInstance::supportedApiVersion() reports that
166 at least Vulkan 1.1 is supported. If this is not done, certain features,
167 such as QRhi::RenderTo3DTextureSlice may be reported as unsupported even
168 when the Vulkan implementation on the system supports Vulkan 1.1 or newer.
169
170 \section2 Working with existing Vulkan devices
171
172 When interoperating with another graphics engine, it may be necessary to
173 get a QRhi instance that uses the same Vulkan device. This can be achieved
174 by passing a pointer to a QRhiVulkanNativeHandles to QRhi::create().
175
176 The physical device must always be set to a non-null value. If the
177 intention is to just specify a physical device, but leave the rest of the
178 VkDevice and queue creation to QRhi, then no other members need to be
179 filled out in the struct. For example, this is the case when working with
180 OpenXR.
181
182 To adopt an existing \c VkDevice, the device field must be set to a
183 non-null value as well. In addition, the graphics queue family index is
184 required. The queue index is optional, as the default of 0 is often
185 suitable.
186
187 Optionally, an existing command pool object can be specified as well. Also
188 optionally, vmemAllocator can be used to share the same
189 \l{https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator}{Vulkan
190 memory allocator} between two QRhi instances.
191
192 The QRhi does not take ownership of any of the external objects.
193
194 Applications are encouraged to query the list of desired device extensions
195 by calling the static function preferredExtensionsForImportedDevice(), and
196 enable them on the VkDevice. Otherwise certain QRhi features may not be
197 available.
198 */
199
200/*!
201 \variable QRhiVulkanInitParams::inst
202
203 The QVulkanInstance that has already been successfully
204 \l{QVulkanInstance::create()}{created}, required.
205*/
206
207/*!
208 \variable QRhiVulkanInitParams::window
209
210 Optional, but recommended when targeting a QWindow.
211*/
212
213/*!
214 \variable QRhiVulkanInitParams::deviceExtensions
215
216 Optional, empty by default. The list of Vulkan device extensions to enable.
217 Unsupported extensions are ignored gracefully.
218*/
219
220/*!
221 \class QRhiVulkanNativeHandles
222 \inmodule QtGuiPrivate
223 \inheaderfile rhi/qrhi.h
224 \since 6.6
225 \brief Collects device, queue, and other Vulkan objects that are used by the QRhi.
226
227 \note Ownership of the Vulkan objects is never transferred.
228
229 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
230 for details.
231 */
232
233/*!
234 \variable QRhiVulkanNativeHandles::physDev
235
236 When different from \nullptr, specifies the Vulkan physical device to use.
237*/
238
239/*!
240 \variable QRhiVulkanNativeHandles::dev
241
242 When wanting to import not just a physical device, but also use an already
243 existing VkDevice, set this and the graphics queue index and family index.
244*/
245
246/*!
247 \variable QRhiVulkanNativeHandles::gfxQueueFamilyIdx
248
249 Graphics queue family index.
250*/
251
252/*!
253 \variable QRhiVulkanNativeHandles::gfxQueueIdx
254
255 Graphics queue index.
256*/
257
258/*!
259 \variable QRhiVulkanNativeHandles::gfxQueueFlags
260 \since 6.13
261
262 Graphics queue flags (VkDeviceQueueCreateFlags) or 0. Setting this to a
263 non-zero value will imply using vkGetDeviceQueue2 instead of
264 vkGetDeviceQueue.
265
266 \note This value is ignored when running with Vulkan 1.0. Non-zero queue
267 flags are introduced in Vulkan 1.1.
268*/
269
270/*!
271 \variable QRhiVulkanNativeHandles::vmemAllocator
272
273 Relevant only when importing an existing memory allocator object,
274 leave it set to \nullptr otherwise.
275*/
276
277/*!
278 \variable QRhiVulkanNativeHandles::gfxQueue
279
280 Output only, not used by QRhi::create(), only set by the
281 QRhi::nativeHandles() accessor. The graphics VkQueue used by the QRhi.
282*/
283
284/*!
285 \variable QRhiVulkanNativeHandles::inst
286
287 Output only, not used by QRhi::create(), only set by the
288 QRhi::nativeHandles() accessor. The QVulkanInstance used by the QRhi.
289*/
290
291/*!
292 \class QRhiVulkanCommandBufferNativeHandles
293 \inmodule QtGuiPrivate
294 \inheaderfile rhi/qrhi.h
295 \since 6.6
296 \brief Holds the Vulkan command buffer object that is backing a QRhiCommandBuffer.
297
298 \note The Vulkan command buffer object is only guaranteed to be valid, and
299 in recording state, while recording a frame. That is, between a
300 \l{QRhi::beginFrame()}{beginFrame()} - \l{QRhi::endFrame()}{endFrame()} or
301 \l{QRhi::beginOffscreenFrame()}{beginOffscreenFrame()} -
302 \l{QRhi::endOffscreenFrame()}{endOffscreenFrame()} pair.
303
304 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
305 for details.
306 */
307
308/*!
309 \variable QRhiVulkanCommandBufferNativeHandles::commandBuffer
310
311 The VkCommandBuffer object.
312*/
313
314/*!
315 \class QRhiVulkanRenderPassNativeHandles
316 \inmodule QtGuiPrivate
317 \inheaderfile rhi/qrhi.h
318 \since 6.6
319 \brief Holds the Vulkan render pass object backing a QRhiRenderPassDescriptor.
320
321 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
322 for details.
323 */
324
325/*!
326 \variable QRhiVulkanRenderPassNativeHandles::renderPass
327
328 The VkRenderPass object.
329*/
330
331/*!
332 \class QRhiVulkanQueueSubmitParams
333 \inmodule QtGui
334 \since 6.9
335 \brief References additional Vulkan API objects that get passed to \c vkQueueSubmit().
336
337 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
338 for details.
339*/
340
341/*!
342 \variable QRhiVulkanQueueSubmitParams::waitSemaphoreCount
343
344 See
345 \l{https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkSubmitInfo.html}{VkSubmitInfo}
346 for details.
347*/
348
349/*!
350 \variable QRhiVulkanQueueSubmitParams::waitSemaphores
351
352 See
353 \l{https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkSubmitInfo.html}{VkSubmitInfo}
354 for details.
355*/
356
357/*!
358 \variable QRhiVulkanQueueSubmitParams::signalSemaphoreCount
359
360 See
361 \l{https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkSubmitInfo.html}{VkSubmitInfo}
362 for details.
363*/
364
365/*!
366 \variable QRhiVulkanQueueSubmitParams::signalSemaphores
367
368 See
369 \l{https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkSubmitInfo.html}{VkSubmitInfo}
370 for details.
371*/
372
373/*!
374 \variable QRhiVulkanQueueSubmitParams::presentWaitSemaphoreCount
375
376 When non-zero, this applies to the next \c vkQueuePresentKHR() call. See
377 \l{https://registry.khronos.org/VulkanSC/specs/1.0-extensions/man/html/VkPresentInfoKHR.html}{VkPresentInfoKHR}
378 for details.
379*/
380
381/*!
382 \variable QRhiVulkanQueueSubmitParams::presentWaitSemaphores
383
384 See
385 \l{https://registry.khronos.org/VulkanSC/specs/1.0-extensions/man/html/VkPresentInfoKHR.html}{VkPresentInfoKHR}
386 for details.
387 */
388
389#ifdef VK_VERSION_1_1
390// Cannot rely on VK_ENABLE_BETA_EXTENSIONS. Declare what we need ourselves.
391// The layout is fixed by the extension specification.
392struct QVkPhysicalDevicePortabilitySubsetFeatures
393{
394 VkStructureType sType;
395 void *pNext;
396 VkBool32 constantAlphaColorBlendFactors;
397 VkBool32 events;
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;
411};
412
413static const VkStructureType QVK_STRUCTURE_TYPE_PDPSF = VkStructureType(1000163000);
414#endif
415
416template <class Int>
417inline Int aligned(Int v, Int byteAlign)
418{
419 return (v + byteAlign - 1) & ~(byteAlign - 1);
420}
421
423
424static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL wrap_vkGetInstanceProcAddr(VkInstance, const char *pName)
425{
426 return globalVulkanInstance->getInstanceProcAddr(pName);
427}
428
429static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL wrap_vkGetDeviceProcAddr(VkDevice device, const char *pName)
430{
431 return globalVulkanInstance->functions()->vkGetDeviceProcAddr(device, pName);
432}
433
435{
436 return reinterpret_cast<VmaAllocation>(a);
437}
438
440{
441 return reinterpret_cast<VmaAllocator>(a);
442}
443
444/*!
445 \return the list of instance extensions that are expected to be enabled on
446 the QVulkanInstance that is used for the Vulkan-based QRhi.
447
448 The returned list can be safely passed to QVulkanInstance::setExtensions()
449 as-is, because unsupported extensions are filtered out automatically.
450 */
451QByteArrayList QRhiVulkanInitParams::preferredInstanceExtensions()
452{
453 return {
454 QByteArrayLiteral("VK_KHR_get_physical_device_properties2"),
455 // to silence validation when e.g. on Wayland a surface format's colorspace is VK_COLOR_SPACE_PASS_THROUGH_EXT
456 QByteArrayLiteral("VK_EXT_swapchain_colorspace")
457 };
458}
459
460/*!
461 \return the list of device extensions that are expected to be enabled on the
462 \c VkDevice when creating a Vulkan-based QRhi with an externally created
463 \c VkDevice object.
464 */
465QByteArrayList QRhiVulkanInitParams::preferredExtensionsForImportedDevice()
466{
467 return {
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")
473 };
474}
475
476QRhiVulkan::QRhiVulkan(QRhiVulkanInitParams *params, QRhiVulkanNativeHandles *importParams)
477 : ofr(this)
478{
479 inst = params->inst;
480 if (!inst) {
481 // This builds on the fact that Qt Quick also uses QVulkanDefaultInstance. While
482 // this way we can support a null inst, it has consequences, so only do it with a
483 // warning. (e.g. if Qt Quick initializes afterwards, its attempt to set flags on
484 // QVulkanDefaultInstance will be futile)
485 qWarning("QRhi for Vulkan attempted to be initialized without a QVulkanInstance; using QVulkanDefaultInstance.");
486 inst = QVulkanDefaultInstance::instance();
487 }
488
489 maybeWindow = params->window; // may be null
490 requestedDeviceExtensions = params->deviceExtensions;
491
492 if (importParams) {
493 physDev = importParams->physDev;
494 dev = importParams->dev;
495 if (dev && physDev) {
496 importedDevice = true;
497 gfxQueueFamilyIdx = importParams->gfxQueueFamilyIdx;
498 gfxQueueIdx = importParams->gfxQueueIdx;
499 gfxQueueFlags = importParams->gfxQueueFlags;
500 // gfxQueue is output only, no point in accepting it as input
501 if (importParams->vmemAllocator) {
502 importedAllocator = true;
503 allocator = importParams->vmemAllocator;
504 }
505 }
506 }
507}
508
509static bool qvk_debug_filter(QVulkanInstance::DebugMessageSeverityFlags severity,
510 QVulkanInstance::DebugMessageTypeFlags type,
511 const void *callbackData)
512{
513 Q_UNUSED(severity);
514 Q_UNUSED(type);
515#ifdef VK_EXT_debug_utils
516 const VkDebugUtilsMessengerCallbackDataEXT *d = static_cast<const VkDebugUtilsMessengerCallbackDataEXT *>(callbackData);
517
518 // Filter out certain misleading validation layer messages, as per
519 // VulkanMemoryAllocator documentation.
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"))
522 {
523 return true;
524 }
525
526 // In certain cases allocateDescriptorSet() will attempt to allocate from a
527 // pool that does not have enough descriptors of a certain type. This makes
528 // the validation layer shout. However, this is not an error since we will
529 // then move on to another pool. If there is a real error, a qWarning
530 // message is shown by allocateDescriptorSet(), so the validation warning
531 // does not have any value and is just noise.
532 if (strstr(d->pMessage, "VUID-VkDescriptorSetAllocateInfo-descriptorPool-00307"))
533 return true;
534#else
535 Q_UNUSED(callbackData);
536#endif
537 return false;
538}
539
540static inline QRhiDriverInfo::DeviceType toRhiDeviceType(VkPhysicalDeviceType type)
541{
542 switch (type) {
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;
553 default:
554 return QRhiDriverInfo::UnknownDevice;
555 }
556}
557
558static inline void fillDriverInfo(QRhiDriverInfo *info, const VkPhysicalDeviceProperties &physDevProperties)
559{
560 info->deviceName = QByteArray(physDevProperties.deviceName);
561 info->deviceId = physDevProperties.deviceID;
562 info->vendorId = physDevProperties.vendorID;
563 info->deviceType = toRhiDeviceType(physDevProperties.deviceType);
564}
565
566template<typename T>
567static inline void addToChain(T *head, void *entry)
568{
569 VkBaseOutStructure *s = reinterpret_cast<VkBaseOutStructure *>(head);
570 for ( ; ; ) {
571 VkBaseOutStructure *next = reinterpret_cast<VkBaseOutStructure *>(s->pNext);
572 if (next)
573 s = next;
574 else
575 break;
576 }
577 s->pNext = reinterpret_cast<VkBaseOutStructure *>(entry);
578}
579
580bool QRhiVulkan::create(QRhi::Flags flags)
581{
582 if (!inst || !inst->isValid()) {
583 qWarning("Vulkan instance is not valid");
584 return false;
585 }
586
587 rhiFlags = flags;
588 qCDebug(QRHI_LOG_INFO, "Initializing QRhi Vulkan backend %p with flags %d", this, int(rhiFlags));
589
590 globalVulkanInstance = inst; // used for function resolving in vkmemalloc callbacks
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);
597 }
598
599 caps = {};
600 caps.debugUtils = inst->extensions().contains(QByteArrayLiteral("VK_EXT_debug_utils"));
601
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());
608 };
609
610 // Choose a physical device, unless one was provided in importParams.
611 if (!physDev) {
612 uint32_t physDevCount = 0;
613 f->vkEnumeratePhysicalDevices(inst->vkInstance(), &physDevCount, nullptr);
614 if (!physDevCount) {
615 qWarning("No physical devices");
616 return false;
617 }
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);
622 return false;
623 }
624
625 int physDevIndex = -1;
626 int requestedPhysDevIndex = -1;
627 if (qEnvironmentVariableIsSet("QT_VK_PHYSICAL_DEVICE_INDEX"))
628 requestedPhysDevIndex = qEnvironmentVariableIntValue("QT_VK_PHYSICAL_DEVICE_INDEX");
629
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;
635 break;
636 }
637 }
638 }
639
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;
645 break;
646 }
647 }
648 }
649
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)",
653 i,
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))) {
665 physDevIndex = i;
666 qCDebug(QRHI_LOG_INFO, " using this physical device");
667 }
668 }
669
670 if (physDevIndex < 0) {
671 qWarning("No matching physical device");
672 return false;
673 }
674 physDev = physDevs[physDevIndex];
675 f->vkGetPhysicalDeviceProperties(physDev, &physDevProperties);
676 } else {
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);
689 }
690
691 caps.apiVersion = inst->apiVersion();
692
693 // Check the physical device API version against the instance API version,
694 // they do not have to match, which means whatever version was set in the
695 // QVulkanInstance may not be legally used with a given device if the
696 // physical device has a lower version.
697 const QVersionNumber physDevApiVersion(VK_VERSION_MAJOR(physDevProperties.apiVersion),
698 VK_VERSION_MINOR(physDevProperties.apiVersion)); // patch version left out intentionally
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;
704 }
705
706 fillDriverInfo(&driverInfoStruct, physDevProperties);
707
708 QVulkanInfoVector<QVulkanExtension> devExts;
709 uint32_t devExtCount = 0;
710 f->vkEnumerateDeviceExtensionProperties(physDev, nullptr, &devExtCount, nullptr);
711 if (devExtCount) {
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 });
716 }
717 qCDebug(QRHI_LOG_INFO, "%d device extensions available", int(devExts.size()));
718
719 const bool hasPhysDevProp2 = inst->extensions().contains(QByteArrayLiteral("VK_KHR_get_physical_device_properties2"));
720
721 bool featuresQueried = false;
722#ifdef VK_VERSION_1_1
723 VkPhysicalDeviceFeatures2 physDevFeaturesChainable = {};
724 physDevFeaturesChainable.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
725
726 // Extensions (that are really extensions in 1.1-1.3, not core)
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);
732#endif
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);
738#endif
739
740 QVkPhysicalDevicePortabilitySubsetFeatures portabilitySubsetFeatures = {};
741 portabilitySubsetFeatures.sType = QVK_STRUCTURE_TYPE_PDPSF;
742 if (hasPhysDevProp2 && devExts.contains(QByteArrayLiteral("VK_KHR_portability_subset")))
743 addToChain(&physDevFeaturesChainable, &portabilitySubsetFeatures);
744#endif // VK_VERSION_1_1
745
746 // Vulkan >=1.2 headers at build time, >=1.2 implementation at run time
747#ifdef VK_VERSION_1_2
748 if (!featuresQueried) {
749 // Vulkan11Features, Vulkan12Features, etc. are only in Vulkan 1.2 and newer.
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;
755#ifdef VK_VERSION_1_3
756 physDevFeatures13 = {};
757 physDevFeatures13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
758#ifdef VK_VERSION_1_4
759 physDevFeatures14 = {};
760 physDevFeatures14.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_4_FEATURES;
761#endif // VK_VERSION_1_4
762#endif // VK_VERSION_1_3
763 addToChain(&physDevFeaturesChainable, &physDevFeatures11IfApi12OrNewer);
764 physDevFeatures11IfApi12OrNewer.pNext = &physDevFeatures12;
765#ifdef VK_VERSION_1_3
766 if (caps.apiVersion >= QVersionNumber(1, 3))
767 physDevFeatures12.pNext = &physDevFeatures13;
768#ifdef VK_VERSION_1_4
769 if (caps.apiVersion >= QVersionNumber(1, 4))
770 physDevFeatures13.pNext = &physDevFeatures14;
771#endif // VK_VERSION_1_4
772#endif // VK_VERSION_1_3
773 f->vkGetPhysicalDeviceFeatures2(physDev, &physDevFeaturesChainable);
774 memcpy(&physDevFeatures, &physDevFeaturesChainable.features, sizeof(VkPhysicalDeviceFeatures));
775 featuresQueried = true;
776 }
777 }
778#endif // VK_VERSION_1_2
779
780 // Vulkan >=1.1 headers at build time, 1.1 implementation at run time
781#ifdef VK_VERSION_1_1
782 if (!featuresQueried) {
783 // Vulkan versioning nightmares: if the runtime API version is 1.1,
784 // there is no Vulkan11Features (introduced in 1.2+, the headers might
785 // have the types and structs, but the Vulkan implementation version at
786 // run time is what matters). But there are individual feature structs.
787 // For multiview, it is important to get this right since at the time of
788 // writing Quest 3 Android is a Vulkan 1.1 implementation at run time on
789 // the headset.
790 if (caps.apiVersion == QVersionNumber(1, 1)) {
791 {
792 multiviewFeaturesIfApi11 = {};
793 multiviewFeaturesIfApi11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES;
794 addToChain(&physDevFeaturesChainable, &multiviewFeaturesIfApi11);
795 }
796 {
797 shaderDrawParametersFeaturesIfApi11 = {};
798 shaderDrawParametersFeaturesIfApi11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES;
799 addToChain(&physDevFeaturesChainable, &shaderDrawParametersFeaturesIfApi11);
800 }
801 f->vkGetPhysicalDeviceFeatures2(physDev, &physDevFeaturesChainable);
802 memcpy(&physDevFeatures, &physDevFeaturesChainable.features, sizeof(VkPhysicalDeviceFeatures));
803 featuresQueried = true;
804 }
805 }
806#endif
807
808 if (!featuresQueried) {
809 // If the API version at run time is 1.0 (or we are building with
810 // ancient 1.0 headers), then do the Vulkan 1.0 query.
811 f->vkGetPhysicalDeviceFeatures(physDev, &physDevFeatures);
812 featuresQueried = true;
813 }
814
815 // Choose queue and create device, unless the device was specified in importParams.
816 if (!importedDevice) {
817 // We only support combined graphics+present queues. When it comes to
818 // compute, only combined graphics+compute queue is used, compute gets
819 // disabled otherwise.
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)))
830 {
831 if (queueFamilyProps[i].queueFlags & VK_QUEUE_COMPUTE_BIT)
832 gfxQueueFamilyIdxOpt = i;
833 else if (!computelessGfxQueueCandidateIdxOpt.has_value())
834 computelessGfxQueueCandidateIdxOpt = i;
835 }
836 }
837 if (gfxQueueFamilyIdxOpt.has_value()) {
838 gfxQueueFamilyIdx = gfxQueueFamilyIdxOpt.value();
839 } else {
840 if (computelessGfxQueueCandidateIdxOpt.has_value()) {
841 gfxQueueFamilyIdx = computelessGfxQueueCandidateIdxOpt.value();
842 } else {
843 qWarning("No graphics (or no graphics+present) queue family found");
844 return false;
845 }
846 }
847
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;
854
855 QList<const char *> requestedDevExts;
856 requestedDevExts.append("VK_KHR_swapchain");
857
858 if (devExts.contains(QByteArrayLiteral("VK_KHR_portability_subset"))) {
859 if (hasPhysDevProp2) {
860 requestedDevExts.append("VK_KHR_portability_subset");
861 } else {
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. "
864 "Expect problems.");
865 }
866 }
867
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;
873 }
874 }
875#endif
876
877#ifdef VK_KHR_create_renderpass2
878 if (devExts.contains(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) {
879 // VK_KHR_create_renderpass2 depends on multiview and maintenance2. Both are
880 // core in Vulkan 1.1, but with a 1.0 instance they have to be requested
881 // explicitly, otherwise enabling create_renderpass2 is invalid.
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"));
887 if (canEnable) {
888 requestedDevExts.append("VK_KHR_multiview");
889 requestedDevExts.append("VK_KHR_maintenance2");
890 }
891 }
892 if (canEnable) {
893 requestedDevExts.append(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME);
894 caps.renderPass2KHR = true;
895 }
896 }
897#endif
898
899#ifdef VK_KHR_depth_stencil_resolve
900 {
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;
905 }
906 }
907#endif
908
909#ifdef VK_KHR_fragment_shading_rate
910 {
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);
914 }
915#endif
916
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;
921 }
922#endif
923
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());
928 } else {
929 qWarning("Device extension %s requested in QRhiVulkanInitParams is not supported",
930 ext.constData());
931 }
932 }
933 }
934
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());
940 } else {
941 qWarning("Device extension %s requested in QT_VULKAN_DEVICE_EXTENSIONS is not supported",
942 ext.constData());
943 }
944 }
945 }
946
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);
951 }
952
953 VkDeviceCreateInfo devInfo = {};
954 devInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
955 devInfo.queueCreateInfoCount = 1;
956 devInfo.pQueueCreateInfos = &queueInfo;
957 // Device layers are deprecated, the spec requires enabledLayerCount to be 0.
958 devInfo.enabledLayerCount = 0;
959 devInfo.ppEnabledLayerNames = nullptr;
960 devInfo.enabledExtensionCount = uint32_t(requestedDevExts.size());
961 devInfo.ppEnabledExtensionNames = requestedDevExts.constData();
962
963 // Enable all features that are reported as supported, except
964 // robustness because that potentially affects performance.
965 //
966 // Enabling all features mainly serves third-party renderers that may
967 // use the VkDevice created here. For the record, the backend here
968 // optionally relies on the following features, meaning just for our
969 // (QRhi/Quick/Quick 3D) purposes it would be sufficient to
970 // enable-if-supported only the following:
971 //
972 // wideLines, largePoints, fillModeNonSolid,
973 // tessellationShader, geometryShader
974 // textureCompressionETC2, textureCompressionASTC_LDR, textureCompressionBC
975
976#ifdef VK_VERSION_1_1
977 physDevFeaturesChainable.features.robustBufferAccess = VK_FALSE;
978#endif
979#ifdef VK_VERSION_1_3
980 physDevFeatures13.robustImageAccess = VK_FALSE;
981#endif
982
983#ifdef VK_VERSION_1_1
984 if (caps.apiVersion >= QVersionNumber(1, 1)) {
985 // For a >=1.2 implementation at run time, this will enable all
986 // (1.0-1.4) features reported as supported, except the ones we turn
987 // off explicitly above. (+extensions) For a 1.1 implementation at
988 // run time, this only enables the 1.0 and multiview features (+any
989 // extensions) reported as supported. We will not be bothering with
990 // the Vulkan 1.1 individual feature struct nonsense.
991 devInfo.pNext = &physDevFeaturesChainable;
992 } else
993#endif
994 {
995 physDevFeatures.robustBufferAccess = VK_FALSE;
996 devInfo.pEnabledFeatures = &physDevFeatures;
997 }
998
999 VkResult err = f->vkCreateDevice(physDev, &devInfo, nullptr, &dev);
1000 if (err != VK_SUCCESS) {
1001 qWarning("Failed to create device: %d", err);
1002 return false;
1003 }
1004 } else {
1005 qCDebug(QRHI_LOG_INFO, "Using imported device %p", dev);
1006
1007 // Here we have no way to tell if the extensions got enabled or not.
1008 // Pretend it's all there and supported. If getProcAddress fails, we'll
1009 // handle that gracefully.
1010 caps.deviceFault = true;
1011 caps.vertexAttribDivisor = true;
1012 caps.renderPass2KHR = true;
1013 caps.depthStencilResolveKHR = true;
1014 }
1015
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"));
1022
1023 df = inst->deviceFunctions(dev);
1024
1025 VkCommandPoolCreateInfo poolInfo = {};
1026 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1027 poolInfo.queueFamilyIndex = gfxQueueFamilyIdx;
1028 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
1029 VkResult err = df->vkCreateCommandPool(dev, &poolInfo, nullptr, &cmdPool[i]);
1030 if (err != VK_SUCCESS) {
1031 qWarning("Failed to create command pool: %d", err);
1032 return false;
1033 }
1034 }
1035
1036 qCDebug(QRHI_LOG_INFO, "Using queue family index %u and queue index %u",
1037 gfxQueueFamilyIdx, gfxQueueIdx);
1038
1039#if VK_VERSION_1_1
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);
1047 } else
1048#endif
1049 df->vkGetDeviceQueue(dev, gfxQueueFamilyIdx, gfxQueueIdx, &gfxQueue);
1050
1051 if (queueFamilyProps.isEmpty())
1052 queryQueueFamilyProps();
1053
1054 caps.compute = (queueFamilyProps[gfxQueueFamilyIdx].queueFlags & VK_QUEUE_COMPUTE_BIT) != 0;
1055 timestampValidBits = queueFamilyProps[gfxQueueFamilyIdx].timestampValidBits;
1056
1057 ubufAlign = physDevProperties.limits.minUniformBufferOffsetAlignment;
1058 // helps little with an optimal offset of 1 (on some drivers) when the spec
1059 // elsewhere states that the minimum bufferOffset is 4...
1060 texbufAlign = qMax<VkDeviceSize>(4, physDevProperties.limits.optimalBufferCopyOffsetAlignment);
1061
1062 caps.depthClamp = physDevFeatures.depthClamp;
1063
1064 caps.wideLines = physDevFeatures.wideLines;
1065
1066 caps.texture3DSliceAs2D = caps.apiVersion >= QVersionNumber(1, 1);
1067
1068 caps.tessellation = physDevFeatures.tessellationShader;
1069 caps.geometryShader = physDevFeatures.geometryShader;
1070
1071 caps.nonFillPolygonMode = physDevFeatures.fillModeNonSolid;
1072
1073 caps.drawIndirectMulti = physDevFeatures.multiDrawIndirect;
1074
1075 caps.dualSrcBlend = physDevFeatures.dualSrcBlend;
1076 caps.drawIndirectFirstInstance = physDevFeatures.drawIndirectFirstInstance;
1077
1078#ifdef VK_VERSION_1_2
1079 if (caps.apiVersion >= QVersionNumber(1, 2)) {
1080 caps.multiView = physDevFeatures11IfApi12OrNewer.multiview;
1081 caps.shaderDrawParameters = physDevFeatures11IfApi12OrNewer.shaderDrawParameters;
1082 // maxDrawCount must be 0 or 1 without multiDrawIndirect, and a
1083 // device-side count cannot be worked around by looping.
1084 caps.drawIndirectCount = physDevFeatures12.drawIndirectCount && caps.drawIndirectMulti;
1085 }
1086#endif
1087
1088#ifdef VK_VERSION_1_1
1089 if (caps.apiVersion == QVersionNumber(1, 1)) {
1090 caps.multiView = multiviewFeaturesIfApi11.multiview;
1091 caps.shaderDrawParameters = shaderDrawParametersFeaturesIfApi11.shaderDrawParameters;
1092 }
1093#endif
1094
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);
1108 // If it's non-square, there's nothing we can do since it is not compatible with other APIs (D3D12) then.
1109 }
1110 if (caps.perDrawShadingRate) {
1111 PFN_vkGetPhysicalDeviceFragmentShadingRatesKHR vkGetPhysicalDeviceFragmentShadingRatesKHR =
1112 reinterpret_cast<PFN_vkGetPhysicalDeviceFragmentShadingRatesKHR>(
1113 inst->getInstanceProcAddr("vkGetPhysicalDeviceFragmentShadingRatesKHR"));
1114 if (vkGetPhysicalDeviceFragmentShadingRatesKHR) {
1115 uint32_t count = 0;
1116 vkGetPhysicalDeviceFragmentShadingRatesKHR(physDev, &count, nullptr);
1117 fragmentShadingRates.resize(count);
1118 for (VkPhysicalDeviceFragmentShadingRateKHR &s : fragmentShadingRates) {
1119 s = {};
1120 s.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_KHR;
1121 }
1122 vkGetPhysicalDeviceFragmentShadingRatesKHR(physDev, &count, fragmentShadingRates.data());
1123 }
1124 vkCmdSetFragmentShadingRateKHR = reinterpret_cast<PFN_vkCmdSetFragmentShadingRateKHR>(
1125 f->vkGetDeviceProcAddr(dev, "vkCmdSetFragmentShadingRateKHR"));
1126 }
1127 }
1128#endif
1129
1130 // With Vulkan 1.2 renderpass2 and depth_stencil_resolve are core, but we
1131 // have to support the case of 1.1 + extensions, in particular for the Quest
1132 // 3 (Android, Vulkan 1.1 at the time of writing). Therefore, always rely on
1133 // the KHR extension for now.
1134#ifdef VK_KHR_create_renderpass2
1135 if (caps.renderPass2KHR) {
1136 vkCreateRenderPass2KHR = reinterpret_cast<PFN_vkCreateRenderPass2KHR>(f->vkGetDeviceProcAddr(dev, "vkCreateRenderPass2KHR"));
1137 if (!vkCreateRenderPass2KHR) // handle it gracefully, the caps flag may be incorrect when using an imported VkDevice
1138 caps.renderPass2KHR = false;
1139 }
1140#endif
1141
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;
1151 }
1152 }
1153#endif
1154
1155 // On Windows, figure out the DXGI adapter LUID.
1156#ifdef Q_OS_WIN
1157 adapterLuidValid = false;
1158 adapterLuid = {};
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);
1174 }
1175 }
1176#endif
1177#endif
1178
1179 if (!importedAllocator) {
1180 VmaVulkanFunctions funcs = {};
1181 funcs.vkGetInstanceProcAddr = wrap_vkGetInstanceProcAddr;
1182 funcs.vkGetDeviceProcAddr = wrap_vkGetDeviceProcAddr;
1183
1184 VmaAllocatorCreateInfo allocatorInfo = {};
1185 // A QRhi is supposed to be used from one single thread only. Disable
1186 // the allocator's own mutexes. This gives a performance boost.
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();
1192
1193 // Logic would dictate setting allocatorInfo.vulkanApiVersion to caps.apiVersion.
1194 // However, VMA has asserts to test if the header version Qt was built with is
1195 // older than the runtime version. This is nice, but a bit unnecessary (in Qt we'd
1196 // rather prefer losing the affected features automatically, and perhaps printing
1197 // a warning, instead of aborting the application). Restrict the runtime version
1198 // passed in based on the preprocessor macro to keep VMA happy.
1199#ifdef VK_VERSION_1_4
1200 if (caps.apiVersion >= QVersionNumber(1, 4))
1201 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_4;
1202 else
1203#endif
1204#ifdef VK_VERSION_1_3
1205 if (caps.apiVersion >= QVersionNumber(1, 3))
1206 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_3;
1207 else
1208#endif
1209#ifdef VK_VERSION_1_2
1210 if (caps.apiVersion >= QVersionNumber(1, 2))
1211 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_2;
1212 else
1213#endif
1214#ifdef VK_VERSION_1_1
1215 if (caps.apiVersion >= QVersionNumber(1, 1))
1216 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_1;
1217 else
1218#endif
1219#ifdef VK_VERSION_1_0
1220 allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_0;
1221#endif
1222
1223 VmaAllocator vmaallocator;
1224 VkResult err = vmaCreateAllocator(&allocatorInfo, &vmaallocator);
1225 if (err != VK_SUCCESS) {
1226 qWarning("Failed to create allocator: %d", err);
1227 return false;
1228 }
1229 allocator = vmaallocator;
1230 }
1231
1232 inst->installDebugOutputFilter(qvk_debug_filter);
1233
1234 VkDescriptorPool pool;
1235 VkResult err = createDescriptorPool(&pool);
1236 if (err == VK_SUCCESS)
1237 descriptorPools.append(pool);
1238 else
1239 qWarning("Failed to create initial descriptor pool: %d", err);
1240
1241 VkQueryPoolCreateInfo timestampQueryPoolInfo = {};
1242 timestampQueryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
1243 timestampQueryPoolInfo.queryType = VK_QUERY_TYPE_TIMESTAMP;
1244 timestampQueryPoolInfo.queryCount = QVK_MAX_ACTIVE_TIMESTAMP_PAIRS * 2;
1245 err = df->vkCreateQueryPool(dev, &timestampQueryPoolInfo, nullptr, &timestampQueryPool);
1246 if (err != VK_SUCCESS) {
1247 qWarning("Failed to create timestamp query pool: %d", err);
1248 return false;
1249 }
1250 timestampQueryPoolMap.resize(QVK_MAX_ACTIVE_TIMESTAMP_PAIRS); // 1 bit per pair
1251 timestampQueryPoolMap.fill(false);
1252
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"));
1259 }
1260#endif
1261
1262#ifdef VK_EXT_device_fault
1263 if (caps.deviceFault) {
1264 vkGetDeviceFaultInfoEXT = reinterpret_cast<PFN_vkGetDeviceFaultInfoEXT>(f->vkGetDeviceProcAddr(dev, "vkGetDeviceFaultInfoEXT"));
1265 }
1266#endif
1267
1268 deviceLost = false;
1269
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;
1278
1279 return true;
1280}
1281
1283{
1284 if (!df)
1285 return;
1286
1287 if (!deviceLost)
1288 df->vkQueueWaitIdle(gfxQueue);
1289
1292
1293#ifdef Q_OS_WIN
1294 delete dxgiHdrInfo;
1295 dxgiHdrInfo = nullptr;
1296#endif
1297
1298 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
1299 if (ofr.cmdFence[i]) {
1300 df->vkDestroyFence(dev, ofr.cmdFence[i], nullptr);
1301 ofr.cmdFence[i] = VK_NULL_HANDLE;
1302 }
1303 ofr.cmdFenceWaitable[i] = false;
1304 }
1305
1306 if (pipelineCache) {
1307 df->vkDestroyPipelineCache(dev, pipelineCache, nullptr);
1308 pipelineCache = VK_NULL_HANDLE;
1309 }
1310
1311 for (const DescriptorPoolData &pool : descriptorPools)
1312 df->vkDestroyDescriptorPool(dev, pool.pool, nullptr);
1313
1314 descriptorPools.clear();
1315
1316 if (timestampQueryPool) {
1317 df->vkDestroyQueryPool(dev, timestampQueryPool, nullptr);
1318 timestampQueryPool = VK_NULL_HANDLE;
1319 }
1320
1321 if (!importedAllocator && allocator) {
1322 vmaDestroyAllocator(toVmaAllocator(allocator));
1323 allocator = nullptr;
1324 }
1325
1326 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
1327 if (cmdPool[i]) {
1328 df->vkDestroyCommandPool(dev, cmdPool[i], nullptr);
1329 cmdPool[i] = VK_NULL_HANDLE;
1330 }
1331 freeSecondaryCbs[i].clear();
1332 ofr.cbWrapper[i]->cb = VK_NULL_HANDLE;
1333 }
1334
1335 if (!importedDevice && dev) {
1336 df->vkDestroyDevice(dev, nullptr);
1337 inst->resetDeviceFunctions(dev);
1338 dev = VK_NULL_HANDLE;
1339 }
1340
1341 f = nullptr;
1342 df = nullptr;
1343
1344 importedDevice = false;
1345 importedAllocator = false;
1346}
1347
1348QRhi::AdapterList QRhiVulkan::enumerateAdaptersBeforeCreate(QRhiNativeHandles *nativeHandles) const
1349{
1350 VkPhysicalDevice requestedPhysDev = VK_NULL_HANDLE;
1351 if (nativeHandles) {
1352 QRhiVulkanNativeHandles *h = static_cast<QRhiVulkanNativeHandles *>(nativeHandles);
1353 requestedPhysDev = h->physDev;
1354 }
1355
1356 QRhi::AdapterList list;
1357 QVulkanFunctions *f = inst->functions();
1358 uint32_t physDevCount = 0;
1359 f->vkEnumeratePhysicalDevices(inst->vkInstance(), &physDevCount, nullptr);
1360 if (!physDevCount)
1361 return {};
1362
1363 QVarLengthArray<VkPhysicalDevice, 4> physDevs(physDevCount);
1364 VkResult err = f->vkEnumeratePhysicalDevices(inst->vkInstance(), &physDevCount, physDevs.data());
1365 if (err != VK_SUCCESS || !physDevCount)
1366 return {};
1367
1368 VkPhysicalDeviceProperties physDevProperties = {};
1369 for (uint32_t i = 0; i < physDevCount; ++i) {
1370 if (requestedPhysDev && physDevs[i] != requestedPhysDev)
1371 continue;
1372
1373 f->vkGetPhysicalDeviceProperties(physDevs[i], &physDevProperties);
1374 QVulkanAdapter *a = new QVulkanAdapter;
1375 a->physDev = physDevs[i];
1376 fillDriverInfo(&a->adapterInfo, physDevProperties);
1377 list.append(a);
1378 }
1379
1380 return list;
1381}
1382
1384{
1385 return adapterInfo;
1386}
1387
1389{
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 }
1398 };
1399 VkDescriptorPoolCreateInfo descPoolInfo = {};
1400 descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
1401 // Do not enable vkFreeDescriptorSets - sets are never freed on their own
1402 // (good so no trouble with fragmentation), they just deref their pool
1403 // which is then reset at some point (or not).
1404 descPoolInfo.flags = 0;
1405 descPoolInfo.maxSets = QVK_DESC_SETS_PER_POOL;
1406 descPoolInfo.poolSizeCount = sizeof(descPoolSizes) / sizeof(descPoolSizes[0]);
1407 descPoolInfo.pPoolSizes = descPoolSizes;
1408 return df->vkCreateDescriptorPool(dev, &descPoolInfo, nullptr, pool);
1409}
1410
1411bool QRhiVulkan::allocateDescriptorSet(VkDescriptorSetAllocateInfo *allocInfo, VkDescriptorSet *result, int *resultPoolIndex)
1412{
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;
1418 return r;
1419 };
1420
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;
1426 }
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;
1432 return true;
1433 }
1434 }
1435 }
1436
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);
1445 return false;
1446 }
1447 descriptorPools[lastPoolIdx].allocedDescSets += allocInfo->descriptorSetCount;
1448 *resultPoolIndex = lastPoolIdx;
1449 return true;
1450 } else {
1451 qWarning("Failed to allocate new descriptor pool: %d", poolErr);
1452 return false;
1453 }
1454}
1455
1456static inline VkFormat toVkTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
1457{
1458 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
1459 switch (format) {
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;
1474
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;
1483
1484 case QRhiTexture::RGB10A2:
1485 // intentionally A2B10G10R10, not A2R10G10B10
1486 return VK_FORMAT_A2B10G10R10_UNORM_PACK32;
1487
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;
1496
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;
1505
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;
1516
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;
1531
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;
1538
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;
1567
1568 default:
1569 Q_UNREACHABLE_RETURN(VK_FORMAT_R8G8B8A8_UNORM);
1570 }
1571}
1572
1573static inline QRhiTexture::Format swapchainReadbackTextureFormat(VkFormat format, QRhiTexture::Flags *flags)
1574{
1575 switch (format) {
1576 case VK_FORMAT_R8G8B8A8_UNORM:
1577 return QRhiTexture::RGBA8;
1578 case VK_FORMAT_R8G8B8A8_SRGB:
1579 if (flags)
1580 (*flags) |= QRhiTexture::sRGB;
1581 return QRhiTexture::RGBA8;
1582 case VK_FORMAT_B8G8R8A8_UNORM:
1583 return QRhiTexture::BGRA8;
1584 case VK_FORMAT_B8G8R8A8_SRGB:
1585 if (flags)
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;
1594 default:
1595 qWarning("VkFormat %d cannot be read back", format);
1596 break;
1597 }
1598 return QRhiTexture::UnknownFormat;
1599}
1600
1601static constexpr inline bool isDepthTextureFormat(QRhiTexture::Format format)
1602{
1603 switch (format) {
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:
1609 return true;
1610
1611 default:
1612 return false;
1613 }
1614}
1615
1616static constexpr inline bool isStencilTextureFormat(QRhiTexture::Format format)
1617{
1618 switch (format) {
1619 case QRhiTexture::Format::D24S8:
1620 case QRhiTexture::Format::D32FS8:
1621 return true;
1622
1623 default:
1624 return false;
1625 }
1626}
1627
1628static constexpr inline VkImageAspectFlags aspectMaskForTextureFormat(QRhiTexture::Format format)
1629{
1630 if (isDepthTextureFormat(format)) {
1631 if (isStencilTextureFormat(format))
1632 return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
1633 else
1634 return VK_IMAGE_ASPECT_DEPTH_BIT;
1635 } else {
1636 return VK_IMAGE_ASPECT_COLOR_BIT;
1637 }
1638}
1639
1640// Transient images ("render buffers") backed by lazily allocated memory are
1641// managed manually without going through vk_mem_alloc since it does not offer
1642// any support for such images. This should be ok since in practice there
1643// should be very few of such images.
1644
1645uint32_t QRhiVulkan::chooseTransientImageMemType(VkImage img, uint32_t startIndex)
1646{
1647 VkPhysicalDeviceMemoryProperties physDevMemProps;
1648 f->vkGetPhysicalDeviceMemoryProperties(physDev, &physDevMemProps);
1649
1650 VkMemoryRequirements memReq;
1651 df->vkGetImageMemoryRequirements(dev, img, &memReq);
1652 uint32_t memTypeIndex = uint32_t(-1);
1653
1654 if (memReq.memoryTypeBits) {
1655 // Find a device local + lazily allocated, or at least device local memtype.
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;
1663 memTypeIndex = i;
1664 }
1665 if (memType[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
1666 memTypeIndex = i;
1667 break;
1668 }
1669 }
1670 }
1671 }
1672 }
1673
1674 return memTypeIndex;
1675}
1676
1677bool QRhiVulkan::createTransientImage(VkFormat format,
1678 const QSize &pixelSize,
1679 VkImageUsageFlags usage,
1680 VkImageAspectFlags aspectMask,
1681 VkSampleCountFlagBits samples,
1682 VkDeviceMemory *mem,
1683 VkImage *images,
1684 VkImageView *views,
1685 int count)
1686{
1687 VkMemoryRequirements memReq;
1688 VkResult err;
1689
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;
1694 }
1695
1696 auto cleanup = qScopeGuard([this, mem, images, views, count] {
1697 for (int i = 0; i < count; ++i) {
1698 if (views[i]) {
1699 df->vkDestroyImageView(dev, views[i], nullptr);
1700 views[i] = VK_NULL_HANDLE;
1701 }
1702 if (images[i]) {
1703 df->vkDestroyImage(dev, images[i], nullptr);
1704 images[i] = VK_NULL_HANDLE;
1705 }
1706 }
1707 if (*mem) {
1708 df->vkFreeMemory(dev, *mem, nullptr);
1709 *mem = VK_NULL_HANDLE;
1710 }
1711 });
1712
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;
1726
1727 err = df->vkCreateImage(dev, &imgInfo, nullptr, images + i);
1728 if (err != VK_SUCCESS) {
1729 qWarning("Failed to create image: %d", err);
1730 return false;
1731 }
1732
1733 // Assume the reqs are the same since the images are same in every way.
1734 // Still, call GetImageMemReq for every image, in order to prevent the
1735 // validation layer from complaining.
1736 df->vkGetImageMemoryRequirements(dev, images[i], &memReq);
1737 }
1738
1739 VkMemoryAllocateInfo memInfo = {};
1740 memInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1741 memInfo.allocationSize = aligned(memReq.size, memReq.alignment) * VkDeviceSize(count);
1742
1743 uint32_t startIndex = 0;
1744 do {
1745 memInfo.memoryTypeIndex = chooseTransientImageMemType(images[0], startIndex);
1746 if (memInfo.memoryTypeIndex == uint32_t(-1)) {
1747 qWarning("No suitable memory type found");
1748 return false;
1749 }
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);
1754 return false;
1755 }
1756 } while (err != VK_SUCCESS);
1757
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);
1763 return false;
1764 }
1765 ofs += aligned(memReq.size, memReq.alignment);
1766
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;
1778
1779 err = df->vkCreateImageView(dev, &imgViewInfo, nullptr, views + i);
1780 if (err != VK_SUCCESS) {
1781 qWarning("Failed to create image view: %d", err);
1782 return false;
1783 }
1784 }
1785
1786 cleanup.dismiss();
1787 return true;
1788}
1789
1791{
1792 if (optimalDsFormat != VK_FORMAT_UNDEFINED)
1793 return optimalDsFormat;
1794
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
1799 };
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)
1807 break;
1808 ++dsFormatIdx;
1809 }
1810 if (dsFormatIdx == dsFormatCandidateCount)
1811 qWarning("Failed to find an optimal depth-stencil format");
1812
1813 return optimalDsFormat;
1814}
1815
1817{
1818 bool prepare(VkRenderPassCreateInfo *rpInfo, int multiViewCount, bool multiViewCap)
1819 {
1820 if (multiViewCount < 2)
1821 return true;
1822 if (!multiViewCap) {
1823 qWarning("Cannot create multiview render pass without support for the Vulkan 1.1 multiview feature");
1824 return false;
1825 }
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;
1838#endif
1839 return true;
1840 }
1841
1842#ifdef VK_VERSION_1_1
1846#endif
1847};
1848
1849#ifdef VK_KHR_create_renderpass2
1850// Effectively converts a VkRenderPassCreateInfo into a VkRenderPassCreateInfo2,
1851// adding depth-stencil resolve and VRS support. Incorporates multiview into the
1852// info structs (no chaining needed). Assumes a single subpass.
1853struct RenderPass2SetupHelper
1854{
1855 RenderPass2SetupHelper(QRhiVulkan *rhiD) : rhiD(rhiD) { }
1856
1857 bool prepare(VkRenderPassCreateInfo2 *rpInfo2, const VkRenderPassCreateInfo *rpInfo, const QVkRenderPassDescriptor *rpD, int multiViewCount) {
1858 *rpInfo2 = {};
1859
1860 viewMask = 0;
1861 if (multiViewCount >= 2) {
1862 for (uint32_t i = 0; i < uint32_t(multiViewCount); ++i)
1863 viewMask |= (1 << i);
1864 }
1865
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]);
1870 att2 = {};
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;
1881 }
1882
1883 attRefs2.clear();
1884 subpass2 = {};
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;
1891
1892 // color attachment refs
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;
1902 }
1903 subpass2.colorAttachmentCount = subpassDesc.colorAttachmentCount;
1904 subpass2.pColorAttachments = attRefs2.constData() + startIndex;
1905
1906 // color resolve refs
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;
1917 }
1918 subpass2.pResolveAttachments = attRefs2.constData() + startIndex;
1919 }
1920
1921 // depth-stencil ref
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;
1932 }
1933
1934 // depth-stencil resolve ref
1935#ifdef VK_KHR_depth_stencil_resolve
1936 dsResolveDesc = {};
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);
1950 }
1951#endif
1952
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);
1967 }
1968#endif
1969
1970 // subpass dependencies, typically 0, 1, 2 of them,
1971 // depending on targeting swapchain or texture
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;
1985 }
1986
1987 rpInfo2->sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR;
1988 rpInfo2->pNext = nullptr; // the 1.1 VkRenderPassMultiviewCreateInfo is part of the '2' structs
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;
1999 }
2000 return true;
2001 }
2002
2003 QRhiVulkan *rhiD;
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;
2010#endif
2011#ifdef VK_KHR_fragment_shading_rate
2012 VkFragmentShadingRateAttachmentInfoKHR shadingRateAttInfo;
2013#endif
2014 uint32_t viewMask;
2015};
2016#endif // VK_KHR_create_renderpass2
2017
2018static void fillRenderPassCreateInfo(VkRenderPassCreateInfo *rpInfo,
2019 VkSubpassDescription *subpassDesc,
2021{
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;
2028
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;
2037}
2038
2039// Add self-dependency to be able to add memory barriers for writes in graphics stages.
2041{
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;
2057#endif
2058 selfDependency.dependencyFlags = depFlags;
2059 rpD->subpassDeps.append(selfDependency);
2060}
2061
2063 bool hasDepthStencil,
2064 VkSampleCountFlagBits samples,
2065 VkFormat colorFormat,
2066 QRhiShadingRateMap *shadingRateMap)
2067{
2068 // attachment list layout is color (1), ds (0-1), resolve (0-1), shading rate (0-1)
2069
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);
2080
2081 rpD->colorRefs.append({ 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL });
2082
2083 rpD->hasDepthStencil = hasDepthStencil;
2084 rpD->hasDepthStencilResolve = false;
2085 rpD->hasShadingRateMap = shadingRateMap != nullptr;
2086 rpD->multiViewCount = 0;
2087
2088 if (hasDepthStencil) {
2089 // clear on load + no store + lazy alloc + transient image should play
2090 // nicely with tiled GPUs (no physical backing necessary for ds buffer)
2091 attDesc = {};
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);
2101
2102 rpD->dsRef = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
2103 } else {
2104 rpD->dsRef = {};
2105 }
2106
2107 if (samples > VK_SAMPLE_COUNT_1_BIT) {
2108 attDesc = {};
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);
2118
2119 rpD->resolveRefs.append({ uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL });
2120 }
2121
2122 rpD->dsResolveRef = {};
2123
2124 rpD->shadingRateRef = {};
2125#ifdef VK_KHR_fragment_shading_rate
2126 if (shadingRateMap) {
2127 attDesc = {};
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);
2137
2138 rpD->shadingRateRef = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR };
2139 }
2140#endif
2141
2142 // Replace the first implicit dep (TOP_OF_PIPE / ALL_COMMANDS) with our own.
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);
2163 }
2164
2166
2167 VkRenderPassCreateInfo rpInfo;
2168 VkSubpassDescription subpassDesc;
2169 fillRenderPassCreateInfo(&rpInfo, &subpassDesc, rpD);
2170
2171#ifdef VK_KHR_create_renderpass2
2172 if (caps.renderPass2KHR) {
2173 // Use the KHR extension, not the 1.2 core API, in order to support Vulkan 1.1.
2174 VkRenderPassCreateInfo2KHR rpInfo2;
2175 RenderPass2SetupHelper rp2Helper(this);
2176 if (!rp2Helper.prepare(&rpInfo2, &rpInfo, rpD, 0))
2177 return false;
2178 VkResult err = vkCreateRenderPass2KHR(dev, &rpInfo2, nullptr, &rpD->rp);
2179 if (err != VK_SUCCESS) {
2180 qWarning("Failed to create renderpass (using VkRenderPassCreateInfo2KHR): %d", err);
2181 return false;
2182 }
2183 } else
2184#endif
2185 {
2186 if (rpD->hasShadingRateMap)
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);
2191 return false;
2192 }
2193 }
2194
2195 return true;
2196}
2197
2199 const QRhiColorAttachment *colorAttachmentsBegin,
2200 const QRhiColorAttachment *colorAttachmentsEnd,
2201 bool preserveColor,
2202 bool preserveDs,
2203 bool storeDs,
2204 QRhiRenderBuffer *depthStencilBuffer,
2205 QRhiTexture *depthTexture,
2206 QRhiTexture *depthResolveTexture,
2207 int depthLayer,
2208 QRhiShadingRateMap *shadingRateMap)
2209{
2210 // attachment list layout is color (0-8), ds (0-1), resolve (0-8), ds resolve (0-1)
2211
2212 int multiViewCount = 0;
2213 for (auto it = colorAttachmentsBegin; it != colorAttachmentsEnd; ++it) {
2214 QVkTexture *texD = QRHI_RES(QVkTexture, it->texture());
2215 QVkRenderBuffer *rbD = QRHI_RES(QVkRenderBuffer, it->renderBuffer());
2216 Q_ASSERT(texD || rbD);
2217 const VkFormat vkformat = texD ? texD->viewFormat : rbD->vkformat;
2218 const VkSampleCountFlagBits samples = texD ? texD->samples : rbD->samples;
2219
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;
2227 // this has to interact correctly with activateTextureRenderTarget(), hence leaving in COLOR_ATT
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);
2231
2232 const VkAttachmentReference ref = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
2233 rpD->colorRefs.append(ref);
2234
2235 if (it->multiViewCount() >= 2) {
2236 if (multiViewCount > 0 && multiViewCount != it->multiViewCount())
2237 qWarning("Inconsistent multiViewCount in color attachment set");
2238 else
2239 multiViewCount = it->multiViewCount();
2240 } else if (multiViewCount > 0) {
2241 qWarning("Mixing non-multiview color attachments within a multiview render pass");
2242 }
2243 }
2244 Q_ASSERT(multiViewCount == 0 || multiViewCount >= 2);
2245 rpD->multiViewCount = uint32_t(multiViewCount);
2246
2247 rpD->hasDepthStencil = depthStencilBuffer || depthTexture;
2248 if (rpD->hasDepthStencil) {
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;
2268 }
2269 rpD->dsRef = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
2270 } else {
2271 rpD->dsRef = {};
2272 }
2273
2274 for (auto it = colorAttachmentsBegin; it != colorAttachmentsEnd; ++it) {
2275 if (it->resolveTexture()) {
2276 QVkTexture *rtexD = QRHI_RES(QVkTexture, 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");
2280
2281 QVkTexture *texD = QRHI_RES(QVkTexture, it->texture());
2282 QVkRenderBuffer *rbD = QRHI_RES(QVkRenderBuffer, it->renderBuffer());
2283 const VkFormat srcFormat = texD ? texD->vkformat : rbD->vkformat;
2284 if (srcFormat != dstFormat) {
2285 // This is a validation error. But some implementations survive,
2286 // actually. Warn about it however, because it's an error with
2287 // some other backends (like D3D) as well.
2288 qWarning("Multisample resolve between different formats (%d and %d) is not supported.",
2289 int(srcFormat), int(dstFormat));
2290 }
2291
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; // ignored
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);
2302
2303 const VkAttachmentReference ref = { uint32_t(rpD->attDescs.size() - 1), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
2304 rpD->resolveRefs.append(ref);
2305 } else {
2306 const VkAttachmentReference ref = { VK_ATTACHMENT_UNUSED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
2307 rpD->resolveRefs.append(ref);
2308 }
2309 }
2310 Q_ASSERT(rpD->colorRefs.size() == rpD->resolveRefs.size());
2311
2312 rpD->hasDepthStencilResolve = rpD->hasDepthStencil && depthResolveTexture;
2313 if (rpD->hasDepthStencilResolve) {
2314 QVkTexture *rtexD = QRHI_RES(QVkTexture, depthResolveTexture);
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;
2318
2319 QVkTexture *texD = QRHI_RES(QVkTexture, depthTexture);
2320 QVkRenderBuffer *rbD = QRHI_RES(QVkRenderBuffer, depthStencilBuffer);
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));
2326 }
2327
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; // ignored
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 };
2339 } else {
2340 rpD->dsResolveRef = {};
2341 }
2342
2343 rpD->hasShadingRateMap = shadingRateMap != nullptr;
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 };
2358 }
2359#endif
2360
2361 // Replace the first implicit dep (TOP_OF_PIPE / ALL_COMMANDS) with our
2362 // own. The resource tracking and activateTextureRenderTarget() take care
2363 // of generating barriers (with dst being the attachment output stages)
2364 // before the render pass, but the layout transitions in the render pass
2365 // (UNDEFINED -> COLOR/DEPTH_STENCIL_ATTACHMENT_OPTIMAL whenever the
2366 // contents are not preserved) are performed as part of the external
2367 // dependency. With the implicit one having srcStageMask TOP_OF_PIPE, those
2368 // would not form a dependency chain with the earlier barriers, leading to
2369 // a write-after-write hazard against e.g. the storeOp of a previous pass
2370 // targeting the same image.
2371 VkSubpassDependency subpassDep = {};
2372 subpassDep.srcSubpass = VK_SUBPASS_EXTERNAL;
2373 subpassDep.dstSubpass = 0;
2374 // Multisample resolves, including depth/stencil, run at color output.
2375 if (!rpD->colorRefs.isEmpty() || rpD->hasDepthStencilResolve) {
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;
2379 }
2380 if (rpD->hasDepthStencil) {
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;
2385 }
2386 if (subpassDep.srcStageMask) {
2387 subpassDep.dstStageMask = subpassDep.srcStageMask;
2388 subpassDep.dstAccessMask |= subpassDep.srcAccessMask;
2389 rpD->subpassDeps.append(subpassDep);
2390 }
2391
2393
2394 VkRenderPassCreateInfo rpInfo;
2395 VkSubpassDescription subpassDesc;
2396 fillRenderPassCreateInfo(&rpInfo, &subpassDesc, rpD);
2397
2398 MultiViewRenderPassSetupHelper multiViewHelper;
2399 if (!multiViewHelper.prepare(&rpInfo, multiViewCount, caps.multiView))
2400 return false;
2401
2402#ifdef VK_KHR_create_renderpass2
2403 if (caps.renderPass2KHR) {
2404 // Use the KHR extension, not the 1.2 core API, in order to support Vulkan 1.1.
2405 VkRenderPassCreateInfo2KHR rpInfo2;
2406 RenderPass2SetupHelper rp2Helper(this);
2407 if (!rp2Helper.prepare(&rpInfo2, &rpInfo, rpD, multiViewCount))
2408 return false;
2409
2410 VkResult err = vkCreateRenderPass2KHR(dev, &rpInfo2, nullptr, &rpD->rp);
2411 if (err != VK_SUCCESS) {
2412 qWarning("Failed to create renderpass (using VkRenderPassCreateInfo2KHR): %d", err);
2413 return false;
2414 }
2415 } else
2416#endif
2417 {
2418 if (rpD->hasDepthStencilResolve) {
2419 qWarning("Resolving multisample depth-stencil buffers is not supported without "
2420 "VK_KHR_depth_stencil_resolve and VK_KHR_create_renderpass2");
2421 }
2422 if (rpD->hasShadingRateMap)
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);
2427 return false;
2428 }
2429 }
2430
2431 return true;
2432}
2433
2434bool QRhiVulkan::recreateSwapChain(QRhiSwapChain *swapChain)
2435{
2436 QVkSwapChain *swapChainD = QRHI_RES(QVkSwapChain, swapChain);
2437 if (swapChainD->pixelSize.isEmpty()) {
2438 qWarning("Surface size is 0, cannot create swapchain");
2439 return false;
2440 }
2441
2442 if (!deviceLost)
2443 df->vkQueueWaitIdle(gfxQueue);
2444
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");
2453 return false;
2454 }
2455 }
2456
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);
2462 } else {
2463 reqBufferCount = qMax(qMin<quint32>(surfaceCaps.maxImageCount, 3), surfaceCaps.minImageCount);
2464 }
2465 VkSurfaceTransformFlagBitsKHR preTransform =
2466 (surfaceCaps.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
2467 ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR
2468 : surfaceCaps.currentTransform;
2469
2470 // This looks odd but matches how platforms work in practice.
2471 //
2472 // On Windows with NVIDIA for example, the only supportedCompositeAlpha
2473 // value reported is OPAQUE, nothing else. Yet transparency works
2474 // regardless, as long as the native window is set up correctly, so that's
2475 // not something we need to handle here.
2476 //
2477 // On Linux with Intel and Mesa and running on xcb reports, on one
2478 // particular system, INHERIT+PRE_MULTIPLIED. Tranparency works, regardless,
2479 // presumably due to setting INHERIT.
2480 //
2481 // On the same setup with Wayland instead of xcb we see
2482 // OPAQUE+PRE_MULTIPLIED reported. Here transparency won't work unless
2483 // PRE_MULTIPLIED is set.
2484 //
2485 // Therefore our rules are:
2486 // - Prefer INHERIT over OPAQUE.
2487 // - Then based on the request, try the requested alpha mode, but if
2488 // that's not reported as supported, try also the other (PRE/POST,
2489 // POST/PRE) as that is better than nothing. This is not different from
2490 // some other backends, e.g. D3D11 with DirectComposition there is also
2491 // no control over being straight or pre-multiplied. Whereas with
2492 // WGL/GLX/EGL we never had that sort of control.
2493
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;
2498
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;
2509 }
2510
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;
2515
2516 const bool stereo = bool(swapChainD->m_window) && (swapChainD->m_window->format().stereo())
2517 && surfaceCaps.maxImageArrayLayers > 1;
2518 swapChainD->stereo = stereo;
2519
2520 VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
2521 if (swapChainD->m_flags.testFlag(QRhiSwapChain::NoVSync)) {
2522 // Stereo has a weird bug, when using VK_PRESENT_MODE_MAILBOX_KHR,
2523 // black screen is shown, but there is no validation error.
2524 // Detected on Windows, with NVidia RTX A series (at least 4000 and 6000) driver 535.98
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;
2529 }
2530
2531 // If the surface is different than before, then passing in the old
2532 // swapchain associated with the old surface can fail the swapchain
2533 // creation. (for example, Android loses the surface when backgrounding and
2534 // restoring applications, and it also enforces failing swapchain creation
2535 // with VK_ERROR_NATIVE_WINDOW_IN_USE_KHR if the old swapchain is provided)
2536 const bool reuseExisting = swapChainD->sc && swapChainD->lastConnectedSurface == swapChainD->surface;
2537
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);
2541
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;
2557
2558 VkSwapchainKHR newSwapChain;
2559 VkResult err = vkCreateSwapchainKHR(dev, &swapChainInfo, nullptr, &newSwapChain);
2560 if (err != VK_SUCCESS) {
2561 qWarning("Failed to create swapchain: %d", err);
2562 return false;
2563 }
2564 setObjectName(uint64_t(newSwapChain), VK_OBJECT_TYPE_SWAPCHAIN_KHR, swapChainD->m_objectName);
2565
2566 if (swapChainD->sc)
2568
2569 swapChainD->sc = newSwapChain;
2570 swapChainD->lastConnectedSurface = swapChainD->surface;
2571
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);
2576 return false;
2577 }
2578
2579 if (actualSwapChainBufferCount != reqBufferCount)
2580 qCDebug(QRHI_LOG_INFO, "Actual swapchain buffer count is %u", actualSwapChainBufferCount);
2581 swapChainD->bufferCount = int(actualSwapChainBufferCount);
2582
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);
2587 return false;
2588 }
2589
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,
2599 msaaImages.data(),
2600 msaaViews.data(),
2601 swapChainD->bufferCount))
2602 {
2603 qWarning("Failed to create transient image for MSAA color buffer");
2604 return false;
2605 }
2606 }
2607
2608 VkFenceCreateInfo fenceInfo = {};
2609 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
2610 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
2611
2612 // Double up for stereo
2613 swapChainD->imageRes.resize(swapChainD->bufferCount * (stereo ? 2u : 1u));
2614
2615 for (int i = 0; i < swapChainD->bufferCount; ++i) {
2616 QVkSwapChain::ImageResources &image(swapChainD->imageRes[i]);
2617 image.image = swapChainImages[i];
2618 if (swapChainD->samples > VK_SAMPLE_COUNT_1_BIT) {
2619 image.msaaImage = msaaImages[i];
2620 image.msaaImageView = msaaViews[i];
2621 }
2622
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);
2637 return false;
2638 }
2639
2641
2642 VkSemaphoreCreateInfo semInfo = {};
2643 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
2644 df->vkCreateSemaphore(dev, &semInfo, nullptr, &image.drawSem);
2645 }
2646 if (stereo) {
2647 for (int i = 0; i < swapChainD->bufferCount; ++i) {
2648 QVkSwapChain::ImageResources &image(swapChainD->imageRes[i + swapChainD->bufferCount]);
2649 image.image = swapChainImages[i];
2650 if (swapChainD->samples > VK_SAMPLE_COUNT_1_BIT) {
2651 image.msaaImage = msaaImages[i];
2652 image.msaaImageView = msaaViews[i];
2653 }
2654
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);
2670 return false;
2671 }
2672
2673 VkSemaphoreCreateInfo semInfo = {};
2674 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
2675 df->vkCreateSemaphore(dev, &semInfo, nullptr, &image.drawSem);
2676
2678 }
2679 }
2680
2681 swapChainD->currentImageIndex = 0;
2682
2683 if (swapChainD->shadingRateMap() && caps.renderPass2KHR && caps.imageBasedShadingRate) {
2684 QVkTexture *texD = QRHI_RES(QVkShadingRateMap, swapChainD->shadingRateMap())->texture;
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);
2703 return false;
2704 }
2705 }
2706
2707 VkSemaphoreCreateInfo semInfo = {};
2708 semInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
2709
2710 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
2711 QVkSwapChain::FrameResources &frame(swapChainD->frameRes[i]);
2712
2713 frame.imageAcquired = false;
2714 frame.imageSemWaitable = false;
2715
2716 df->vkCreateSemaphore(dev, &semInfo, nullptr, &frame.imageSem);
2717
2718 err = df->vkCreateFence(dev, &fenceInfo, nullptr, &frame.cmdFence);
2719 if (err != VK_SUCCESS) {
2720 qWarning("Failed to create command buffer fence: %d", err);
2721 return false;
2722 }
2723 frame.cmdFenceWaitable = true; // fence was created in signaled state
2724 }
2725
2726 return true;
2727}
2728
2729void QRhiVulkan::releaseSwapChainResources(QRhiSwapChain *swapChain)
2730{
2731 QVkSwapChain *swapChainD = QRHI_RES(QVkSwapChain, swapChain);
2732
2733 if (swapChainD->sc == VK_NULL_HANDLE)
2734 return;
2735
2736 if (!deviceLost)
2737 df->vkQueueWaitIdle(gfxQueue);
2738
2739 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
2740 QVkSwapChain::FrameResources &frame(swapChainD->frameRes[i]);
2741 if (frame.cmdFence) {
2742 if (!deviceLost && frame.cmdFenceWaitable)
2743 df->vkWaitForFences(dev, 1, &frame.cmdFence, VK_TRUE, UINT64_MAX);
2744 df->vkDestroyFence(dev, frame.cmdFence, nullptr);
2745 frame.cmdFence = VK_NULL_HANDLE;
2746 frame.cmdFenceWaitable = false;
2747 }
2748 if (frame.imageSem) {
2749 df->vkDestroySemaphore(dev, frame.imageSem, nullptr);
2750 frame.imageSem = VK_NULL_HANDLE;
2751 }
2752 }
2753
2754 for (int i = 0; i < swapChainD->bufferCount * (swapChainD->stereo ? 2 : 1); ++i) {
2755 QVkSwapChain::ImageResources &image(swapChainD->imageRes[i]);
2756 if (image.fb) {
2757 df->vkDestroyFramebuffer(dev, image.fb, nullptr);
2758 image.fb = VK_NULL_HANDLE;
2759 }
2760 if (image.imageView) {
2761 df->vkDestroyImageView(dev, image.imageView, nullptr);
2762 image.imageView = VK_NULL_HANDLE;
2763 }
2764 if (image.msaaImageView) {
2765 df->vkDestroyImageView(dev, image.msaaImageView, nullptr);
2766 image.msaaImageView = VK_NULL_HANDLE;
2767 }
2768 if (image.msaaImage) {
2769 df->vkDestroyImage(dev, image.msaaImage, nullptr);
2770 image.msaaImage = VK_NULL_HANDLE;
2771 }
2772 if (image.drawSem) {
2773 df->vkDestroySemaphore(dev, image.drawSem, nullptr);
2774 image.drawSem = VK_NULL_HANDLE;
2775 }
2776 }
2777
2778 if (swapChainD->msaaImageMem) {
2779 df->vkFreeMemory(dev, swapChainD->msaaImageMem, nullptr);
2780 swapChainD->msaaImageMem = VK_NULL_HANDLE;
2781 }
2782
2783 if (swapChainD->shadingRateMapView) {
2784 df->vkDestroyImageView(dev, swapChainD->shadingRateMapView, nullptr);
2785 swapChainD->shadingRateMapView = VK_NULL_HANDLE;
2786 }
2787
2788 vkDestroySwapchainKHR(dev, swapChainD->sc, nullptr);
2789 swapChainD->sc = VK_NULL_HANDLE;
2790
2791 // NB! surface and similar must remain intact
2792}
2793
2795{
2796 VkCommandPoolResetFlags flags = 0;
2797
2798 // While not clear what "recycles all of the resources from the command
2799 // pool back to the system" really means in practice, set it when there was
2800 // a call to releaseCachedResources() recently.
2802 flags |= VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT;
2803
2804 // put all command buffers allocated from this slot's pool to initial state
2805 df->vkResetCommandPool(dev, cmdPool[currentFrameSlot], flags);
2806}
2807
2808double QRhiVulkan::elapsedSecondsFromTimestamp(quint64 timestamp[2], bool *ok)
2809{
2810 quint64 mask = 0;
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;
2819 *ok = true;
2820 return elapsedSec;
2821 }
2822 *ok = false;
2823 return 0;
2824}
2825
2827{
2828 QVkSwapChain *swapChainD = QRHI_RES(QVkSwapChain, swapChain);
2829 const int frameResIndex = swapChainD->bufferCount > 1 ? currentFrameSlot : 0;
2830 QVkSwapChain::FrameResources &frame(swapChainD->frameRes[frameResIndex]);
2831
2832 inst->handle()->beginFrame(swapChainD->window);
2833 auto instEndFrameOnErrorGuard = qScopeGuard([this, swapChainD] {
2834 inst->handle()->endFrame(swapChainD->window);
2835 });
2836
2837 // Make sure the previous commands for the same frame slot have finished.
2838 //
2839 // Do this also for any other swapchain's commands with the same frame slot
2840 // It keeps resource usage safe: swapchain A starting its frame 0, followed
2841 // by swapchain B starting its own frame 0 will make B wait for A's frame 0
2842 // commands, so if a resource is written in B's frame or when B checks for
2843 // pending resource releases, that won't mess up A's in-flight commands (as
2844 // they are not in flight anymore).
2845 QRhi::FrameOpResult waitResult = waitCommandCompletion(frameResIndex);
2846 if (waitResult != QRhi::FrameOpSuccess)
2847 return waitResult;
2848
2849 if (!frame.imageAcquired) {
2850 // move on to next swapchain image
2851 uint32_t imageIndex = 0;
2852 VkResult err = vkAcquireNextImageKHR(dev, swapChainD->sc, UINT64_MAX,
2853 frame.imageSem, VK_NULL_HANDLE, &imageIndex);
2854
2855 if (err == VK_SUCCESS || err == VK_SUBOPTIMAL_KHR) {
2856 swapChainD->currentImageIndex = imageIndex;
2857 frame.imageSemWaitable = true;
2858 frame.imageAcquired = true;
2859 } else if (err == VK_ERROR_OUT_OF_DATE_KHR) {
2860 return QRhi::FrameOpSwapChainOutOfDate;
2861 } else {
2862 if (err == VK_ERROR_DEVICE_LOST) {
2863 qWarning("Device loss detected in vkAcquireNextImageKHR()");
2864 printExtraErrorInfo(err);
2865 deviceLost = true;
2866 return QRhi::FrameOpDeviceLost;
2867 }
2868 qWarning("Failed to acquire next swapchain image: %d", err);
2869 return QRhi::FrameOpError;
2870 }
2871 }
2872
2873 currentSwapChain = swapChainD;
2874 if (swapChainD->ds)
2875 swapChainD->ds->lastActiveFrameSlot = currentFrameSlot;
2876
2877 // reset the command pool
2879
2880 // start recording to this frame's command buffer
2881 QRhi::FrameOpResult cbres = startPrimaryCommandBuffer(&frame.cmdBuf);
2882 if (cbres != QRhi::FrameOpSuccess)
2883 return cbres;
2884
2885 swapChainD->cbWrapper.cb = frame.cmdBuf;
2886
2887 QVkSwapChain::ImageResources &image(swapChainD->imageRes[swapChainD->currentImageIndex]);
2888 swapChainD->rtWrapper.d.fb = image.fb;
2889
2890 if (swapChainD->stereo) {
2892 swapChainD->imageRes[swapChainD->currentImageIndex + swapChainD->bufferCount]);
2893 swapChainD->rtWrapperRight.d.fb = image.fb;
2894 }
2895
2896 prepareNewFrame(&swapChainD->cbWrapper);
2897
2898 // Read the timestamps for the previous frame for this slot.
2899 if (frame.timestampQueryIndex >= 0) {
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);
2905 frame.timestampQueryIndex = -1;
2906 if (err == VK_SUCCESS) {
2907 bool ok = false;
2908 const double elapsedSec = elapsedSecondsFromTimestamp(timestamp, &ok);
2909 if (ok)
2910 swapChainD->cbWrapper.lastGpuTime = elapsedSec;
2911 } else {
2912 qWarning("Failed to query timestamp: %d", err);
2913 }
2914 }
2915
2916 // No timestamps if the client did not opt in, or when not having at least 2 frames in flight.
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;
2923 break;
2924 }
2925 }
2926 if (timestampQueryIdx >= 0) {
2927 df->vkCmdResetQueryPool(frame.cmdBuf, timestampQueryPool, uint32_t(timestampQueryIdx), 2);
2928 // record timestamp at the start of the command buffer
2929 df->vkCmdWriteTimestamp(frame.cmdBuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
2930 timestampQueryPool, uint32_t(timestampQueryIdx));
2931 frame.timestampQueryIndex = timestampQueryIdx;
2932 }
2933 }
2934
2935 instEndFrameOnErrorGuard.dismiss();
2936 return QRhi::FrameOpSuccess;
2937}
2938
2939QRhi::FrameOpResult QRhiVulkan::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
2940{
2941 QVkSwapChain *swapChainD = QRHI_RES(QVkSwapChain, swapChain);
2942 Q_ASSERT(currentSwapChain == swapChainD);
2943
2944 auto cleanup = qScopeGuard([this, swapChainD] {
2945 inst->handle()->endFrame(swapChainD->window);
2946 });
2947
2948 recordPrimaryCommandBuffer(&swapChainD->cbWrapper);
2949
2950 int frameResIndex = swapChainD->bufferCount > 1 ? currentFrameSlot : 0;
2951 QVkSwapChain::FrameResources &frame(swapChainD->frameRes[frameResIndex]);
2952 QVkSwapChain::ImageResources &image(swapChainD->imageRes[swapChainD->currentImageIndex]);
2953
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;
2962
2964 // was not used at all (no render pass), just transition from undefined to presentable
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,
2970 1, &presTrans);
2972 // was used in a readback as transfer source, go back to presentable layout
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,
2978 1, &presTrans);
2979 }
2981 }
2982
2983 // record another timestamp, when enabled
2984 if (frame.timestampQueryIndex >= 0) {
2985 df->vkCmdWriteTimestamp(frame.cmdBuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2986 timestampQueryPool, uint32_t(frame.timestampQueryIndex + 1));
2987 }
2988
2989 // stop recording and submit to the queue
2990 Q_ASSERT(!frame.cmdFenceWaitable);
2991 const bool needsPresent = !flags.testFlag(QRhi::SkipPresent);
2992 QRhi::FrameOpResult submitres = endAndSubmitPrimaryCommandBuffer(frame.cmdBuf,
2993 frame.cmdFence,
2994 frame.imageSemWaitable ? &frame.imageSem : nullptr,
2995 needsPresent ? &image.drawSem : nullptr);
2996 if (submitres != QRhi::FrameOpSuccess)
2997 return submitres;
2998
2999 frame.imageSemWaitable = false;
3000 frame.cmdFenceWaitable = true;
3001
3002 if (needsPresent) {
3003 // add the Present to the queue
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();
3012
3013 // Do platform-specific WM notification. F.ex. essential on Wayland in
3014 // order to circumvent driver frame callbacks
3015 inst->presentAboutToBeQueued(swapChainD->window);
3016
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);
3026 deviceLost = true;
3027 return QRhi::FrameOpDeviceLost;
3028 }
3029 qWarning("Failed to present: %d", err);
3030 return QRhi::FrameOpError;
3031 }
3032 }
3033
3034 // Do platform-specific WM notification. F.ex. essential on X11 in
3035 // order to prevent glitches on resizing the window.
3036 inst->presentQueued(swapChainD->window);
3037
3038 // mark the current swapchain buffer as unused from our side
3039 frame.imageAcquired = false;
3040 // and move on to the next slot
3041 currentFrameSlot = (currentFrameSlot + 1) % QVK_FRAMES_IN_FLIGHT;
3042 }
3043
3044 swapChainD->frameCount += 1;
3045 currentSwapChain = nullptr;
3046 return QRhi::FrameOpSuccess;
3047}
3048
3049void QRhiVulkan::prepareNewFrame(QRhiCommandBuffer *cb)
3050{
3051 // Now is the time to do things for frame N-F, where N is the current one,
3052 // F is QVK_FRAMES_IN_FLIGHT, because only here it is guaranteed that that
3053 // frame has completed on the GPU (due to the fence wait in beginFrame). To
3054 // decide if something is safe to handle now a simple "lastActiveFrameSlot
3055 // == currentFrameSlot" is sufficient (remember that e.g. with F==2
3056 // currentFrameSlot goes 0, 1, 0, 1, 0, ...)
3057
3059
3060 QRHI_RES(QVkCommandBuffer, cb)->resetState();
3061
3062 finishActiveReadbacks(); // last, in case the readback-completed callback issues rhi calls
3063
3065}
3066
3068{
3069 if (!*cb) {
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;
3075
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);
3081 deviceLost = true;
3082 return QRhi::FrameOpDeviceLost;
3083 }
3084 qWarning("Failed to allocate frame command buffer: %d", err);
3085 return QRhi::FrameOpError;
3086 }
3087 }
3088
3089 VkCommandBufferBeginInfo cmdBufBeginInfo = {};
3090 cmdBufBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
3091
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);
3097 deviceLost = true;
3098 return QRhi::FrameOpDeviceLost;
3099 }
3100 qWarning("Failed to begin frame command buffer: %d", err);
3101 return QRhi::FrameOpError;
3102 }
3103
3104 return QRhi::FrameOpSuccess;
3105}
3106
3107QRhi::FrameOpResult QRhiVulkan::endAndSubmitPrimaryCommandBuffer(VkCommandBuffer cb, VkFence cmdFence,
3108 VkSemaphore *waitSem, VkSemaphore *signalSem)
3109{
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);
3115 deviceLost = true;
3116 return QRhi::FrameOpDeviceLost;
3117 }
3118 qWarning("Failed to end frame command buffer: %d", err);
3119 return QRhi::FrameOpError;
3120 }
3121
3122 VkSubmitInfo submitInfo = {};
3123 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
3124 submitInfo.commandBufferCount = 1;
3125 submitInfo.pCommandBuffers = &cb;
3126
3127 if (waitSem)
3128 waitSemaphoresForQueueSubmit.append(*waitSem);
3129 if (signalSem)
3130 signalSemaphoresForQueueSubmit.append(*signalSem);
3131
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();
3137 }
3138 submitInfo.signalSemaphoreCount = uint32_t(signalSemaphoresForQueueSubmit.count());
3139 if (!signalSemaphoresForQueueSubmit.isEmpty()) {
3140 submitInfo.pSignalSemaphores = signalSemaphoresForQueueSubmit.constData();
3141 }
3142
3143 err = df->vkQueueSubmit(gfxQueue, 1, &submitInfo, cmdFence);
3144
3145 waitSemaphoresForQueueSubmit.clear();
3146 signalSemaphoresForQueueSubmit.clear();
3147
3148 if (err != VK_SUCCESS) {
3149 if (err == VK_ERROR_DEVICE_LOST) {
3150 qWarning("Device loss detected in vkQueueSubmit()");
3151 printExtraErrorInfo(err);
3152 deviceLost = true;
3153 return QRhi::FrameOpDeviceLost;
3154 }
3155 qWarning("Failed to submit to graphics queue: %d", err);
3156 return QRhi::FrameOpError;
3157 }
3158
3159 return QRhi::FrameOpSuccess;
3160}
3161
3163{
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);
3169
3170 if (err != VK_SUCCESS) {
3171 if (err == VK_ERROR_DEVICE_LOST) {
3172 qWarning("Device loss detected in vkWaitForFences()");
3173 printExtraErrorInfo(err);
3174 deviceLost = true;
3175 return QRhi::FrameOpDeviceLost;
3176 }
3177 qWarning("Failed to wait for fence: %d", err);
3178 return QRhi::FrameOpError;
3179 }
3180
3181 df->vkResetFences(dev, 1, &frame.cmdFence);
3182 frame.cmdFenceWaitable = false;
3183 }
3184 }
3185
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);
3192 deviceLost = true;
3193 return QRhi::FrameOpDeviceLost;
3194 }
3195 qWarning("Failed to wait for offscreen fence: %d", err);
3196 return QRhi::FrameOpError;
3197 }
3198 df->vkResetFences(dev, 1, &ofr.cmdFence[frameSlot]);
3199 ofr.cmdFenceWaitable[frameSlot] = false;
3200 }
3201
3202 return QRhi::FrameOpSuccess;
3203}
3204
3206{
3207 QRhi::FrameOpResult waitResult = waitCommandCompletion(currentFrameSlot);
3208 if (waitResult != QRhi::FrameOpSuccess)
3209 return waitResult;
3210
3212
3213 QVkCommandBuffer *cbWrapper = ofr.cbWrapper[currentFrameSlot];
3214 QRhi::FrameOpResult cbres = startPrimaryCommandBuffer(&cbWrapper->cb);
3215 if (cbres != QRhi::FrameOpSuccess)
3216 return cbres;
3217
3218 prepareNewFrame(cbWrapper);
3219 ofr.active = true;
3220
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) {
3230 bool ok = false;
3231 const double elapsedSec = elapsedSecondsFromTimestamp(timestamp, &ok);
3232 if (ok)
3233 cbWrapper->lastGpuTime = elapsedSec;
3234 } else {
3235 qWarning("Failed to query timestamp: %d", err);
3236 }
3237 }
3238
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;
3245 break;
3246 }
3247 }
3248 if (timestampQueryIdx >= 0) {
3249 df->vkCmdResetQueryPool(cbWrapper->cb, timestampQueryPool, uint32_t(timestampQueryIdx), 2);
3250 // record timestamp at the start of the command buffer
3251 df->vkCmdWriteTimestamp(cbWrapper->cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
3252 timestampQueryPool, uint32_t(timestampQueryIdx));
3253 ofr.timestampQueryIndex[currentFrameSlot] = timestampQueryIdx;
3254 }
3255 }
3256
3257 *cb = cbWrapper;
3258 return QRhi::FrameOpSuccess;
3259}
3260
3262{
3263 Q_UNUSED(flags);
3264 Q_ASSERT(ofr.active);
3265 ofr.active = false;
3266
3267 QVkCommandBuffer *cbWrapper(ofr.cbWrapper[currentFrameSlot]);
3269
3270 const bool readbacksPending = !activeTextureReadbacks.isEmpty() || !activeBufferReadbacks.isEmpty();
3271
3272 // record the end timestamp, when enabled; results are read back in the
3273 // next beginOffscreenFrame for this slot, after the fence wait.
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));
3277 }
3278
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;
3286 }
3287 }
3288
3289 QRhi::FrameOpResult submitres = endAndSubmitPrimaryCommandBuffer(cbWrapper->cb, ofr.cmdFence[currentFrameSlot], nullptr, nullptr);
3290 if (submitres != QRhi::FrameOpSuccess)
3291 return submitres;
3292
3293 ofr.cmdFenceWaitable[currentFrameSlot] = true;
3294
3295 // Synchronously wait only when readbacks were scheduled.
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;
3300
3301 // Here we know that executing the host-side reads for this (or any
3302 // previous) frame is safe since we waited for completion above.
3304 }
3305
3306 currentFrameSlot = (currentFrameSlot + 1) % QVK_FRAMES_IN_FLIGHT;
3307
3308 return QRhi::FrameOpSuccess;
3309}
3310
3312{
3313 QVkSwapChain *swapChainD = nullptr;
3314 QVkSwapChain::FrameResources *swapChainFrameRes = nullptr;
3315 if (inFrame) {
3316 // There is either a swapchain or an offscreen frame on-going.
3317 // End command recording and submit what we have.
3318 VkCommandBuffer cb;
3319 if (ofr.active) {
3320 Q_ASSERT(!currentSwapChain);
3321 QVkCommandBuffer *cbWrapper(ofr.cbWrapper[currentFrameSlot]);
3322 Q_ASSERT(cbWrapper->recordingPass == QVkCommandBuffer::NoPass);
3324 cbWrapper->resetCommands();
3325 cb = cbWrapper->cb;
3326 } else {
3327 Q_ASSERT(currentSwapChain);
3328 Q_ASSERT(currentSwapChain->cbWrapper.recordingPass == QVkCommandBuffer::NoPass);
3329 swapChainD = currentSwapChain;
3330 swapChainFrameRes = &swapChainD->frameRes[swapChainD->bufferCount > 1 ? currentFrameSlot : 0];
3331 recordPrimaryCommandBuffer(&swapChainD->cbWrapper);
3332 swapChainD->cbWrapper.resetCommands();
3333 cb = swapChainD->cbWrapper.cb;
3334 }
3335 VkSemaphore *waitSem = swapChainFrameRes && swapChainFrameRes->imageSemWaitable
3336 ? &swapChainFrameRes->imageSem
3337 : nullptr;
3338 QRhi::FrameOpResult submitres = endAndSubmitPrimaryCommandBuffer(cb, VK_NULL_HANDLE, waitSem, nullptr);
3339 if (submitres != QRhi::FrameOpSuccess)
3340 return submitres;
3341 if (waitSem)
3342 swapChainFrameRes->imageSemWaitable = false;
3343 }
3344
3345 df->vkQueueWaitIdle(gfxQueue);
3346
3347 if (inFrame) {
3348 // The current frame slot's command pool needs to be reset.
3350 // Allocate and begin recording on a new command buffer.
3351 if (ofr.active) {
3352 startPrimaryCommandBuffer(&ofr.cbWrapper[currentFrameSlot]->cb);
3353 } else {
3354 startPrimaryCommandBuffer(&swapChainFrameRes->cmdBuf);
3355 swapChainD->cbWrapper.cb = swapChainFrameRes->cmdBuf;
3356 }
3357 }
3358
3361
3362 return QRhi::FrameOpSuccess;
3363}
3364
3366{
3368 u.layout = 0; // unused with buffers
3369 u.access = int(bufUsage.access);
3370 u.stage = int(bufUsage.stage);
3371 return u;
3372}
3373
3375{
3377 u.layout = texUsage.layout;
3378 u.access = int(texUsage.access);
3379 u.stage = int(texUsage.stage);
3380 return u;
3381}
3382
3384{
3385 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QVkTexture, QVkRenderBuffer>(rtD->description(), rtD->d.currentResIdList))
3386 rtD->create();
3387
3388 rtD->lastActiveFrameSlot = currentFrameSlot;
3389 rtD->d.rp->lastActiveFrameSlot = currentFrameSlot;
3390 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
3391 for (auto it = rtD->m_desc.cbeginColorAttachments(), itEnd = rtD->m_desc.cendColorAttachments(); it != itEnd; ++it) {
3392 QVkTexture *texD = QRHI_RES(QVkTexture, it->texture());
3393 QVkTexture *resolveTexD = QRHI_RES(QVkTexture, it->resolveTexture());
3394 QVkRenderBuffer *rbD = QRHI_RES(QVkRenderBuffer, it->renderBuffer());
3395 if (texD) {
3396 trackedRegisterTexture(&passResTracker, texD,
3399 texD->lastActiveFrameSlot = currentFrameSlot;
3400 } else if (rbD) {
3401 // Won't register rbD->backingTexture because it cannot be used for
3402 // anything in a renderpass, its use makes only sense in
3403 // combination with a resolveTexture.
3404 rbD->lastActiveFrameSlot = currentFrameSlot;
3405 }
3406 if (resolveTexD) {
3407 trackedRegisterTexture(&passResTracker, resolveTexD,
3410 resolveTexD->lastActiveFrameSlot = currentFrameSlot;
3411 }
3412 }
3413 if (rtD->m_desc.depthStencilBuffer()) {
3414 QVkRenderBuffer *rbD = QRHI_RES(QVkRenderBuffer, rtD->m_desc.depthStencilBuffer());
3415 Q_ASSERT(rbD->m_type == QRhiRenderBuffer::DepthStencil);
3416 // Textures are taken care of by the resource tracking but that
3417 // excludes the (content-wise) throwaway depth-stencil buffer, so
3418 // issue an explicit barrier to avoid a write-after-write hazard.
3420 rbD->lastActiveFrameSlot = currentFrameSlot;
3421 }
3422 if (rtD->m_desc.depthTexture()) {
3423 QVkTexture *depthTexD = QRHI_RES(QVkTexture, rtD->m_desc.depthTexture());
3424 trackedRegisterTexture(&passResTracker, depthTexD,
3427 depthTexD->lastActiveFrameSlot = currentFrameSlot;
3428 }
3429 if (rtD->m_desc.depthResolveTexture()) {
3430 QVkTexture *depthResolveTexD = QRHI_RES(QVkTexture, rtD->m_desc.depthResolveTexture());
3431 trackedRegisterTexture(&passResTracker, depthResolveTexD,
3434 depthResolveTexD->lastActiveFrameSlot = currentFrameSlot;
3435 }
3436 if (rtD->m_desc.shadingRateMap()) {
3437 QVkTexture *texD = QRHI_RES(QVkShadingRateMap, rtD->m_desc.shadingRateMap())->texture;
3438 trackedRegisterTexture(&passResTracker, texD,
3441 texD->lastActiveFrameSlot = currentFrameSlot;
3442 }
3443}
3444
3445void QRhiVulkan::resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
3446{
3447 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3449
3450 enqueueResourceUpdates(cbD, resourceUpdates);
3451}
3452
3454{
3455 VkCommandBuffer secondaryCb;
3456
3457 if (!freeSecondaryCbs[currentFrameSlot].isEmpty()) {
3458 secondaryCb = freeSecondaryCbs[currentFrameSlot].last();
3459 freeSecondaryCbs[currentFrameSlot].removeLast();
3460 } else {
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;
3466
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;
3471 }
3472 }
3473
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;
3480 if (rtD) {
3481 cmdBufInheritInfo.renderPass = rtD->rp->rp;
3482 cmdBufInheritInfo.framebuffer = rtD->fb;
3483 }
3484 cmdBufBeginInfo.pInheritanceInfo = &cmdBufInheritInfo;
3485
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;
3490 }
3491
3492 return secondaryCb;
3493}
3494
3496{
3497 VkResult err = df->vkEndCommandBuffer(cb);
3498 if (err != VK_SUCCESS)
3499 qWarning("Failed to end secondary command buffer: %d", err);
3500
3501 QVkCommandBuffer::Command &cmd(cbD->commands.get());
3503 cmd.args.executeSecondary.cb = cb;
3504
3507 e.lastActiveFrameSlot = currentFrameSlot;
3508 e.secondaryCommandBuffer.cb = cb;
3509 releaseQueue.append(e);
3510}
3511
3512void QRhiVulkan::beginPass(QRhiCommandBuffer *cb,
3513 QRhiRenderTarget *rt,
3514 const QColor &colorClearValue,
3515 const QRhiDepthStencilClearValue &depthStencilClearValue,
3516 QRhiResourceUpdateBatch *resourceUpdates,
3517 QRhiCommandBuffer::BeginPassFlags flags)
3518{
3519 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3521
3522 if (resourceUpdates)
3523 enqueueResourceUpdates(cbD, resourceUpdates);
3524
3525 // Insert a TransitionPassResources into the command stream, pointing to
3526 // the tracker this pass is going to use. That's how we generate the
3527 // barriers later during recording the real VkCommandBuffer, right before
3528 // the vkCmdBeginRenderPass.
3530
3531 QVkRenderTargetData *rtD = nullptr;
3532 switch (rt->resourceType()) {
3533 case QRhiResource::SwapChainRenderTarget:
3534 rtD = &QRHI_RES(QVkSwapChainRenderTarget, rt)->d;
3535 rtD->rp->lastActiveFrameSlot = currentFrameSlot;
3536 Q_ASSERT(currentSwapChain);
3537 currentSwapChain->imageRes[currentSwapChain->currentImageIndex].lastUse =
3539 if (currentSwapChain->shadingRateMapView) {
3541 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
3542 trackedRegisterTexture(&passResTracker, texD,
3545 texD->lastActiveFrameSlot = currentFrameSlot;
3546 }
3547 break;
3548 case QRhiResource::TextureRenderTarget:
3549 {
3551 rtD = &rtTex->d;
3553 }
3554 break;
3555 default:
3556 Q_UNREACHABLE();
3557 break;
3558 }
3559
3561 cbD->passUsesSecondaryCb = flags.testFlag(QRhiCommandBuffer::ExternalContent);
3562 cbD->currentTarget = rt;
3563
3564 // No copy operations or image layout transitions allowed after this point
3565 // (up until endPass) as we are going to begin the renderpass.
3566
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());
3573
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);
3578 });
3579
3580 QVarLengthArray<VkClearValue, (QVkRenderTargetData::MAX_COLOR_ATTACHMENTS + 1) * 2 + 1> cvs;
3581 if (rpHasAnyClearOp) {
3582 for (int i = 0; i < rtD->colorAttCount; ++i) {
3583 VkClearValue cv = {};
3584 cv.color = { { colorClearValue.redF(), colorClearValue.greenF(), colorClearValue.blueF(),
3585 colorClearValue.alphaF() } };
3586 cvs.append(cv);
3587 }
3588 for (int i = 0; i < rtD->dsAttCount; ++i) {
3589 VkClearValue cv = {};
3590 cv.depthStencil = { depthStencilClearValue.depthClearValue(), depthStencilClearValue.stencilClearValue() };
3591 cvs.append(cv);
3592 }
3593 for (int i = 0; i < rtD->resolveAttCount; ++i) {
3594 VkClearValue cv = {};
3595 cv.color = { { colorClearValue.redF(), colorClearValue.greenF(), colorClearValue.blueF(),
3596 colorClearValue.alphaF() } };
3597 cvs.append(cv);
3598 }
3599 for (int i = 0; i < rtD->dsResolveAttCount; ++i) {
3600 VkClearValue cv = {};
3601 cv.depthStencil = { depthStencilClearValue.depthClearValue(), depthStencilClearValue.stencilClearValue() };
3602 cvs.append(cv);
3603 }
3604 for (int i = 0; i < rtD->shadingRateAttCount; ++i) {
3605 VkClearValue cv = {};
3606 cv.color = { { 0.0f, 0.0f, 0.0f, 0.0f } };
3607 cvs.append(cv);
3608 }
3609 }
3610 Q_ASSERT(!rpHasAnyClearOp || cvs.size() == rtD->rp->attDescs.size());
3611 rpBeginInfo.clearValueCount = uint32_t(cvs.size());
3612
3613 QVkCommandBuffer::Command &cmd(cbD->commands.get());
3615 cmd.args.beginRenderPass.desc = rpBeginInfo;
3616 cmd.args.beginRenderPass.clearValueIndex = cbD->pools.clearValue.size();
3617 cmd.args.beginRenderPass.useSecondaryCb = cbD->passUsesSecondaryCb;
3618 cbD->pools.clearValue.append(cvs.constData(), cvs.size());
3619
3620 if (cbD->passUsesSecondaryCb)
3621 cbD->activeSecondaryCbStack.append(startSecondaryCommandBuffer(rtD));
3622
3623 if (cbD->hasShadingRateSet) {
3624 QVkCommandBuffer::Command &rateCmd(cbD->commands.get());
3626 rateCmd.args.setShadingRate.w = 1;
3627 rateCmd.args.setShadingRate.h = 1;
3628 }
3629
3631}
3632
3633void QRhiVulkan::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
3634{
3635 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3637
3638 if (cbD->passUsesSecondaryCb) {
3639 VkCommandBuffer secondaryCb = cbD->activeSecondaryCbStack.last();
3640 cbD->activeSecondaryCbStack.removeLast();
3641 endAndEnqueueSecondaryCommandBuffer(secondaryCb, cbD);
3642 }
3643
3644 QVkCommandBuffer::Command &cmd(cbD->commands.get());
3646
3648 cbD->currentTarget = nullptr;
3649
3650 if (resourceUpdates)
3651 enqueueResourceUpdates(cbD, resourceUpdates);
3652}
3653
3654void QRhiVulkan::beginComputePass(QRhiCommandBuffer *cb,
3655 QRhiResourceUpdateBatch *resourceUpdates,
3656 QRhiCommandBuffer::BeginPassFlags flags)
3657{
3658 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3660
3661 if (resourceUpdates)
3662 enqueueResourceUpdates(cbD, resourceUpdates);
3663
3665
3667 cbD->passUsesSecondaryCb = flags.testFlag(QRhiCommandBuffer::ExternalContent);
3668
3669 cbD->computePassState.reset();
3670
3671 if (cbD->passUsesSecondaryCb)
3672 cbD->activeSecondaryCbStack.append(startSecondaryCommandBuffer());
3673
3675}
3676
3677void QRhiVulkan::endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
3678{
3679 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3681
3682 if (cbD->passUsesSecondaryCb) {
3683 VkCommandBuffer secondaryCb = cbD->activeSecondaryCbStack.last();
3684 cbD->activeSecondaryCbStack.removeLast();
3685 endAndEnqueueSecondaryCommandBuffer(secondaryCb, cbD);
3686 }
3687
3689
3690 if (resourceUpdates)
3691 enqueueResourceUpdates(cbD, resourceUpdates);
3692}
3693
3694void QRhiVulkan::setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps)
3695{
3697 Q_ASSERT(psD->pipeline);
3698 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3700
3701 if (cbD->currentComputePipeline != ps || cbD->currentPipelineGeneration != psD->generation) {
3702 if (cbD->passUsesSecondaryCb) {
3703 df->vkCmdBindPipeline(cbD->activeSecondaryCbStack.last(), VK_PIPELINE_BIND_POINT_COMPUTE, psD->pipeline);
3704 } else {
3705 QVkCommandBuffer::Command &cmd(cbD->commands.get());
3707 cmd.args.bindPipeline.bindPoint = VK_PIPELINE_BIND_POINT_COMPUTE;
3708 cmd.args.bindPipeline.pipeline = psD->pipeline;
3709 }
3710
3711 cbD->currentGraphicsPipeline = nullptr;
3712 cbD->currentComputePipeline = ps;
3714 }
3715
3716 psD->lastActiveFrameSlot = currentFrameSlot;
3717}
3718
3719template<typename T>
3720inline void qrhivk_accumulateComputeResource(T *writtenResources, QRhiResource *resource,
3721 QRhiShaderResourceBinding::Type bindingType,
3722 int loadTypeVal, int storeTypeVal, int loadStoreTypeVal)
3723{
3724 VkAccessFlags access = 0;
3725 if (bindingType == loadTypeVal) {
3726 access = VK_ACCESS_SHADER_READ_BIT;
3727 } else {
3728 access = VK_ACCESS_SHADER_WRITE_BIT;
3729 if (bindingType == loadStoreTypeVal)
3730 access |= VK_ACCESS_SHADER_READ_BIT;
3731 }
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 });
3737}
3738
3739static inline bool accessIsWrite(VkAccessFlags access)
3740{
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;
3747}
3748
3749// When there are multiple dispatches, read-after-write and write-after-write
3750// need a barrier. Updates writtenResources, so call once per dispatch.
3752 QVarLengthArray<VkImageMemoryBarrier, 8> *imageBarriers,
3753 QVarLengthArray<VkBufferMemoryBarrier, 8> *bufferBarriers)
3754{
3755 if (!cbD->currentComputeSrb)
3756 return;
3757
3758 // The key in the writtenResources map indicates that the resource was
3759 // written in a previous dispatch, whereas the value accumulates the
3760 // access mask in the current one.
3761 for (auto [res, accessAndIsNewFlag] : cbD->computePassState.writtenResources)
3762 accessAndIsNewFlag = { 0, false }; // note: accessAndIsNewFlag is a reference
3763
3764 QVkShaderResourceBindings *srbD = QRHI_RES(QVkShaderResourceBindings, cbD->currentComputeSrb);
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,
3772 b->simage().tex,
3773 b->type(),
3774 QRhiShaderResourceBinding::ImageLoad,
3775 QRhiShaderResourceBinding::ImageStore,
3776 QRhiShaderResourceBinding::ImageLoadStore);
3777 break;
3778 case QRhiShaderResourceBinding::BufferLoad:
3779 case QRhiShaderResourceBinding::BufferStore:
3780 case QRhiShaderResourceBinding::BufferLoadStore:
3781 qrhivk_accumulateComputeResource(&cbD->computePassState.writtenResources,
3782 b->sbuf().buf,
3783 b->type(),
3784 QRhiShaderResourceBinding::BufferLoad,
3785 QRhiShaderResourceBinding::BufferStore,
3786 QRhiShaderResourceBinding::BufferLoadStore);
3787 break;
3788 default:
3789 break;
3790 }
3791 }
3792
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) {
3798 QVkTexture *texD = QRHI_RES(QVkTexture, it.key());
3799 VkImageMemoryBarrier barrier = {};
3800 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
3801 barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
3802 // won't care about subresources, pretend the whole resource was written
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);
3813 } else {
3814 QVkBuffer *bufD = QRHI_RES(QVkBuffer, it.key());
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);
3824 }
3825 }
3826 // Anything that was previously written, but is only read now, can be
3827 // removed from the written list (because that previous write got a
3828 // corresponding barrier now).
3829 if (accessInThisDispatch == VK_ACCESS_SHADER_READ_BIT)
3830 it = cbD->computePassState.writtenResources.erase(it);
3831 else
3832 ++it;
3833 }
3834}
3835
3836void QRhiVulkan::dispatch(QRhiCommandBuffer *cb, int x, int y, int z)
3837{
3838 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3840
3841 QVarLengthArray<VkImageMemoryBarrier, 8> imageBarriers;
3842 QVarLengthArray<VkBufferMemoryBarrier, 8> bufferBarriers;
3843 collectComputeBarriers(cbD, &imageBarriers, &bufferBarriers);
3844
3845 if (cbD->passUsesSecondaryCb) {
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,
3849 0, 0, nullptr,
3850 bufferBarriers.size(), bufferBarriers.isEmpty() ? nullptr : bufferBarriers.constData(),
3851 imageBarriers.size(), imageBarriers.isEmpty() ? nullptr : imageBarriers.constData());
3852 }
3853 df->vkCmdDispatch(secondaryCb, uint32_t(x), uint32_t(y), uint32_t(z));
3854 } else {
3855 if (!imageBarriers.isEmpty() || !bufferBarriers.isEmpty()) {
3856 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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());
3866 }
3867 QVkCommandBuffer::Command &cmd(cbD->commands.get());
3869 cmd.args.dispatch.x = x;
3870 cmd.args.dispatch.y = y;
3871 cmd.args.dispatch.z = z;
3872 }
3873}
3874
3875void QRhiVulkan::drawIndirectCount(QRhiCommandBuffer *cb,
3876 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
3877 QRhiBuffer *countBuffer, quint32 countBufferOffset,
3878 quint32 maxDrawCount, quint32 stride)
3879{
3880 if (!caps.drawIndirectCount) {
3881 qWarning("drawIndirectCount called but the DrawIndirectCount feature is not supported");
3882 return;
3883 }
3884
3885 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3887 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
3888
3889 QVkBuffer *indirectBufD = QRHI_RES(QVkBuffer, indirectBuffer);
3890 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
3891 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
3892 executeBufferHostWritesForSlot(indirectBufD, currentFrameSlot);
3893 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3894 trackedRegisterBuffer(&passResTracker, indirectBufD, indirectBufSlot,
3897 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
3898
3899 QVkBuffer *countBufD = QRHI_RES(QVkBuffer, countBuffer);
3900 countBufD->lastActiveFrameSlot = currentFrameSlot;
3901 if (countBufD->m_type == QRhiBuffer::Dynamic)
3902 executeBufferHostWritesForSlot(countBufD, currentFrameSlot);
3903 const int countBufSlot = countBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3904 trackedRegisterBuffer(&passResTracker, countBufD, countBufSlot,
3907 VkBuffer countBufVk = countBufD->buffers[countBufSlot];
3908
3909 if (cbD->passUsesSecondaryCb) {
3910#ifdef VK_VERSION_1_2
3911 vkCmdDrawIndirectCount(cbD->activeSecondaryCbStack.last(),
3912 indirectBufVk, indirectBufferOffset,
3913 countBufVk, countBufferOffset,
3914 maxDrawCount, stride);
3915#endif
3916 } else {
3917 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
3925 }
3926}
3927
3928void QRhiVulkan::drawIndexedIndirectCount(QRhiCommandBuffer *cb,
3929 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
3930 QRhiBuffer *countBuffer, quint32 countBufferOffset,
3931 quint32 maxDrawCount, quint32 stride)
3932{
3933 if (!caps.drawIndirectCount) {
3934 qWarning("drawIndexedIndirectCount called but the DrawIndirectCount feature is not supported");
3935 return;
3936 }
3937
3938 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3940 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
3941
3942 QVkBuffer *indirectBufD = QRHI_RES(QVkBuffer, indirectBuffer);
3943 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
3944 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
3945 executeBufferHostWritesForSlot(indirectBufD, currentFrameSlot);
3946 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3947 trackedRegisterBuffer(&passResTracker, indirectBufD, indirectBufSlot,
3950 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
3951
3952 QVkBuffer *countBufD = QRHI_RES(QVkBuffer, countBuffer);
3953 countBufD->lastActiveFrameSlot = currentFrameSlot;
3954 if (countBufD->m_type == QRhiBuffer::Dynamic)
3955 executeBufferHostWritesForSlot(countBufD, currentFrameSlot);
3956 const int countBufSlot = countBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3957 trackedRegisterBuffer(&passResTracker, countBufD, countBufSlot,
3960 VkBuffer countBufVk = countBufD->buffers[countBufSlot];
3961
3962 if (cbD->passUsesSecondaryCb) {
3963#ifdef VK_VERSION_1_2
3964 vkCmdDrawIndexedIndirectCount(cbD->activeSecondaryCbStack.last(),
3965 indirectBufVk, indirectBufferOffset,
3966 countBufVk, countBufferOffset,
3967 maxDrawCount, stride);
3968#endif
3969 } else {
3970 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
3978 }
3979}
3980
3981void QRhiVulkan::dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
3982 quint32 indirectBufferOffset)
3983{
3984 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
3986 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
3987
3988 QVkBuffer *indirectBufD = QRHI_RES(QVkBuffer, indirectBuffer);
3989 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
3990 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
3991 executeBufferHostWritesForSlot(indirectBufD, currentFrameSlot);
3992 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
3993 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
3994
3995 // Make a preceding write visible to the INDIRECT_COMMAND_READ at the
3996 // DRAW_INDIRECT stage. The write may have happened in an earlier dispatch
3997 // in this pass, or before the pass.
3998 VkAccessFlags indirectSrcAccess = 0;
3999 VkPipelineStageFlags indirectSrcStage = 0;
4000
4001 // Sample before collectComputeBarriers(), which drops entries for anything
4002 // the upcoming dispatch only reads - including this buffer, if the
4003 // consuming shader also binds it as a storage buffer.
4004 if (cbD->computePassState.writtenResources.contains(indirectBufD)) {
4005 indirectSrcAccess |= VK_ACCESS_SHADER_WRITE_BIT;
4006 indirectSrcStage |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
4007 }
4008
4009 // A write before the pass is normally covered by registering the indirect
4010 // usage with the tracker. That is not possible when the buffer is also
4011 // bound as a storage buffer here - which is how the arguments get generated
4012 // on the GPU - because registerBuffer() rejects a second, differing access.
4013 // Synchronize against the pre-pass state instead.
4014 const auto trackedIt = passResTracker.buffers().find(indirectBufD);
4015 if (trackedIt != passResTracker.buffers().cend()
4016 && trackedIt->second.access != QRhiPassResourceTracker::BufIndirectDraw)
4017 {
4018 indirectSrcAccess |= VkAccessFlags(trackedIt->second.stateAtPassBegin.access);
4019 indirectSrcStage |= VkPipelineStageFlags(trackedIt->second.stateAtPassBegin.stage);
4020 // So that a later write to the buffer waits for the indirect read.
4021 QVkBuffer::UsageState &u(indirectBufD->usageState[indirectBufSlot]);
4022 u.access |= VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
4023 u.stage |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
4024 } else {
4025 trackedRegisterBuffer(&passResTracker, indirectBufD, indirectBufSlot,
4028 }
4029
4030 QVarLengthArray<VkImageMemoryBarrier, 8> imageBarriers;
4031 QVarLengthArray<VkBufferMemoryBarrier, 8> bufferBarriers;
4032 collectComputeBarriers(cbD, &imageBarriers, &bufferBarriers);
4033
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;
4044 }
4045
4046 if (cbD->passUsesSecondaryCb) {
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,
4050 0, 0, nullptr,
4051 bufferBarriers.size(), bufferBarriers.isEmpty() ? nullptr : bufferBarriers.constData(),
4052 imageBarriers.size(), imageBarriers.isEmpty() ? nullptr : imageBarriers.constData());
4053 }
4054 if (needsIndirectBarrier) {
4055 df->vkCmdPipelineBarrier(secondaryCb, indirectSrcStage, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT,
4056 0, 0, nullptr,
4057 1, &indirectBarrier,
4058 0, nullptr);
4059 }
4060 df->vkCmdDispatchIndirect(secondaryCb, indirectBufVk, VkDeviceSize(indirectBufferOffset));
4061 } else {
4062 if (!imageBarriers.isEmpty() || !bufferBarriers.isEmpty()) {
4063 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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());
4073 }
4074 if (needsIndirectBarrier) {
4075 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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);
4082 }
4083 QVkCommandBuffer::Command &cmd(cbD->commands.get());
4085 cmd.args.dispatchIndirect.indirectBuffer = indirectBufVk;
4086 cmd.args.dispatchIndirect.indirectBufferOffset = VkDeviceSize(indirectBufferOffset);
4087 }
4088}
4089
4090VkShaderModule QRhiVulkan::createShader(const QByteArray &spirv)
4091{
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;
4101 }
4102 return shaderModule;
4103}
4104
4105bool QRhiVulkan::ensurePipelineCache(const void *initialData, size_t initialDataSize)
4106{
4107 if (pipelineCache)
4108 return true;
4109
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);
4117 return false;
4118 }
4119 return true;
4120}
4121
4122void QRhiVulkan::updateShaderResourceBindings(QRhiShaderResourceBindings *srb)
4123{
4125
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;
4131
4132 for (int i = 0, ie = srbD->sortedBindings.size(); i != ie; ++i) {
4133 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings.at(i));
4134 QVkShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[currentFrameSlot][i]);
4135
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;
4141
4142 int bufferInfoIndex = -1;
4143 int imageInfoIndex = -1;
4144
4145 switch (b->type()) {
4146 case QRhiShaderResourceBinding::UniformBuffer:
4147 {
4148 writeInfo.descriptorType = b->ubuf().hasDynamicOffset ? VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC
4149 : VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
4150 QRhiBuffer *buf = b->ubuf().buf;
4151 QVkBuffer *bufD = QRHI_RES(QVkBuffer, buf);
4152 bd.ubuf.id = bufD->m_id;
4153 bd.ubuf.generation = bufD->generation;
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;
4158 // be nice and assert when we know the vulkan device would die a horrible death due to non-aligned reads
4159 Q_ASSERT(aligned(bufInfo.offset, ubufAlign) == bufInfo.offset);
4160 bufferInfoIndex = bufferInfos.size();
4161 bufferInfos.append(bufInfo);
4162 }
4163 break;
4164 case QRhiShaderResourceBinding::SampledTexture:
4165 {
4166 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
4167 writeInfo.descriptorCount = data->count(); // arrays of combined image samplers are supported
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) {
4172 QVkTexture *texD = QRHI_RES(QVkTexture, data->texSamplers[elem].tex);
4173 QVkSampler *samplerD = QRHI_RES(QVkSampler, data->texSamplers[elem].sampler);
4174 bd.stex.d[elem].texId = texD->m_id;
4175 bd.stex.d[elem].texGeneration = texD->generation;
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;
4181 }
4182 imageInfoIndex = imageInfos.size();
4183 imageInfos.append(imageInfo);
4184 }
4185 break;
4186 case QRhiShaderResourceBinding::Texture:
4187 {
4188 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
4189 writeInfo.descriptorCount = data->count(); // arrays of (separate) images are supported
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) {
4194 QVkTexture *texD = QRHI_RES(QVkTexture, data->texSamplers[elem].tex);
4195 bd.stex.d[elem].texId = texD->m_id;
4196 bd.stex.d[elem].texGeneration = texD->generation;
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;
4202 }
4203 imageInfoIndex = imageInfos.size();
4204 imageInfos.append(imageInfo);
4205 }
4206 break;
4207 case QRhiShaderResourceBinding::Sampler:
4208 {
4209 QVkSampler *samplerD = QRHI_RES(QVkSampler, b->stex().texSamplers[0].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;
4215 bd.stex.d[0].samplerGeneration = samplerD->generation;
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);
4222 }
4223 break;
4224 case QRhiShaderResourceBinding::ImageLoad:
4225 case QRhiShaderResourceBinding::ImageStore:
4226 case QRhiShaderResourceBinding::ImageLoadStore:
4227 {
4228 QVkTexture *texD = QRHI_RES(QVkTexture, b->simage().tex);
4229 VkImageView view = texD->perLevelImageViewForLoadStore(b->simage().level);
4230 if (view) {
4231 writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
4232 bd.simage.id = texD->m_id;
4233 bd.simage.generation = texD->generation;
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);
4240 }
4241 }
4242 break;
4243 case QRhiShaderResourceBinding::BufferLoad:
4244 case QRhiShaderResourceBinding::BufferStore:
4245 case QRhiShaderResourceBinding::BufferLoadStore:
4246 {
4247 QVkBuffer *bufD = QRHI_RES(QVkBuffer, b->sbuf().buf);
4248 writeInfo.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
4249 bd.sbuf.id = bufD->m_id;
4250 bd.sbuf.generation = bufD->generation;
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);
4257 }
4258 break;
4259 default:
4260 continue;
4261 }
4262
4263 writeInfos.append(writeInfo);
4264 infoIndices.append({ bufferInfoIndex, imageInfoIndex });
4265 }
4266
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();
4274 }
4275
4276 df->vkUpdateDescriptorSets(dev, uint32_t(writeInfos.size()), writeInfos.constData(), 0, nullptr);
4277}
4278
4280 VkAccessFlags access, VkPipelineStageFlags stage)
4281{
4283 Q_ASSERT(access && stage);
4284 QVkBuffer::UsageState &s(bufD->usageState[slot]);
4285 if (!s.stage) {
4286 s.access = access;
4287 s.stage = stage;
4288 return;
4289 }
4290
4291 if (s.access == access && s.stage == stage) {
4292 // No need to flood with unnecessary read-after-read barriers.
4293 // Write-after-write is a different matter, however.
4294 if (!accessIsWrite(access))
4295 return;
4296 }
4297
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;
4306
4307 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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);
4314
4315 s.access = access;
4316 s.stage = stage;
4317}
4318
4320 VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stage)
4321{
4323 Q_ASSERT(layout && access && stage);
4324 QVkTexture::UsageState &s(texD->usageState);
4325 if (s.access == access && s.stage == stage && s.layout == layout) {
4326 if (!accessIsWrite(access))
4327 return;
4328 }
4329
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; // new textures have this set to UNDEFINED
4338 barrier.newLayout = layout;
4339 barrier.srcAccessMask = s.access; // may be 0 but that's fine
4340 barrier.dstAccessMask = access;
4341 barrier.image = texD->image;
4342
4343 VkPipelineStageFlags srcStage = s.stage;
4344 // stage mask cannot be 0
4345 if (!srcStage)
4346 srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
4347
4348 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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);
4355
4356 s.layout = layout;
4357 s.access = access;
4358 s.stage = stage;
4359}
4360
4362{
4364
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;
4378
4379 const VkPipelineStageFlags stages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT
4380 | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
4381
4382 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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);
4389}
4390
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)
4397{
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;
4411
4412 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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);
4419}
4420
4421VkDeviceSize QRhiVulkan::subresUploadByteSize(const QRhiTextureSubresourceUploadDescription &subresDesc) const
4422{
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);
4428 return size;
4429}
4430
4431void QRhiVulkan::prepareUploadSubres(QVkTexture *texD, int layer, int level,
4432 const QRhiTextureSubresourceUploadDescription &subresDesc,
4433 size_t *curOfs, void *mp,
4434 BufferImageCopyList *copyInfos)
4435{
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);
4441
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;
4449 if (is3D)
4450 copyInfo.imageOffset.z = uint32_t(layer);
4451 if (is1D)
4452 copyInfo.imageOffset.y = uint32_t(layer);
4453
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();
4461 // Scanlines in QImage are 4 byte aligned so bpl must
4462 // be taken into account for bufferRowLength.
4463 int bpc = qMax(1, image.depth() / 8);
4464 // this is in pixels, not bytes, to make it more complicated...
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()) {
4473 // No need to make a QImage copy here, can copy from the source
4474 // QImage into staging directly.
4475 src = image.constBits() + sy * image.bytesPerLine() + sx * bpc;
4476 copySizeBytes = size.height() * image.bytesPerLine();
4477 } else {
4478 image = image.copy(sx, sy, size.width(), size.height());
4479 src = image.constBits();
4480 // The staging buffer gets the slice only. The rest of the
4481 // space reserved for this mip will be unused.
4482 copySizeBytes = image.sizeInBytes();
4483 bpc = qMax(1, image.depth() / 8);
4484 copyInfo.bufferRowLength = uint32_t(image.bytesPerLine() / bpc);
4485 }
4486 } else {
4487 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
4488 }
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,
4503 rawData.size());
4504 if (size.height() == 0)
4505 return;
4506 const int w = size.width();
4507 const int h = size.height();
4508 QSize blockDim;
4509 compressedFormatInfo(texD->m_format, QSize(w, h), nullptr, nullptr, &blockDim);
4510 // x and y must be multiples of the block width and height
4511 copyInfo.imageOffset.x = aligned(dp.x(), blockDim.width());
4512 copyInfo.imageOffset.y = aligned(dp.y(), blockDim.height());
4513 // width and height must be multiples of the block width and height
4514 // or x + width and y + height must equal the subresource width and 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);
4525
4526 quint32 bytesPerPixel = 0;
4527 textureFormatInfo(texD->m_format, size, nullptr, nullptr, &bytesPerPixel);
4528 if (subresDesc.dataStride() && bytesPerPixel)
4529 copyInfo.bufferRowLength = subresDesc.dataStride() / bytesPerPixel;
4530
4531 size = clampedSubResourceUploadSizeForSourceData(size, subresDesc.dataStride(),
4532 bytesPerPixel, rawData.size());
4533
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);
4540 }
4541 } else {
4542 qWarning("Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
4543 }
4544
4545 if (src) {
4546 memcpy(reinterpret_cast<char *>(mp) + *curOfs, src, size_t(copySizeBytes));
4547 *curOfs += aligned(VkDeviceSize(imageSizeBytes), texbufAlign);
4548 }
4549}
4550
4552{
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();
4557}
4558
4560{
4561#ifdef VK_EXT_device_fault
4562 if (!dev || !caps.deviceFault || !vkGetDeviceFaultInfoEXT)
4563 return;
4564
4565 VkDeviceFaultCountsEXT faultCounts{};
4566 faultCounts.sType = VK_STRUCTURE_TYPE_DEVICE_FAULT_COUNTS_EXT;
4567 faultCounts.pNext = nullptr;
4568
4569 VkResult result = vkGetDeviceFaultInfoEXT(dev, &faultCounts, nullptr);
4570 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
4571 qWarning("vkGetDeviceFaultInfoEXT failed with %d", result);
4572 return;
4573 }
4574 faultCounts.vendorBinarySize = 0;
4575
4576 const auto numAddressInfos = faultCounts.addressInfoCount;
4577 const auto addressInfos
4578 = q20::make_unique_for_overwrite<VkDeviceFaultAddressInfoEXT[]>(numAddressInfos);
4579
4580 const auto numVendorInfos = faultCounts.vendorInfoCount;
4581 const auto vendorInfos
4582 = q20::make_unique_for_overwrite<VkDeviceFaultVendorInfoEXT[]>(numVendorInfos);
4583
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;
4590
4591 result = vkGetDeviceFaultInfoEXT(dev, &faultCounts, &info);
4592 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
4593 qWarning("vkGetDeviceFaultInfoEXT failed with %d", result);
4594 return;
4595 }
4596
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,
4602 desc);
4603
4604 for (uint32_t i = 0; i < faultCounts.addressInfoCount; ++i) {
4605 const auto &a = addressInfos[i];
4606 auto addressTypeString = [](const VkDeviceFaultAddressTypeEXT type) {
4607 switch (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";
4616 };
4617 };
4618 qWarning(" AddressInfo[%02u]: type=%s addr=0x%llx precision=%llu",
4619 i,
4620 addressTypeString(a.addressType),
4621 (unsigned long long)a.reportedAddress,
4622 (unsigned long long)a.addressPrecision);
4623 }
4624
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",
4628 i,
4629 (unsigned long long)v.vendorFaultCode,
4630 (unsigned long long)v.vendorFaultData,
4631 v.description);
4632 }
4633#endif // VK_EXT_device_fault
4634}
4635
4636void QRhiVulkan::enqueueResourceUpdates(QVkCommandBuffer *cbD, QRhiResourceUpdateBatch *resourceUpdates)
4637{
4639
4640 for (int opIdx = 0; opIdx < ud->activeBufferOpCount; ++opIdx) {
4641 const QRhiResourceUpdateBatchPrivate::BufferOp &u(ud->bufferOps[opIdx]);
4643 QVkBuffer *bufD = QRHI_RES(QVkBuffer, u.buf);
4644 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
4645 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
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 });
4649 }
4651 QVkBuffer *bufD = QRHI_RES(QVkBuffer, u.buf);
4652 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
4653 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
4654
4655 if (!bufD->stagingBuffers[currentFrameSlot]) {
4656 VkBufferCreateInfo bufferInfo = {};
4657 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
4658 // must cover the entire buffer - this way multiple, partial updates per frame
4659 // are supported even when the staging buffer is reused (Static)
4660 bufferInfo.size = bufD->m_size;
4661 bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
4662
4663 VmaAllocationCreateInfo allocInfo = {};
4664 allocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
4665
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());
4672 } else {
4673 qWarning("Failed to create staging buffer of size %u: %d", bufD->m_size, err);
4674 printExtraErrorInfo(err);
4675 continue;
4676 }
4677 }
4678
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);
4684 continue;
4685 }
4686
4687 trackedBufferBarrier(cbD, bufD, 0,
4688 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4689
4690 VkBufferCopy copyInfo = {};
4691 copyInfo.srcOffset = u.offset;
4692 copyInfo.dstOffset = u.offset;
4693 copyInfo.size = u.data.size();
4694
4695 QVkCommandBuffer::Command &cmd(cbD->commands.get());
4697 cmd.args.copyBuffer.src = bufD->stagingBuffers[currentFrameSlot];
4698 cmd.args.copyBuffer.dst = bufD->buffers[0];
4699 cmd.args.copyBuffer.desc = copyInfo;
4700
4701 // Where's the barrier for read-after-write? (assuming the common case
4702 // of binding this buffer as vertex/index, or, less likely, as uniform
4703 // buffer, in a renderpass later on) That is handled by the pass
4704 // resource tracking: the appropriate pipeline barrier will be
4705 // generated and recorded right before the renderpass, that binds this
4706 // buffer in one of its commands, gets its BeginRenderPass recorded.
4707
4708 bufD->lastActiveFrameSlot = currentFrameSlot;
4709
4710 if (bufD->m_type == QRhiBuffer::Immutable) {
4713 e.lastActiveFrameSlot = currentFrameSlot;
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);
4719 }
4721 QVkBuffer *bufD = QRHI_RES(QVkBuffer, u.buf);
4722 if (bufD->m_type == QRhiBuffer::Dynamic) {
4723 executeBufferHostWritesForSlot(bufD, currentFrameSlot);
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();
4731 }
4732 if (u.result->completed)
4733 u.result->completed();
4734 } else {
4735 // Non-Dynamic buffers may not be host visible, so have to
4736 // create a readback buffer, enqueue a copy from
4737 // bufD->buffers[0] to this buffer, and then once the command
4738 // buffer completes, copy the data out of the host visible
4739 // readback buffer. Quite similar to what we do for texture
4740 // readbacks.
4741 BufferReadback readback;
4742 readback.activeFrameSlot = currentFrameSlot;
4743 readback.result = u.result;
4744 readback.byteSize = u.readSize;
4745
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;
4750
4751 VmaAllocationCreateInfo allocInfo = {};
4752 allocInfo.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
4753
4754 VmaAllocation allocation;
4755 VkResult err = vmaCreateBuffer(toVmaAllocator(allocator), &bufferInfo, &allocInfo, &readback.stagingBuf, &allocation, nullptr);
4756 if (err == VK_SUCCESS) {
4757 readback.stagingAlloc = allocation;
4758 setAllocationName(allocation, bufD->name());
4759 } else {
4760 qWarning("Failed to create readback buffer of size %u: %d", readback.byteSize, err);
4761 printExtraErrorInfo(err);
4762 continue;
4763 }
4764
4765 trackedBufferBarrier(cbD, bufD, 0, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4766
4767 VkBufferCopy copyInfo = {};
4768 copyInfo.srcOffset = u.offset;
4769 copyInfo.size = u.readSize;
4770
4771 QVkCommandBuffer::Command &cmd(cbD->commands.get());
4773 cmd.args.copyBuffer.src = bufD->buffers[0];
4774 cmd.args.copyBuffer.dst = readback.stagingBuf;
4775 cmd.args.copyBuffer.desc = copyInfo;
4776
4777 bufD->lastActiveFrameSlot = currentFrameSlot;
4778
4779 activeBufferReadbacks.append(readback);
4780 }
4782 QVkBuffer *dstD = QRHI_RES(QVkBuffer, u.buf);
4783 QVkBuffer *srcD = QRHI_RES(QVkBuffer, u.src);
4784 Q_ASSERT(dstD->m_type != QRhiBuffer::Dynamic && srcD->m_type != QRhiBuffer::Dynamic);
4785
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);
4788
4789 VkBufferCopy copyInfo = {};
4790 copyInfo.srcOffset = u.srcOffset;
4791 copyInfo.dstOffset = u.offset;
4792 copyInfo.size = u.readSize;
4793
4794 QVkCommandBuffer::Command &cmd(cbD->commands.get());
4796 cmd.args.copyBuffer.src = srcD->buffers[0];
4797 cmd.args.copyBuffer.dst = dstD->buffers[0];
4798 cmd.args.copyBuffer.desc = copyInfo;
4799
4800 srcD->lastActiveFrameSlot = dstD->lastActiveFrameSlot = currentFrameSlot;
4802 QVkBuffer *bufD = QRHI_RES(QVkBuffer, u.buf);
4803 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
4804
4805 trackedBufferBarrier(cbD, bufD, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4806
4807 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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();
4813
4814 bufD->lastActiveFrameSlot = currentFrameSlot;
4815 }
4816 }
4817
4818 for (int opIdx = 0; opIdx < ud->activeTextureOpCount; ++opIdx) {
4819 const QRhiResourceUpdateBatchPrivate::TextureOp &u(ud->textureOps[opIdx]);
4821 QVkTexture *utexD = QRHI_RES(QVkTexture, u.dst);
4822 // batch into a single staging buffer and a single CopyBufferToImage with multiple copyInfos
4823 VkDeviceSize stagingSize = 0;
4824 for (const auto &subres : u.subresDesc)
4825 stagingSize += subresUploadByteSize(subres.desc);
4826
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;
4832
4833 VmaAllocationCreateInfo allocInfo = {};
4834 allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
4835
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);
4842 continue;
4843 }
4844 utexD->stagingAllocations[currentFrameSlot] = allocation;
4845 setAllocationName(allocation, utexD->name());
4846
4847 BufferImageCopyList copyInfos;
4848 size_t curOfs = 0;
4849 void *mp = nullptr;
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;
4857 continue;
4858 }
4859
4860 for (const auto &subres : u.subresDesc)
4861 prepareUploadSubres(utexD, subres.layer, subres.level, subres.desc, &curOfs, mp, &copyInfos);
4862 vmaFlushAllocation(toVmaAllocator(allocator), a, 0, stagingSize);
4863 vmaUnmapMemory(toVmaAllocator(allocator), a);
4864
4865 trackedImageBarrier(cbD, utexD, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
4866 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
4867
4868 if (!copyInfos.isEmpty()) {
4869 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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());
4877 }
4878
4879 // no reuse of staging, this is intentional
4882 e.lastActiveFrameSlot = currentFrameSlot;
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);
4888
4889 // Similarly to buffers, transitioning away from DST is done later,
4890 // when a renderpass using the texture is encountered.
4891
4892 utexD->lastActiveFrameSlot = currentFrameSlot;
4894 Q_ASSERT(u.src && u.dst);
4895 if (u.src == u.dst) {
4896 qWarning("Texture copy with matching source and destination is not supported");
4897 continue;
4898 }
4899 QVkTexture *srcD = QRHI_RES(QVkTexture, u.src);
4900 QVkTexture *dstD = QRHI_RES(QVkTexture, u.dst);
4901 const bool srcIs3D = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4902 const bool dstIs3D = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4903
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;
4909
4910 region.srcOffset.x = u.desc.sourceTopLeft().x();
4911 region.srcOffset.y = u.desc.sourceTopLeft().y();
4912 if (srcIs3D)
4913 region.srcOffset.z = uint32_t(u.desc.sourceLayer());
4914
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;
4919
4920 region.dstOffset.x = u.desc.destinationTopLeft().x();
4921 region.dstOffset.y = u.desc.destinationTopLeft().y();
4922 if (dstIs3D)
4923 region.dstOffset.z = uint32_t(u.desc.destinationLayer());
4924
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;
4930
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);
4935
4936 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
4943
4944 srcD->lastActiveFrameSlot = dstD->lastActiveFrameSlot = currentFrameSlot;
4946 TextureReadback readback;
4947 readback.activeFrameSlot = currentFrameSlot;
4948 readback.desc = u.rb;
4949 readback.result = u.result;
4950
4951 QVkTexture *texD = QRHI_RES(QVkTexture, u.rb.texture());
4952 QVkSwapChain *swapChainD = nullptr;
4953 bool is3D = false;
4954 if (texD) {
4955 if (texD->samples > VK_SAMPLE_COUNT_1_BIT) {
4956 qWarning("Multisample texture cannot be read back");
4957 continue;
4958 }
4959 is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4960 if (u.rb.rect().isValid())
4961 readback.rect = u.rb.rect();
4962 else
4963 readback.rect = QRect({0, 0}, q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize));
4964 readback.format = texD->m_format;
4965 texD->lastActiveFrameSlot = currentFrameSlot;
4966 } else {
4967 Q_ASSERT(currentSwapChain);
4968 swapChainD = QRHI_RES(QVkSwapChain, currentSwapChain);
4969 if (!swapChainD->supportsReadback) {
4970 qWarning("Swapchain does not support readback");
4971 continue;
4972 }
4973 if (u.rb.rect().isValid())
4974 readback.rect = u.rb.rect();
4975 else
4976 readback.rect = QRect({0, 0}, swapChainD->pixelSize);
4977 readback.format = swapchainReadbackTextureFormat(swapChainD->colorFormat, nullptr);
4978 if (readback.format == QRhiTexture::UnknownFormat)
4979 continue;
4980
4981 // Multisample swapchains need nothing special since resolving
4982 // happens when ending a renderpass.
4983 }
4984 if (!textureFormatInfo(readback.format, readback.rect.size(), nullptr,
4985 &readback.byteSize, nullptr))
4986 continue;
4987
4988 // vkCmdCopyImageToBuffer() only accepts single-aspect regions
4989 // (unlike barriers), so a combined depth-stencil texture is
4990 // copied as two regions, each into its own densely packed plane
4991 // of the staging buffer. finishActiveReadbacks() then
4992 // interleaves the two planes into the result.
4993 const bool combinedDepthStencil = texD && isStencilTextureFormat(readback.format);
4994 // The depth aspect is copied out as VK_FORMAT_X8_D24_UNORM_PACK32
4995 // (D24S8) or VK_FORMAT_D32_SFLOAT (D32FS8), i.e. 4 bytes per
4996 // pixel either way, the stencil aspect as VK_FORMAT_S8_UINT.
4997 // Compute in 64-bit, as safety for extreme geometry that would not fit.
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);
5008 continue;
5009 }
5010
5011 // Create a host visible readback buffer.
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;
5016
5017 VmaAllocationCreateInfo allocInfo = {};
5018 allocInfo.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
5019
5020 VmaAllocation allocation;
5021 VkResult err = vmaCreateBuffer(toVmaAllocator(allocator), &bufferInfo, &allocInfo, &readback.stagingBuf, &allocation, nullptr);
5022 if (err == VK_SUCCESS) {
5023 readback.stagingAlloc = allocation;
5024 setAllocationName(allocation, texD ? texD->name() : swapChainD->name());
5025 } else {
5026 qWarning("Failed to create readback buffer of size %llu: %d", stagingByteSize, err);
5027 printExtraErrorInfo(err);
5028 continue;
5029 }
5030
5031 // Copy from the (optimal and not host visible) image into the buffer.
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();
5040 if (is3D)
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;
5045
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;
5052 }
5053 cbD->pools.bufferImageCopy.append(copyDesc);
5054 const int copyCount = cbD->pools.bufferImageCopy.size() - bufferImageCopyIndex;
5055
5056 if (texD) {
5057 trackedImageBarrier(cbD, texD, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
5058 VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
5059 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
5066 } else {
5067 // use the swapchain image
5068 QVkSwapChain::ImageResources &imageRes(swapChainD->imageRes[swapChainD->currentImageIndex]);
5069 VkImage image = imageRes.image;
5072 qWarning("Attempted to read back undefined swapchain image content, "
5073 "results are undefined. (do a render pass first)");
5074 }
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,
5079 0, 1,
5080 0, 1);
5082 }
5083
5084 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
5091 }
5092
5093 activeTextureReadbacks.append(readback);
5095 QVkTexture *utexD = QRHI_RES(QVkTexture, u.dst);
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);
5100
5101 VkImageLayout origLayout = utexD->usageState.layout;
5102 VkAccessFlags origAccess = utexD->usageState.access;
5103 VkPipelineStageFlags origStage = utexD->usageState.stage;
5104 if (!origStage)
5105 origStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
5106
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;
5111 for (int level = 1; level < int(utexD->mipLevelCount); ++level) {
5112 if (level == 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,
5117 layer, 1,
5118 level - 1, 1);
5119 } else {
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,
5124 layer, 1,
5125 level - 1, 1);
5126 }
5127
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,
5132 layer, 1,
5133 level, 1);
5134
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;
5140
5141 region.srcOffsets[1].x = qMax(1, w);
5142 region.srcOffsets[1].y = qMax(1, h);
5143 region.srcOffsets[1].z = qMax(1, depth);
5144
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;
5149
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);
5153
5154 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
5162
5163 w >>= 1;
5164 h >>= 1;
5165 depth >>= 1;
5166 }
5167
5168 if (utexD->mipLevelCount > 1) {
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,
5173 layer, 1,
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,
5179 layer, 1,
5180 int(utexD->mipLevelCount) - 1, 1);
5181 }
5182 }
5183 utexD->lastActiveFrameSlot = currentFrameSlot;
5184 }
5185 }
5186
5187 ud->free();
5188}
5189
5191{
5192 if (bufD->pendingDynamicUpdates[slot].isEmpty())
5193 return;
5194
5195 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
5196 void *p = nullptr;
5197 VmaAllocation a = toVmaAllocation(bufD->allocations[slot]);
5198 // The vmaMap/Unmap are basically a no-op when persistently mapped since it
5199 // refcounts; this is great because we don't need to care if the allocation
5200 // was created as persistently mapped or not.
5201 VkResult err = vmaMapMemory(toVmaAllocator(allocator), a, &p);
5202 if (err != VK_SUCCESS) {
5203 qWarning("Failed to map buffer: %d", err);
5204 return;
5205 }
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();
5214 }
5215 if (changeBegin < UINT32_MAX && changeBegin < changeEnd)
5216 vmaFlushAllocation(toVmaAllocator(allocator), a, changeBegin, changeEnd - changeBegin);
5217 vmaUnmapMemory(toVmaAllocator(allocator), a);
5218
5219 bufD->pendingDynamicUpdates[slot].clear();
5220}
5221
5222static void qrhivk_releaseBuffer(const QRhiVulkan::DeferredReleaseEntry &e, void *allocator)
5223{
5224 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
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]));
5227 }
5228}
5229
5230static void qrhivk_releaseRenderBuffer(const QRhiVulkan::DeferredReleaseEntry &e, VkDevice dev, QVulkanDeviceFunctions *df)
5231{
5232 df->vkDestroyImageView(dev, e.renderBuffer.imageView, nullptr);
5233 df->vkDestroyImage(dev, e.renderBuffer.image, nullptr);
5234 df->vkFreeMemory(dev, e.renderBuffer.memory, nullptr);
5235}
5236
5237static void qrhivk_releaseTexture(const QRhiVulkan::DeferredReleaseEntry &e, VkDevice dev, QVulkanDeviceFunctions *df, void *allocator)
5238{
5239 df->vkDestroyImageView(dev, e.texture.imageView, nullptr);
5240 vmaDestroyImage(toVmaAllocator(allocator), e.texture.image, toVmaAllocation(e.texture.allocation));
5241 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i)
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);
5246 }
5247}
5248
5249static void qrhivk_releaseSampler(const QRhiVulkan::DeferredReleaseEntry &e, VkDevice dev, QVulkanDeviceFunctions *df)
5250{
5251 df->vkDestroySampler(dev, e.sampler.sampler, nullptr);
5252}
5253
5255{
5256 qsizetype keepBegin = releaseQueue.size();
5257 for (qsizetype i = keepBegin - 1; i >= 0; --i) {
5258 const QRhiVulkan::DeferredReleaseEntry &e(releaseQueue[i]);
5259 if (forced || currentFrameSlot == e.lastActiveFrameSlot || e.lastActiveFrameSlot < 0) {
5260 switch (e.type) {
5262 df->vkDestroyPipeline(dev, e.pipelineState.pipeline, nullptr);
5263 df->vkDestroyPipelineLayout(dev, e.pipelineState.layout, nullptr);
5264 break;
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);
5270 }
5271 break;
5274 break;
5276 qrhivk_releaseRenderBuffer(e, dev, df);
5277 break;
5279 qrhivk_releaseTexture(e, dev, df, allocator);
5280 break;
5282 qrhivk_releaseSampler(e, dev, df);
5283 break;
5285 df->vkDestroyFramebuffer(dev, e.textureRenderTarget.fb, nullptr);
5286 for (int att = 0; att < QVkRenderTargetData::MAX_COLOR_ATTACHMENTS; ++att) {
5287 df->vkDestroyImageView(dev, e.textureRenderTarget.rtv[att], nullptr);
5288 df->vkDestroyImageView(dev, e.textureRenderTarget.resrtv[att], nullptr);
5289 }
5290 df->vkDestroyImageView(dev, e.textureRenderTarget.dsv, nullptr);
5291 df->vkDestroyImageView(dev, e.textureRenderTarget.resdsv, nullptr);
5292 df->vkDestroyImageView(dev, e.textureRenderTarget.shadingRateMapView, nullptr);
5293 break;
5295 df->vkDestroyRenderPass(dev, e.renderPass.rp, nullptr);
5296 break;
5298 vmaDestroyBuffer(toVmaAllocator(allocator), e.stagingBuffer.stagingBuffer, toVmaAllocation(e.stagingBuffer.stagingAllocation));
5299 break;
5300 case QRhiVulkan::DeferredReleaseEntry::SecondaryCommandBuffer:
5301 freeSecondaryCbs[e.lastActiveFrameSlot].append(e.secondaryCommandBuffer.cb);
5302 break;
5303 default:
5304 Q_UNREACHABLE();
5305 break;
5306 }
5307 } else if (--keepBegin != i) {
5308 releaseQueue[keepBegin] = std::move(releaseQueue[i]);
5309 }
5310 }
5311 if (keepBegin)
5312 releaseQueue.remove(0, keepBegin);
5313}
5314
5316{
5317 QVarLengthArray<std::function<void()>, 4> completedCallbacks;
5318
5319 for (int i = activeTextureReadbacks.size() - 1; i >= 0; --i) {
5320 const QRhiVulkan::TextureReadback &readback(activeTextureReadbacks[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);
5325
5326 if (isStencilTextureFormat(readback.format)) {
5327 // The staging buffer holds a densely packed 32-bit depth
5328 // plane followed by a densely packed 8-bit stencil plane (see
5329 // enqueueResourceUpdates()). Interleave them into one packed
5330 // value per pixel, in the same layout OpenGL's native
5331 // GL_UNSIGNED_INT_24_8 (D24S8) and
5332 // GL_FLOAT_32_UNSIGNED_INT_24_8_REV (D32FS8) readbacks
5333 // produce. The Metal and D3D12 backends do the same.
5334 const quint64 pixelCount =
5335 quint64(readback.rect.width()) * quint64(readback.rect.height());
5336 const quint64 depthPlaneByteSize = pixelCount * 4;
5337 QByteArray planar;
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) {
5347 // 8 bytes per pixel: the float depth, then a 32-bit
5348 // word with the stencil in its low 8 bits.
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));
5353 }
5354 } else { // D24S8
5355 // 4 bytes per pixel: depth in the upper 24 bits,
5356 // stencil in the low 8 bits.
5357 for (quint32 px = 0; px < pixelCount; ++px) {
5358 // depthPlane[px] is VK_FORMAT_X8_D24_UNORM_PACK32: depth in
5359 // the low 24 bits, upper 8 bits undefined
5360 const quint32 combined = ((depthPlane[px] & 0x00FFFFFFu) << 8) | stencilPlane[px];
5361 memcpy(dst + px * 4, &combined, sizeof(quint32));
5362 }
5363 }
5364 } else {
5365 qWarning("Failed to copy texture readback buffer of size %lld: %d",
5366 qint64(planar.size()), err);
5367 readback.result->data.clear();
5368 }
5369 } else {
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) {
5377 // VK_FORMAT_X8_D24_UNORM_PACK32 has the depth in the low
5378 // 24 bits and the upper 8 bits undefined. Use the same
5379 // layout as for D24S8: depth in the upper 24 bits, the
5380 // low 8 bits zero.
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);
5384 }
5385 }
5386
5387 vmaDestroyBuffer(toVmaAllocator(allocator), readback.stagingBuf, toVmaAllocation(readback.stagingAlloc));
5388
5389 if (readback.result->completed)
5390 completedCallbacks.append(readback.result->completed);
5391
5392 activeTextureReadbacks.remove(i);
5393 }
5394 }
5395
5396 for (int i = activeBufferReadbacks.size() - 1; i >= 0; --i) {
5397 const QRhiVulkan::BufferReadback &readback(activeBufferReadbacks[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();
5406 }
5407
5408 vmaDestroyBuffer(toVmaAllocator(allocator), readback.stagingBuf, toVmaAllocation(readback.stagingAlloc));
5409
5410 if (readback.result->completed)
5411 completedCallbacks.append(readback.result->completed);
5412
5413 activeBufferReadbacks.remove(i);
5414 }
5415 }
5416
5417 for (const auto &f : completedCallbacks)
5418 f();
5419}
5420
5421static struct {
5422 VkSampleCountFlagBits mask;
5423 int count;
5424} qvk_sampleCounts[] = {
5425 // keep this sorted by 'count'
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 }
5434
5436{
5437 const VkPhysicalDeviceLimits *limits = &physDevProperties.limits;
5438 VkSampleCountFlags color = limits->framebufferColorSampleCounts;
5439 VkSampleCountFlags depth = limits->framebufferDepthSampleCounts;
5440 VkSampleCountFlags stencil = limits->framebufferStencilSampleCounts;
5441 QList<int> result;
5442
5443 for (const auto &qvk_sampleCount : qvk_sampleCounts) {
5444 if ((color & qvk_sampleCount.mask)
5445 && (depth & qvk_sampleCount.mask)
5446 && (stencil & qvk_sampleCount.mask))
5447 {
5448 result.append(qvk_sampleCount.count);
5449 }
5450 }
5451
5452 return result;
5453}
5454
5456{
5457 const int s = effectiveSampleCount(sampleCount);
5458
5459 for (const auto &qvk_sampleCount : qvk_sampleCounts) {
5460 if (qvk_sampleCount.count == s)
5461 return qvk_sampleCount.mask;
5462 }
5463
5464 Q_UNREACHABLE_RETURN(VK_SAMPLE_COUNT_1_BIT);
5465}
5466
5468{
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;
5476 break;
5477 }
5478 }
5479 for (const VkPhysicalDeviceFragmentShadingRateKHR &s : fragmentShadingRates) {
5480 if (s.sampleCounts & mask)
5481 result.append(QSize(int(s.fragmentSize.width), int(s.fragmentSize.height)));
5482 }
5483#else
5484 Q_UNUSED(sampleCount);
5485 result.append(QSize(1, 1));
5486#endif
5487 return result;
5488}
5489
5491{
5492 cbD->passResTrackers.emplace_back();
5493 cbD->currentPassResTrackerIndex = cbD->passResTrackers.size() - 1;
5494
5495 QVkCommandBuffer::Command &cmd(cbD->commands.get());
5497 cmd.args.transitionResources.trackerIndex = cbD->passResTrackers.size() - 1;
5498}
5499
5501{
5503
5504 for (auto it = cbD->commands.begin(), end = cbD->commands.end(); it != end; ++it) {
5505 QVkCommandBuffer::Command &cmd(*it);
5506 switch (cmd.cmd) {
5508 df->vkCmdCopyBuffer(cbD->cb, cmd.args.copyBuffer.src, cmd.args.copyBuffer.dst,
5509 1, &cmd.args.copyBuffer.desc);
5510 break;
5512 df->vkCmdFillBuffer(cbD->cb, cmd.args.fillBuffer.dst, cmd.args.fillBuffer.offset,
5513 cmd.args.fillBuffer.size, cmd.args.fillBuffer.data);
5514 break;
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);
5520 break;
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);
5525 break;
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);
5531 break;
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);
5536 break;
5538 df->vkCmdPipelineBarrier(cbD->cb, cmd.args.bufferBarrier.srcStageMask, cmd.args.bufferBarrier.dstStageMask,
5539 0, 0, nullptr,
5540 cmd.args.bufferBarrier.count, cbD->pools.bufferBarrier.constData() + cmd.args.bufferBarrier.index,
5541 0, nullptr);
5542 break;
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,
5550 0, 0, nullptr,
5551 barrier.bufferCount, bufferBarrierData,
5552 barrier.imageCount, imageBarrierData);
5553 } break;
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);
5559 break;
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);
5565 break;
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,
5573 1, &barrier,
5574 0, VK_NULL_HANDLE,
5575 0, VK_NULL_HANDLE);
5576 } break;
5578 df->vkCmdEndRenderPass(cbD->cb);
5579 break;
5581 df->vkCmdBindPipeline(cbD->cb, cmd.args.bindPipeline.bindPoint, cmd.args.bindPipeline.pipeline);
5582 break;
5584 {
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),
5592 offsets);
5593 }
5594 break;
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);
5600 break;
5602 df->vkCmdBindIndexBuffer(cbD->cb, cmd.args.bindIndexBuffer.buf,
5603 cmd.args.bindIndexBuffer.ofs, cmd.args.bindIndexBuffer.type);
5604 break;
5606 df->vkCmdSetViewport(cbD->cb, 0, 1, &cmd.args.setViewport.viewport);
5607 break;
5609 df->vkCmdSetScissor(cbD->cb, 0, 1, &cmd.args.setScissor.scissor);
5610 break;
5612 df->vkCmdSetBlendConstants(cbD->cb, cmd.args.setBlendConstants.c);
5613 break;
5615 df->vkCmdSetStencilReference(cbD->cb, VK_STENCIL_FRONT_AND_BACK, cmd.args.setStencilRef.ref);
5616 break;
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);
5624 break;
5626 df->vkCmdDraw(cbD->cb, cmd.args.draw.vertexCount, cmd.args.draw.instanceCount,
5627 cmd.args.draw.firstVertex, cmd.args.draw.firstInstance);
5628 break;
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);
5633 break;
5635 df->vkCmdDrawIndirect(cbD->cb, cmd.args.drawIndirect.indirectBuffer,
5636 cmd.args.drawIndirect.indirectBufferOffset,
5637 cmd.args.drawIndirect.drawCount,
5638 cmd.args.drawIndirect.stride);
5639 break;
5641 df->vkCmdDrawIndexedIndirect(cbD->cb, cmd.args.drawIndexedIndirect.indirectBuffer,
5642 cmd.args.drawIndexedIndirect.indirectBufferOffset,
5643 cmd.args.drawIndexedIndirect.drawCount,
5644 cmd.args.drawIndexedIndirect.stride);
5645 break;
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);
5655 break;
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);
5664 break;
5665#endif
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);
5671#endif
5672 break;
5674#ifdef VK_EXT_debug_utils
5675 vkCmdEndDebugUtilsLabelEXT(cbD->cb);
5676#endif
5677 break;
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);
5683#endif
5684 break;
5686 recordTransitionPassResources(cbD, cbD->passResTrackers[cmd.args.transitionResources.trackerIndex]);
5687 break;
5689 df->vkCmdDispatch(cbD->cb, uint32_t(cmd.args.dispatch.x), uint32_t(cmd.args.dispatch.y), uint32_t(cmd.args.dispatch.z));
5690 break;
5692 df->vkCmdDispatchIndirect(cbD->cb,
5693 cmd.args.dispatchIndirect.indirectBuffer,
5694 cmd.args.dispatchIndirect.indirectBufferOffset);
5695 break;
5697 df->vkCmdExecuteCommands(cbD->cb, 1, &cmd.args.executeSecondary.cb);
5698 break;
5700 {
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
5705 };
5706 VkExtent2D size = { cmd.args.setShadingRate.w, cmd.args.setShadingRate.h };
5707 vkCmdSetFragmentShadingRateKHR(cbD->cb, &size, op);
5708#endif
5709 }
5710 break;
5711 default:
5712 break;
5713 }
5714 }
5715}
5716
5718{
5719 switch (access) {
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;
5734 default:
5735 Q_UNREACHABLE();
5736 break;
5737 }
5738 return 0;
5739}
5740
5742{
5743 switch (stage) {
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;
5760 default:
5761 Q_UNREACHABLE();
5762 break;
5763 }
5764 return 0;
5765}
5766
5768{
5770 u.access = VkAccessFlags(usage.access);
5771 u.stage = VkPipelineStageFlags(usage.stage);
5772 return u;
5773}
5774
5776{
5777 switch (access) {
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;
5792#else
5793 return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
5794#endif
5795 default:
5796 Q_UNREACHABLE();
5797 break;
5798 }
5799 return VK_IMAGE_LAYOUT_GENERAL;
5800}
5801
5803{
5804 switch (access) {
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:
5812 // a multisample resolve, even for depth-stencil, is a color attachment
5813 // write as far as synchronization is concerned
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;
5822 return 0;
5823 default:
5824 Q_UNREACHABLE();
5825 break;
5826 }
5827 return 0;
5828}
5829
5831{
5832 switch (stage) {
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;
5849 default:
5850 Q_UNREACHABLE();
5851 break;
5852 }
5853 return 0;
5854}
5855
5857{
5859 u.layout = VkImageLayout(usage.layout);
5860 u.access = VkAccessFlags(usage.access);
5861 u.stage = VkPipelineStageFlags(usage.stage);
5862 return u;
5863}
5864
5866 QVkBuffer *bufD,
5867 int slot,
5870{
5871 QVkBuffer::UsageState &u(bufD->usageState[slot]);
5872 const VkAccessFlags newAccess = toVkAccess(access);
5873 const VkPipelineStageFlags newStage = toVkPipelineStage(stage);
5874 if (u.access == newAccess && u.stage == newStage) {
5875 if (!accessIsWrite(newAccess))
5876 return;
5877 }
5878 passResTracker->registerBuffer(bufD, slot, &access, &stage, toPassTrackerUsageState(u));
5879 u.access = newAccess;
5880 u.stage = newStage;
5881}
5882
5884 QVkTexture *texD,
5887{
5888 QVkTexture::UsageState &u(texD->usageState);
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))
5894 return;
5895 }
5896 passResTracker->registerTexture(texD, &access, &stage, toPassTrackerUsageState(u));
5897 u.layout = newLayout;
5898 u.access = newAccess;
5899 u.stage = newStage;
5900}
5901
5903{
5904 if (tracker.isEmpty())
5905 return;
5906
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);
5912 if (!s.stage)
5913 continue;
5914 if (s.access == access && s.stage == stage) {
5915 if (!accessIsWrite(access))
5916 continue;
5917 }
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,
5927 0, nullptr,
5928 1, &bufMemBarrier,
5929 0, nullptr);
5930 }
5931
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))
5940 continue;
5941 }
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; // new textures have this set to UNDEFINED
5950 barrier.newLayout = layout;
5951 barrier.srcAccessMask = s.access; // may be 0 but that's fine
5952 barrier.dstAccessMask = access;
5953 barrier.image = texD->image;
5954 VkPipelineStageFlags srcStage = s.stage;
5955 // stage mask cannot be 0
5956 if (!srcStage)
5957 srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
5958 df->vkCmdPipelineBarrier(cbD->cb, srcStage, stage, 0,
5959 0, nullptr,
5960 0, nullptr,
5961 1, &barrier);
5962 }
5963}
5964
5966{
5967 if (!vkGetPhysicalDeviceSurfaceCapabilitiesKHR
5968 || !vkGetPhysicalDeviceSurfaceFormatsKHR
5969 || !vkGetPhysicalDeviceSurfacePresentModesKHR)
5970 {
5971 qWarning("Physical device surface queries not available");
5972 return nullptr;
5973 }
5974
5975 return new QVkSwapChain(this);
5976}
5977
5978QRhiBuffer *QRhiVulkan::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
5979{
5980 return new QVkBuffer(this, type, usage, size);
5981}
5982
5984{
5985 return int(ubufAlign); // typically 256 (bytes)
5986}
5987
5989{
5990 return false;
5991}
5992
5994{
5995 return false;
5996}
5997
5999{
6000 return true;
6001}
6002
6004{
6005 // See https://matthewwellings.com/blog/the-new-vulkan-coordinate-system/
6006
6007 // NB the ctor takes row-major
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);
6012 return m;
6013}
6014
6015bool QRhiVulkan::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
6016{
6017 // Note that with some SDKs the validation layer gives an odd warning about
6018 // BC not being supported, even when our check here succeeds. Not much we
6019 // can do about that.
6020 if (format >= QRhiTexture::BC1 && format <= QRhiTexture::BC7) {
6021 if (!physDevFeatures.textureCompressionBC)
6022 return false;
6023 }
6024
6025 if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ETC2_RGBA8) {
6026 if (!physDevFeatures.textureCompressionETC2)
6027 return false;
6028 }
6029
6030 if (format >= QRhiTexture::ASTC_4x4 && format <= QRhiTexture::ASTC_12x12) {
6031 if (!physDevFeatures.textureCompressionASTC_LDR)
6032 return false;
6033 }
6034
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;
6039}
6040
6041bool QRhiVulkan::isFeatureSupported(QRhi::Feature feature) const
6042{
6043 switch (feature) {
6044 case QRhi::MultisampleTexture:
6045 return true;
6046 case QRhi::MultisampleRenderBuffer:
6047 return true;
6048 case QRhi::DebugMarkers:
6049 return caps.debugUtils;
6050 case QRhi::Timestamps:
6051 return timestampValidBits != 0;
6052 case QRhi::Instancing:
6053 return true;
6054 case QRhi::CustomInstanceStepRate:
6055 return caps.vertexAttribDivisor;
6056 case QRhi::PrimitiveRestart:
6057 return true;
6058 case QRhi::NonDynamicUniformBuffers:
6059 return true;
6060 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
6061 return true;
6062 case QRhi::NPOTTextureRepeat:
6063 return true;
6064 case QRhi::RedOrAlpha8IsRed:
6065 return true;
6066 case QRhi::ElementIndexUint:
6067 return true;
6068 case QRhi::Compute:
6069 return caps.compute;
6070 case QRhi::FragmentStoresAndAtomics:
6071 return physDevFeatures.fragmentStoresAndAtomics;
6072 case QRhi::WideLines:
6073 return caps.wideLines;
6074 case QRhi::VertexShaderPointSize:
6075 return true;
6076 case QRhi::BaseVertex:
6077 return true;
6078 case QRhi::BaseInstance:
6079 return true;
6080 case QRhi::TriangleFanTopology:
6081 return true;
6082 case QRhi::ReadBackNonUniformBuffer:
6083 return true;
6084 case QRhi::ReadBackNonBaseMipLevel:
6085 return true;
6086 case QRhi::TexelFetch:
6087 return true;
6088 case QRhi::RenderToNonBaseMipLevel:
6089 return true;
6090 case QRhi::IntAttributes:
6091 return true;
6092 case QRhi::ScreenSpaceDerivatives:
6093 return true;
6094 case QRhi::ReadBackAnyTextureFormat:
6095 return true;
6096 case QRhi::PipelineCacheDataLoadSave:
6097 return true;
6098 case QRhi::ImageDataStride:
6099 return true;
6100 case QRhi::RenderBufferImport:
6101 return false;
6102 case QRhi::ThreeDimensionalTextures:
6103 return true;
6104 case QRhi::RenderTo3DTextureSlice:
6105 return caps.texture3DSliceAs2D;
6106 case QRhi::TextureArrays:
6107 return true;
6108 case QRhi::Tessellation:
6109 return caps.tessellation;
6110 case QRhi::GeometryShader:
6111 return caps.geometryShader;
6112 case QRhi::TextureArrayRange:
6113 return true;
6114 case QRhi::NonFillPolygonMode:
6115 return caps.nonFillPolygonMode;
6116 case QRhi::OneDimensionalTextures:
6117 return true;
6118 case QRhi::OneDimensionalTextureMipmaps:
6119 return true;
6120 case QRhi::HalfAttributes:
6121 return true;
6122 case QRhi::RenderToOneDimensionalTexture:
6123 return true;
6124 case QRhi::ThreeDimensionalTextureMipmaps:
6125 return true;
6126 case QRhi::MultiView:
6127 return caps.multiView;
6128 case QRhi::TextureViewFormat:
6129 return true;
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:
6143 return true;
6144 case QRhi::InstanceIndexIncludesBaseInstance:
6145 return true;
6146 case QRhi::DepthClamp:
6147 return caps.depthClamp;
6148 case QRhi::DrawIndirect:
6149 return true; // available in Vulkan 1.0
6150 case QRhi::DrawIndirectMulti:
6151 return caps.drawIndirectMulti;
6152 case QRhi::ShaderDrawParameters:
6153 return caps.shaderDrawParameters;
6154 case QRhi::DispatchIndirect:
6155 return true; // available in Vulkan 1.0
6156 case QRhi::PushConstants:
6157 return true;
6158 case QRhi::DrawIndirectCount:
6159 return caps.drawIndirectCount;
6160 case QRhi::BufferToBufferCopy:
6161 return true;
6162 case QRhi::StaticBuffersOnGpuTimeline:
6163 return true;
6164 default:
6165 Q_UNREACHABLE_RETURN(false);
6166 }
6167}
6168
6169int QRhiVulkan::resourceLimit(QRhi::ResourceLimit limit) const
6170{
6171 switch (limit) {
6172 case QRhi::TextureSizeMin:
6173 return 1;
6174 case QRhi::TextureSizeMax:
6175 return int(physDevProperties.limits.maxImageDimension2D);
6176 case QRhi::MaxColorAttachments:
6177 return int(physDevProperties.limits.maxColorAttachments);
6178 case QRhi::FramesInFlight:
6179 return QVK_FRAMES_IN_FLIGHT;
6180 case QRhi::MaxAsyncReadbackFrames:
6181 return QVK_FRAMES_IN_FLIGHT;
6182 case QRhi::MaxThreadGroupsPerDimension:
6183 // Some drivers (Arm Mali) report UINT32_MAX, which must not wrap to -1
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:
6208 // no upper bound in the spec either, so do not let it wrap
6209 return int(qMin<uint32_t>(INT_MAX,
6210 physDevProperties.limits.maxPerStageDescriptorStorageBuffers));
6211 case QRhi::MaxStorageBufferBindings:
6212 case QRhi::MaxStorageImageBindings:
6213 return INT_MAX; // descriptor set layouts do not limit binding numbers
6214 case QRhi::ShadingRateImageTileSize:
6215 return caps.imageBasedShadingRateTileSize;
6216 default:
6217 Q_UNREACHABLE_RETURN(0);
6218 }
6219}
6220
6222{
6223 return &nativeHandlesStruct;
6224}
6225
6227{
6228 return driverInfoStruct;
6229}
6230
6232{
6233 QRhiStats result;
6234 result.totalPipelineCreationTime = totalPipelineCreationTime();
6235
6236 VmaBudget budgets[VK_MAX_MEMORY_HEAPS];
6237 vmaGetHeapBudgets(toVmaAllocator(allocator), budgets);
6238
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;
6246 }
6247
6248 return result;
6249}
6250
6252{
6253 // not applicable
6254 return false;
6255}
6256
6257void QRhiVulkan::setQueueSubmitParams(QRhiNativeHandles *params)
6258{
6259 QRhiVulkanQueueSubmitParams *sp = static_cast<QRhiVulkanQueueSubmitParams *>(params);
6260 if (!sp)
6261 return;
6262
6263 waitSemaphoresForQueueSubmit.clear();
6264 if (sp->waitSemaphoreCount)
6265 waitSemaphoresForQueueSubmit.append(sp->waitSemaphores, sp->waitSemaphoreCount);
6266
6267 signalSemaphoresForQueueSubmit.clear();
6268 if (sp->signalSemaphoreCount)
6269 signalSemaphoresForQueueSubmit.append(sp->signalSemaphores, sp->signalSemaphoreCount);
6270
6271 waitSemaphoresForPresent.clear();
6272 if (sp->presentWaitSemaphoreCount)
6273 waitSemaphoresForPresent.append(sp->presentWaitSemaphores, sp->presentWaitSemaphoreCount);
6274}
6275
6280
6282{
6283 return deviceLost;
6284}
6285
6297
6299{
6300 Q_STATIC_ASSERT(sizeof(QVkPipelineCacheDataHeader) == 32);
6301
6302 QByteArray data;
6303 if (!pipelineCache || !rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
6304 return data;
6305
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();
6311 }
6312 const size_t headerSize = sizeof(QVkPipelineCacheDataHeader);
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();
6319 }
6320
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);
6332
6333 return data;
6334}
6335
6336void QRhiVulkan::setPipelineCacheData(const QByteArray &data)
6337{
6338 if (data.isEmpty())
6339 return;
6340
6341 const size_t headerSize = sizeof(QVkPipelineCacheDataHeader);
6342 if (data.size() < qsizetype(headerSize)) {
6343 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob size");
6344 return;
6345 }
6347 memcpy(&header, data.constData(), headerSize);
6348
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);
6353 return;
6354 }
6355 const quint32 arch = quint32(sizeof(void*));
6356 if (header.arch != arch) {
6357 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Architecture does not match (%u, %u)",
6358 arch, header.arch);
6359 return;
6360 }
6361 if (header.driverVersion != physDevProperties.driverVersion) {
6362 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: driverVersion does not match (%u, %u)",
6363 physDevProperties.driverVersion, header.driverVersion);
6364 return;
6365 }
6366 if (header.vendorId != physDevProperties.vendorID) {
6367 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: vendorID does not match (%u, %u)",
6368 physDevProperties.vendorID, header.vendorId);
6369 return;
6370 }
6371 if (header.deviceId != physDevProperties.deviceID) {
6372 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: deviceID does not match (%u, %u)",
6373 physDevProperties.deviceID, header.deviceId);
6374 return;
6375 }
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);
6379 return;
6380 }
6381
6382 if (data.size() < qsizetype(headerSize + VK_UUID_SIZE)) {
6383 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob, no uuid");
6384 return;
6385 }
6386 if (memcmp(data.constData() + headerSize, physDevProperties.pipelineCacheUUID, VK_UUID_SIZE)) {
6387 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: pipelineCacheUUID does not match");
6388 return;
6389 }
6390
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");
6394 return;
6395 }
6396
6397 if (pipelineCache) {
6398 df->vkDestroyPipelineCache(dev, pipelineCache, nullptr);
6399 pipelineCache = VK_NULL_HANDLE;
6400 }
6401
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));
6405 } else {
6406 qCDebug(QRHI_LOG_INFO, "Failed to create pipeline cache with initial data specified");
6407 }
6408}
6409
6410QRhiRenderBuffer *QRhiVulkan::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
6411 int sampleCount, QRhiRenderBuffer::Flags flags,
6412 QRhiTexture::Format backingFormatHint)
6413{
6414 return new QVkRenderBuffer(this, type, pixelSize, sampleCount, flags, backingFormatHint);
6415}
6416
6417QRhiTexture *QRhiVulkan::createTexture(QRhiTexture::Format format,
6418 const QSize &pixelSize, int depth, int arraySize,
6419 int sampleCount, QRhiTexture::Flags flags)
6420{
6421 return new QVkTexture(this, format, pixelSize, depth, arraySize, sampleCount, flags);
6422}
6423
6424QRhiSampler *QRhiVulkan::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
6425 QRhiSampler::Filter mipmapMode,
6426 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
6427{
6428 return new QVkSampler(this, magFilter, minFilter, mipmapMode, u, v, w);
6429}
6430
6431QRhiShadingRateMap *QRhiVulkan::createShadingRateMap()
6432{
6433 return new QVkShadingRateMap(this);
6434}
6435
6436QRhiTextureRenderTarget *QRhiVulkan::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
6437 QRhiTextureRenderTarget::Flags flags)
6438{
6439 return new QVkTextureRenderTarget(this, desc, flags);
6440}
6441
6443{
6444 return new QVkGraphicsPipeline(this);
6445}
6446
6448{
6449 return new QVkComputePipeline(this);
6450}
6451
6453{
6454 return new QVkShaderResourceBindings(this);
6455}
6456
6457void QRhiVulkan::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps)
6458{
6460 Q_ASSERT(psD->pipeline);
6461 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
6463
6464 if (cbD->currentGraphicsPipeline != ps || cbD->currentPipelineGeneration != psD->generation) {
6465 if (cbD->passUsesSecondaryCb) {
6466 df->vkCmdBindPipeline(cbD->activeSecondaryCbStack.last(), VK_PIPELINE_BIND_POINT_GRAPHICS, psD->pipeline);
6467 } else {
6468 QVkCommandBuffer::Command &cmd(cbD->commands.get());
6470 cmd.args.bindPipeline.bindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
6471 cmd.args.bindPipeline.pipeline = psD->pipeline;
6472 }
6473
6474 cbD->currentGraphicsPipeline = ps;
6475 cbD->currentComputePipeline = nullptr;
6477
6478 if (cbD->hasCustomScissorSet && !psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor))
6480
6481 // Binding a pipeline with a static stencil reference value (0)
6482 // invalidates the dynamic state, so the value needs to be set again
6483 // for the next pipeline with UsesStencilRef. This also gives such
6484 // pipelines a well-defined value of 0 at the start of a pass.
6485 if (psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)) {
6486 if (!cbD->stencilRefValid)
6487 recordStencilRef(cbD, cbD->currentStencilRef);
6488 } else {
6489 cbD->stencilRefValid = false;
6490 }
6491 }
6492
6493 psD->lastActiveFrameSlot = currentFrameSlot;
6494}
6495
6496void QRhiVulkan::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb,
6497 int dynamicOffsetCount,
6498 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
6499{
6500 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
6502 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
6503 QVkGraphicsPipeline *gfxPsD = QRHI_RES(QVkGraphicsPipeline, cbD->currentGraphicsPipeline);
6504 QVkComputePipeline *compPsD = QRHI_RES(QVkComputePipeline, cbD->currentComputePipeline);
6505
6506 if (!srb) {
6507 if (gfxPsD)
6508 srb = gfxPsD->m_shaderResourceBindings;
6509 else
6510 srb = compPsD->m_shaderResourceBindings;
6511 }
6512
6514 auto &descSetBd(srbD->boundResourceData[currentFrameSlot]);
6515 bool rewriteDescSet = false;
6516 bool addWriteBarrier = false;
6517 VkPipelineStageFlags writeBarrierSrcStageMask = 0;
6518 VkPipelineStageFlags writeBarrierDstStageMask = 0;
6519
6520 // Do host writes and mark referenced shader resources as in-use.
6521 // Also prepare to ensure the descriptor set we are going to bind refers to up-to-date Vk objects.
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:
6527 {
6528 QVkBuffer *bufD = QRHI_RES(QVkBuffer, b->ubuf().buf);
6529 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
6530 sanityCheckResourceOwnership(bufD);
6531
6532 if (bufD->m_type == QRhiBuffer::Dynamic)
6533 executeBufferHostWritesForSlot(bufD, currentFrameSlot);
6534
6535 bufD->lastActiveFrameSlot = currentFrameSlot;
6536 trackedRegisterBuffer(&passResTracker, bufD, bufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0,
6538 QRhiPassResourceTracker::toPassTrackerBufferStage(b->stage));
6539
6540 // Check both the "local" id (the generation counter) and the
6541 // global id. The latter is relevant when a newly allocated
6542 // QRhiResource ends up with the same pointer as a previous one.
6543 // (and that previous one could have been in an srb...)
6544 if (bufD->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
6545 rewriteDescSet = true;
6546 bd.ubuf.id = bufD->m_id;
6547 bd.ubuf.generation = bufD->generation;
6548 }
6549 }
6550 break;
6551 case QRhiShaderResourceBinding::SampledTexture:
6552 case QRhiShaderResourceBinding::Texture:
6553 case QRhiShaderResourceBinding::Sampler:
6554 {
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;
6559 }
6560 for (int elem = 0; elem < data->count(); ++elem) {
6561 QVkTexture *texD = QRHI_RES(QVkTexture, data->texSamplers[elem].tex);
6562 QVkSampler *samplerD = QRHI_RES(QVkSampler, data->texSamplers[elem].sampler);
6563 // We use the same code path for both combined and separate
6564 // images and samplers, so tex or sampler (but not both) can be
6565 // null here.
6566 Q_ASSERT(texD || samplerD);
6567 sanityCheckResourceOwnership(texD);
6568 sanityCheckResourceOwnership(samplerD);
6569 if (texD) {
6570 texD->lastActiveFrameSlot = currentFrameSlot;
6571 trackedRegisterTexture(&passResTracker, texD,
6573 QRhiPassResourceTracker::toPassTrackerTextureStage(b->stage));
6574 }
6575 if (samplerD)
6576 samplerD->lastActiveFrameSlot = currentFrameSlot;
6577 const quint64 texId = texD ? texD->m_id : 0;
6578 const uint texGen = texD ? texD->generation : 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)
6585 {
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;
6591 }
6592 }
6593 }
6594 break;
6595 case QRhiShaderResourceBinding::ImageLoad:
6596 case QRhiShaderResourceBinding::ImageStore:
6597 case QRhiShaderResourceBinding::ImageLoadStore:
6598 {
6599 QVkTexture *texD = QRHI_RES(QVkTexture, b->simage().tex);
6600 sanityCheckResourceOwnership(texD);
6601 Q_ASSERT(texD->m_flags.testFlag(QRhiTexture::UsedWithLoadStore));
6602 texD->lastActiveFrameSlot = currentFrameSlot;
6604 if (b->type() == QRhiShaderResourceBinding::ImageLoad)
6606 else if (b->type() == QRhiShaderResourceBinding::ImageStore)
6608 else
6610
6611 const auto stage = QRhiPassResourceTracker::toPassTrackerTextureStage(b->stage);
6612 const auto prevAccess = passResTracker.textures().find(texD);
6613 if (prevAccess != passResTracker.textures().end()) {
6614 const QRhiPassResourceTracker::Texture &tex = prevAccess->second;
6617 addWriteBarrier = true;
6618 writeBarrierDstStageMask |= toVkPipelineStage(stage);
6619 writeBarrierSrcStageMask |= toVkPipelineStage(tex.stage);
6620 }
6621 }
6622
6623 trackedRegisterTexture(&passResTracker, texD,
6624 access,
6625 stage);
6626
6627 if (texD->generation != bd.simage.generation || texD->m_id != bd.simage.id) {
6628 rewriteDescSet = true;
6629 bd.simage.id = texD->m_id;
6630 bd.simage.generation = texD->generation;
6631 }
6632 }
6633 break;
6634 case QRhiShaderResourceBinding::BufferLoad:
6635 case QRhiShaderResourceBinding::BufferStore:
6636 case QRhiShaderResourceBinding::BufferLoadStore:
6637 {
6638 QVkBuffer *bufD = QRHI_RES(QVkBuffer, b->sbuf().buf);
6639 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::StorageBuffer));
6640 sanityCheckResourceOwnership(bufD);
6641
6642 if (bufD->m_type == QRhiBuffer::Dynamic)
6643 executeBufferHostWritesForSlot(bufD, currentFrameSlot);
6644
6645 bufD->lastActiveFrameSlot = currentFrameSlot;
6647 if (b->type() == QRhiShaderResourceBinding::BufferLoad)
6649 else if (b->type() == QRhiShaderResourceBinding::BufferStore)
6651 else
6653
6654 const auto stage = QRhiPassResourceTracker::toPassTrackerBufferStage(b->stage);
6655 const auto prevAccess = passResTracker.buffers().find(bufD);
6656 if (prevAccess != passResTracker.buffers().end()) {
6657 const QRhiPassResourceTracker::Buffer &buf = prevAccess->second;
6660 addWriteBarrier = true;
6661 writeBarrierDstStageMask |= toVkPipelineStage(stage);
6662 writeBarrierSrcStageMask |= toVkPipelineStage(buf.stage);
6663 }
6664 }
6665 trackedRegisterBuffer(&passResTracker, bufD, bufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0,
6666 access,
6667 stage);
6668
6669 if (bufD->generation != bd.sbuf.generation || bufD->m_id != bd.sbuf.id) {
6670 rewriteDescSet = true;
6671 bd.sbuf.id = bufD->m_id;
6672 bd.sbuf.generation = bufD->generation;
6673 }
6674 }
6675 break;
6676 default:
6677 Q_UNREACHABLE();
6678 break;
6679 }
6680 }
6681
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;
6688#endif
6689 if (cbD->passUsesSecondaryCb) {
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,
6696 1, &barrier,
6697 0, VK_NULL_HANDLE,
6698 0, VK_NULL_HANDLE);
6699 } else {
6700 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
6707 }
6708 }
6709
6710 // write descriptor sets, if needed
6711 if (rewriteDescSet)
6712 updateShaderResourceBindings(srb);
6713
6714 // make sure the descriptors for the correct slot will get bound.
6715 // also, dynamic offsets always need a bind.
6716 const bool forceRebind = cbD->currentDescSetSlot != currentFrameSlot
6717 || !srbD->sortedDynamicOffsetBindingNumbers.isEmpty();
6718
6719 const bool srbChanged = gfxPsD ? (cbD->currentGraphicsSrb != srb) : (cbD->currentComputeSrb != srb);
6720
6721 if (forceRebind || rewriteDescSet || srbChanged || cbD->currentSrbGeneration != srbD->generation) {
6722 QVarLengthArray<uint32_t, 4> dynOfs;
6723 // Filling out dynOfs based on the sorted bindings is important
6724 // because dynOfs has to be ordered based on the binding numbers,
6725 // and neither srb nor dynamicOffsets has any such ordering
6726 // requirement.
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;
6733 break;
6734 }
6735 }
6736 dynOfs.append(offset); // use 0 if dynamicOffsets did not contain this binding
6737 }
6738
6739 if (cbD->passUsesSecondaryCb) {
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);
6746 } else {
6747 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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());
6756 }
6757
6758 if (gfxPsD) {
6759 cbD->currentGraphicsSrb = srb;
6760 cbD->currentComputeSrb = nullptr;
6761 } else {
6762 cbD->currentGraphicsSrb = nullptr;
6763 cbD->currentComputeSrb = srb;
6764 }
6766 cbD->currentDescSetSlot = currentFrameSlot;
6767 }
6768
6769 srbD->lastActiveFrameSlot = currentFrameSlot;
6770}
6771
6772void QRhiVulkan::setVertexInput(QRhiCommandBuffer *cb,
6773 int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings,
6774 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
6775{
6776 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
6778 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
6779
6780 bool needsBindVBuf = false;
6781 for (int i = 0; i < bindingCount; ++i) {
6782 const int inputSlot = startBinding + i;
6783 QVkBuffer *bufD = QRHI_RES(QVkBuffer, bindings[i].first);
6784 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
6785 bufD->lastActiveFrameSlot = currentFrameSlot;
6786 if (bufD->m_type == QRhiBuffer::Dynamic)
6787 executeBufferHostWritesForSlot(bufD, currentFrameSlot);
6788
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)
6792 {
6793 needsBindVBuf = true;
6794 cbD->currentVertexBuffers[inputSlot] = vkvertexbuf;
6795 cbD->currentVertexOffsets[inputSlot] = bindings[i].second;
6796 }
6797 }
6798
6799 if (needsBindVBuf) {
6800 QVarLengthArray<VkBuffer, 4> bufs;
6801 QVarLengthArray<VkDeviceSize, 4> ofs;
6802 for (int i = 0; i < bindingCount; ++i) {
6803 QVkBuffer *bufD = QRHI_RES(QVkBuffer, bindings[i].first);
6804 const int slot = bufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
6805 bufs.append(bufD->buffers[slot]);
6806 ofs.append(bindings[i].second);
6807 trackedRegisterBuffer(&passResTracker, bufD, slot,
6810 }
6811
6812 if (cbD->passUsesSecondaryCb) {
6813 df->vkCmdBindVertexBuffers(cbD->activeSecondaryCbStack.last(), uint32_t(startBinding),
6814 uint32_t(bufs.size()), bufs.constData(), ofs.constData());
6815 } else {
6816 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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());
6824 }
6825 }
6826
6827 if (indexBuf) {
6828 QVkBuffer *ibufD = QRHI_RES(QVkBuffer, indexBuf);
6829 Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
6830 ibufD->lastActiveFrameSlot = currentFrameSlot;
6831 if (ibufD->m_type == QRhiBuffer::Dynamic)
6832 executeBufferHostWritesForSlot(ibufD, currentFrameSlot);
6833
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;
6838
6839 if (cbD->currentIndexBuffer != vkindexbuf
6840 || cbD->currentIndexOffset != indexOffset
6841 || cbD->currentIndexFormat != type)
6842 {
6843 cbD->currentIndexBuffer = vkindexbuf;
6844 cbD->currentIndexOffset = indexOffset;
6845 cbD->currentIndexFormat = type;
6846
6847 if (cbD->passUsesSecondaryCb) {
6848 df->vkCmdBindIndexBuffer(cbD->activeSecondaryCbStack.last(), vkindexbuf, indexOffset, type);
6849 } else {
6850 QVkCommandBuffer::Command &cmd(cbD->commands.get());
6852 cmd.args.bindIndexBuffer.buf = vkindexbuf;
6853 cmd.args.bindIndexBuffer.ofs = indexOffset;
6854 cmd.args.bindIndexBuffer.type = type;
6855 }
6856
6857 trackedRegisterBuffer(&passResTracker, ibufD, slot,
6860 }
6861 }
6862}
6863
6865{
6866 cbD->hasCustomScissorSet = false;
6867
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;
6871
6872 if (qFuzzyIsNull(vp[2]) && qFuzzyIsNull(vp[3])) {
6873 x = 0;
6874 y = 0;
6875 w = outputSize.width();
6876 h = outputSize.height();
6877 } else {
6878 // x,y is top-left in VkRect2D but bottom-left in QRhiScissor
6879 qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, vp, &x, &y, &w, &h);
6880 }
6881
6882 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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);
6888
6889 if (cbD->passUsesSecondaryCb) {
6890 df->vkCmdSetScissor(cbD->activeSecondaryCbStack.last(), 0, 1, s);
6891 cbD->commands.unget();
6892 } else {
6894 }
6895}
6896
6897void QRhiVulkan::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
6898{
6899 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
6901 const QSize outputSize = cbD->currentTarget->pixelSize();
6902
6903 // x,y is top-left in VkViewport but bottom-left in QRhiViewport
6904 float x, y, w, h;
6905 if (!qrhi_toTopLeftRenderTargetRect<UnBounded>(outputSize, viewport.viewport(), &x, &y, &w, &h))
6906 return;
6907
6908 QVkCommandBuffer::Command &cmd(cbD->commands.get());
6909 VkViewport *vp = &cmd.args.setViewport.viewport;
6910 vp->x = x;
6911 vp->y = y;
6912 vp->width = w;
6913 vp->height = h;
6914 vp->minDepth = viewport.minDepth();
6915 vp->maxDepth = viewport.maxDepth();
6916
6917 if (cbD->passUsesSecondaryCb) {
6918 df->vkCmdSetViewport(cbD->activeSecondaryCbStack.last(), 0, 1, vp);
6919 cbD->commands.unget();
6920 } else {
6922 }
6923
6924 cbD->currentViewport = viewport;
6925 if (cbD->currentGraphicsPipeline
6926 && !cbD->currentGraphicsPipeline->flags().testFlag(QRhiGraphicsPipeline::UsesScissor))
6927 {
6929 }
6930}
6931
6932void QRhiVulkan::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
6933{
6934 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
6936 Q_ASSERT(!cbD->currentGraphicsPipeline
6937 || QRHI_RES(QVkGraphicsPipeline, cbD->currentGraphicsPipeline)
6938 ->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor));
6939 const QSize outputSize = cbD->currentTarget->pixelSize();
6940
6941 // x,y is top-left in VkRect2D but bottom-left in QRhiScissor
6942 int x, y, w, h;
6943 if (!qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, scissor.scissor(), &x, &y, &w, &h))
6944 return;
6945
6946 QVkCommandBuffer::Command &cmd(cbD->commands.get());
6947 VkRect2D *s = &cmd.args.setScissor.scissor;
6948 s->offset.x = x;
6949 s->offset.y = y;
6950 s->extent.width = uint32_t(w);
6951 s->extent.height = uint32_t(h);
6952
6953 if (cbD->passUsesSecondaryCb) {
6954 df->vkCmdSetScissor(cbD->activeSecondaryCbStack.last(), 0, 1, s);
6955 cbD->commands.unget();
6956 } else {
6958 }
6959
6960 cbD->hasCustomScissorSet = true;
6961}
6962
6963void QRhiVulkan::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c)
6964{
6965 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
6967
6968 if (cbD->passUsesSecondaryCb) {
6969 float constants[] = { float(c.redF()), float(c.greenF()), float(c.blueF()), float(c.alphaF()) };
6970 df->vkCmdSetBlendConstants(cbD->activeSecondaryCbStack.last(), constants);
6971 } else {
6972 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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();
6978 }
6979}
6980
6981void QRhiVulkan::recordStencilRef(QVkCommandBuffer *cbD, quint32 refValue)
6982{
6983 if (cbD->passUsesSecondaryCb) {
6984 df->vkCmdSetStencilReference(cbD->activeSecondaryCbStack.last(), VK_STENCIL_FRONT_AND_BACK, refValue);
6985 } else {
6986 QVkCommandBuffer::Command &cmd(cbD->commands.get());
6988 cmd.args.setStencilRef.ref = refValue;
6989 }
6990 cbD->stencilRefValid = true;
6991}
6992
6993void QRhiVulkan::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
6994{
6995 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
6997
6998 recordStencilRef(cbD, refValue);
6999 cbD->currentStencilRef = refValue;
7000}
7001
7002void QRhiVulkan::setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data)
7003{
7004 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7006
7007 VkPipelineLayout layout = VK_NULL_HANDLE;
7008 VkShaderStageFlags stages = 0;
7010 if (QVkComputePipeline *psD = QRHI_RES(QVkComputePipeline, cbD->currentComputePipeline)) {
7011 layout = psD->layout;
7012 stages = psD->pushConstantStages;
7013 }
7014 } else {
7015 if (QVkGraphicsPipeline *psD = QRHI_RES(QVkGraphicsPipeline, cbD->currentGraphicsPipeline)) {
7016 layout = psD->layout;
7017 stages = psD->pushConstantStages;
7018 }
7019 }
7020 if (!layout || !stages) {
7021 qWarning("No pipeline with a push constant block is active; setPushConstants ignored");
7022 return;
7023 }
7024
7025 if (cbD->passUsesSecondaryCb) {
7026 df->vkCmdPushConstants(cbD->activeSecondaryCbStack.last(), layout, stages, offset, size, data);
7027 } else {
7028 const int dataIndex = cbD->pools.pushConstantData.size();
7029 cbD->pools.pushConstantData.append(static_cast<const char *>(data), size);
7030 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
7037 }
7038}
7039
7040void QRhiVulkan::setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize)
7041{
7042#ifdef VK_KHR_fragment_shading_rate
7043 if (!vkCmdSetFragmentShadingRateKHR)
7044 return;
7045
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));
7049
7050 VkFragmentShadingRateCombinerOpKHR ops[2] = {
7051 VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR,
7052 VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR
7053 };
7054 VkExtent2D size = { uint32_t(coarsePixelSize.width()), uint32_t(coarsePixelSize.height()) };
7055 if (cbD->passUsesSecondaryCb) {
7056 vkCmdSetFragmentShadingRateKHR(cbD->activeSecondaryCbStack.last(), &size, ops);
7057 } else {
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;
7062 }
7063 if (coarsePixelSize.width() != 1 || coarsePixelSize.height() != 1)
7064 cbD->hasShadingRateSet = true;
7065#else
7066 Q_UNUSED(cb);
7067 Q_UNUSED(coarsePixelSize);
7068#endif
7069}
7070
7071void QRhiVulkan::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
7072 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
7073{
7074 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7076
7077 if (cbD->passUsesSecondaryCb) {
7078 df->vkCmdDraw(cbD->activeSecondaryCbStack.last(), vertexCount, instanceCount, firstVertex, firstInstance);
7079 } else {
7080 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7082 cmd.args.draw.vertexCount = vertexCount;
7083 cmd.args.draw.instanceCount = instanceCount;
7084 cmd.args.draw.firstVertex = firstVertex;
7085 cmd.args.draw.firstInstance = firstInstance;
7086 }
7087}
7088
7089void QRhiVulkan::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
7090 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
7091{
7092 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7094
7095 if (cbD->passUsesSecondaryCb) {
7096 df->vkCmdDrawIndexed(cbD->activeSecondaryCbStack.last(), indexCount, instanceCount,
7097 firstIndex, vertexOffset, firstInstance);
7098 } else {
7099 QVkCommandBuffer::Command &cmd(cbD->commands.get());
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;
7106 }
7107}
7108
7109void QRhiVulkan::drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
7110 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
7111{
7112 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7114 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
7115
7116 QVkBuffer *indirectBufD = QRHI_RES(QVkBuffer, indirectBuffer);
7117 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
7118 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
7119 executeBufferHostWritesForSlot(indirectBufD, currentFrameSlot);
7120 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
7121 trackedRegisterBuffer(&passResTracker, indirectBufD, indirectBufSlot,
7124 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
7125
7126 if (cbD->passUsesSecondaryCb) {
7127 if (caps.drawIndirectMulti) {
7128 df->vkCmdDrawIndirect(cbD->activeSecondaryCbStack.last(),
7129 indirectBufVk, indirectBufferOffset,
7130 drawCount, stride);
7131 } else {
7132 VkDeviceSize offset = indirectBufferOffset;
7133 for (quint32 i = 0; i < drawCount; ++i) {
7134 df->vkCmdDrawIndirect(cbD->activeSecondaryCbStack.last(),
7135 indirectBufVk, offset,
7136 1, stride);
7137 offset += stride;
7138 }
7139 }
7140 } else {
7141 if (caps.drawIndirectMulti) {
7142 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7144 cmd.args.drawIndirect.indirectBuffer = indirectBufVk;
7145 cmd.args.drawIndirect.indirectBufferOffset = indirectBufferOffset;
7146 cmd.args.drawIndirect.drawCount = drawCount;
7147 cmd.args.drawIndirect.stride = stride;
7148 } else {
7149 VkDeviceSize offset = indirectBufferOffset;
7150 for (quint32 i = 0; i < drawCount; ++i) {
7151 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7153 cmd.args.drawIndirect.indirectBuffer = indirectBufVk;
7154 cmd.args.drawIndirect.indirectBufferOffset = offset;
7155 cmd.args.drawIndirect.drawCount = 1;
7156 cmd.args.drawIndirect.stride = stride;
7157 offset += stride;
7158 }
7159 }
7160 }
7161}
7162
7163void QRhiVulkan::drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
7164 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
7165{
7166 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7168 QRhiPassResourceTracker &passResTracker(cbD->passResTrackers[cbD->currentPassResTrackerIndex]);
7169
7170 QVkBuffer *indirectBufD = QRHI_RES(QVkBuffer, indirectBuffer);
7171 indirectBufD->lastActiveFrameSlot = currentFrameSlot;
7172 if (indirectBufD->m_type == QRhiBuffer::Dynamic)
7173 executeBufferHostWritesForSlot(indirectBufD, currentFrameSlot);
7174 const int indirectBufSlot = indirectBufD->m_type == QRhiBuffer::Dynamic ? currentFrameSlot : 0;
7175 trackedRegisterBuffer(&passResTracker, indirectBufD, indirectBufSlot,
7178 VkBuffer indirectBufVk = indirectBufD->buffers[indirectBufSlot];
7179
7180 if (cbD->passUsesSecondaryCb) {
7181 if (caps.drawIndirectMulti) {
7182 df->vkCmdDrawIndexedIndirect(cbD->activeSecondaryCbStack.last(),
7183 indirectBufVk, indirectBufferOffset,
7184 drawCount, stride);
7185 } else {
7186 VkDeviceSize offset = indirectBufferOffset;
7187 for (quint32 i = 0; i < drawCount; ++i) {
7188 df->vkCmdDrawIndexedIndirect(cbD->activeSecondaryCbStack.last(),
7189 indirectBufVk, offset,
7190 1, stride);
7191 offset += stride;
7192 }
7193 }
7194 } else {
7195 if (caps.drawIndirectMulti) {
7196 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7198 cmd.args.drawIndexedIndirect.indirectBuffer = indirectBufVk;
7199 cmd.args.drawIndexedIndirect.indirectBufferOffset = indirectBufferOffset;
7200 cmd.args.drawIndexedIndirect.drawCount = drawCount;
7201 cmd.args.drawIndexedIndirect.stride = stride;
7202 } else {
7203 VkDeviceSize offset = indirectBufferOffset;
7204 for (quint32 i = 0; i < drawCount; ++i) {
7205 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7207 cmd.args.drawIndexedIndirect.indirectBuffer = indirectBufVk;
7208 cmd.args.drawIndexedIndirect.indirectBufferOffset = offset;
7209 cmd.args.drawIndexedIndirect.drawCount = 1;
7210 cmd.args.drawIndexedIndirect.stride = stride;
7211 offset += stride;
7212 }
7213 }
7214 }
7215}
7216
7217void QRhiVulkan::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
7218{
7219#ifdef VK_EXT_debug_utils
7220 if (!debugMarkers || !caps.debugUtils)
7221 return;
7222
7223 VkDebugUtilsLabelEXT label = {};
7224 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
7225
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);
7230 } else {
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);
7236 }
7237#else
7238 Q_UNUSED(cb);
7239 Q_UNUSED(name);
7240#endif
7241}
7242
7243void QRhiVulkan::debugMarkEnd(QRhiCommandBuffer *cb)
7244{
7245#ifdef VK_EXT_debug_utils
7246 if (!debugMarkers || !caps.debugUtils)
7247 return;
7248
7249 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7250 if (cbD->recordingPass != QVkCommandBuffer::NoPass && cbD->passUsesSecondaryCb) {
7251 vkCmdEndDebugUtilsLabelEXT(cbD->activeSecondaryCbStack.last());
7252 } else {
7253 QVkCommandBuffer::Command &cmd(cbD->commands.get());
7254 cmd.cmd = QVkCommandBuffer::Command::DebugMarkerEnd;
7255 }
7256#else
7257 Q_UNUSED(cb);
7258#endif
7259}
7260
7261void QRhiVulkan::debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg)
7262{
7263#ifdef VK_EXT_debug_utils
7264 if (!debugMarkers || !caps.debugUtils)
7265 return;
7266
7267 VkDebugUtilsLabelEXT label = {};
7268 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
7269
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);
7274 } else {
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);
7280 }
7281#else
7282 Q_UNUSED(cb);
7283 Q_UNUSED(msg);
7284#endif
7285}
7286
7287const QRhiNativeHandles *QRhiVulkan::nativeHandles(QRhiCommandBuffer *cb)
7288{
7289 return QRHI_RES(QVkCommandBuffer, cb)->nativeHandles();
7290}
7291
7293{
7294 Q_ASSERT(cbD->currentTarget);
7295 QVkRenderTargetData *rtD = nullptr;
7297 switch (cbD->currentTarget->resourceType()) {
7298 case QRhiResource::SwapChainRenderTarget:
7299 rtD = &QRHI_RES(QVkSwapChainRenderTarget, cbD->currentTarget)->d;
7300 break;
7301 case QRhiResource::TextureRenderTarget:
7302 rtD = &QRHI_RES(QVkTextureRenderTarget, cbD->currentTarget)->d;
7303 break;
7304 default:
7305 Q_UNREACHABLE();
7306 break;
7307 }
7308 }
7309 return rtD;
7310}
7311
7312void QRhiVulkan::beginExternal(QRhiCommandBuffer *cb)
7313{
7314 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7315
7316 // When not in a pass, it is simple: record what we have (but do not
7317 // submit), the cb can then be used to record more external commands.
7321 return;
7322 }
7323
7324 // Otherwise, inside a pass, have a secondary command buffer (with
7325 // RENDER_PASS_CONTINUE). Using the main one is not acceptable since we
7326 // cannot just record at this stage, that would mess up the resource
7327 // tracking and commands like TransitionPassResources.
7328
7329 if (cbD->inExternal)
7330 return;
7331
7332 if (!cbD->passUsesSecondaryCb) {
7333 qWarning("beginExternal() within a pass is only supported with secondary command buffers. "
7334 "This can be enabled by passing QRhiCommandBuffer::ExternalContent to beginPass().");
7335 return;
7336 }
7337
7338 VkCommandBuffer secondaryCb = cbD->activeSecondaryCbStack.last();
7339 cbD->activeSecondaryCbStack.removeLast();
7340 endAndEnqueueSecondaryCommandBuffer(secondaryCb, cbD);
7341
7342 VkCommandBuffer extCb = startSecondaryCommandBuffer(maybeRenderTargetData(cbD));
7343 if (extCb) {
7344 cbD->activeSecondaryCbStack.append(extCb);
7345 cbD->inExternal = true;
7346 }
7347}
7348
7349void QRhiVulkan::endExternal(QRhiCommandBuffer *cb)
7350{
7351 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7352
7354 Q_ASSERT(cbD->commands.isEmpty() && cbD->currentPassResTrackerIndex == -1);
7355 } else if (cbD->inExternal) {
7356 VkCommandBuffer extCb = cbD->activeSecondaryCbStack.last();
7357 cbD->activeSecondaryCbStack.removeLast();
7358 endAndEnqueueSecondaryCommandBuffer(extCb, cbD);
7359 cbD->activeSecondaryCbStack.append(startSecondaryCommandBuffer(maybeRenderTargetData(cbD)));
7360 }
7361
7363}
7364
7365double QRhiVulkan::lastCompletedGpuTime(QRhiCommandBuffer *cb)
7366{
7367 QVkCommandBuffer *cbD = QRHI_RES(QVkCommandBuffer, cb);
7368 return cbD->lastGpuTime;
7369}
7370
7371void QRhiVulkan::setAllocationName(QVkAlloc allocation, const QByteArray &name, int slot)
7372{
7373 if (!debugMarkers || name.isEmpty())
7374 return;
7375
7376 QByteArray decoratedName = name;
7377 if (slot >= 0) {
7378 decoratedName += '/';
7379 decoratedName += QByteArray::number(slot);
7380 }
7381 vmaSetAllocationName(toVmaAllocator(allocator), toVmaAllocation(allocation), decoratedName.constData());
7382}
7383
7384void QRhiVulkan::setObjectName(uint64_t object, VkObjectType type, const QByteArray &name, int slot)
7385{
7386#ifdef VK_EXT_debug_utils
7387 if (!debugMarkers || !caps.debugUtils || name.isEmpty())
7388 return;
7389
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;
7395 if (slot >= 0) {
7396 decoratedName += '/';
7397 decoratedName += QByteArray::number(slot);
7398 }
7399 nameInfo.pObjectName = decoratedName.constData();
7400 vkSetDebugUtilsObjectNameEXT(dev, &nameInfo);
7401#else
7402 Q_UNUSED(object);
7403 Q_UNUSED(type);
7404 Q_UNUSED(name);
7405 Q_UNUSED(slot);
7406#endif
7407}
7408
7409static inline VkBufferUsageFlagBits toVkBufferUsage(QRhiBuffer::UsageFlags usage)
7410{
7411 int u = 0;
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);
7423}
7424
7425static inline VkFilter toVkFilter(QRhiSampler::Filter f)
7426{
7427 switch (f) {
7428 case QRhiSampler::Nearest:
7429 return VK_FILTER_NEAREST;
7430 case QRhiSampler::Linear:
7431 return VK_FILTER_LINEAR;
7432 default:
7433 Q_UNREACHABLE_RETURN(VK_FILTER_NEAREST);
7434 }
7435}
7436
7437static inline VkSamplerMipmapMode toVkMipmapMode(QRhiSampler::Filter f)
7438{
7439 switch (f) {
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;
7446 default:
7447 Q_UNREACHABLE_RETURN(VK_SAMPLER_MIPMAP_MODE_NEAREST);
7448 }
7449}
7450
7451static inline VkSamplerAddressMode toVkAddressMode(QRhiSampler::AddressMode m)
7452{
7453 switch (m) {
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;
7460 default:
7461 Q_UNREACHABLE_RETURN(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE);
7462 }
7463}
7464
7465static inline VkShaderStageFlagBits toVkShaderStage(QRhiShaderStage::Type type)
7466{
7467 switch (type) {
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;
7480 default:
7481 Q_UNREACHABLE_RETURN(VK_SHADER_STAGE_VERTEX_BIT);
7482 }
7483}
7484
7485static inline VkFormat toVkAttributeFormat(QRhiVertexInputAttribute::Format format)
7486{
7487 switch (format) {
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;
7542 default:
7543 Q_UNREACHABLE_RETURN(VK_FORMAT_R32G32B32A32_SFLOAT);
7544 }
7545}
7546
7547static inline VkPrimitiveTopology toVkTopology(QRhiGraphicsPipeline::Topology t)
7548{
7549 switch (t) {
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;
7564 default:
7565 Q_UNREACHABLE_RETURN(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
7566 }
7567}
7568
7569static inline VkCullModeFlags toVkCullMode(QRhiGraphicsPipeline::CullMode c)
7570{
7571 switch (c) {
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;
7578 default:
7579 Q_UNREACHABLE_RETURN(VK_CULL_MODE_NONE);
7580 }
7581}
7582
7583static inline VkFrontFace toVkFrontFace(QRhiGraphicsPipeline::FrontFace f)
7584{
7585 switch (f) {
7586 case QRhiGraphicsPipeline::CCW:
7587 return VK_FRONT_FACE_COUNTER_CLOCKWISE;
7588 case QRhiGraphicsPipeline::CW:
7589 return VK_FRONT_FACE_CLOCKWISE;
7590 default:
7591 Q_UNREACHABLE_RETURN(VK_FRONT_FACE_COUNTER_CLOCKWISE);
7592 }
7593}
7594
7595static inline VkColorComponentFlags toVkColorComponents(QRhiGraphicsPipeline::ColorMask c)
7596{
7597 int f = 0;
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);
7607}
7608
7609static inline VkBlendFactor toVkBlendFactor(QRhiGraphicsPipeline::BlendFactor f)
7610{
7611 switch (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;
7650 default:
7651 Q_UNREACHABLE_RETURN(VK_BLEND_FACTOR_ZERO);
7652 }
7653}
7654
7655static inline VkBlendOp toVkBlendOp(QRhiGraphicsPipeline::BlendOp op)
7656{
7657 switch (op) {
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;
7668 default:
7669 Q_UNREACHABLE_RETURN(VK_BLEND_OP_ADD);
7670 }
7671}
7672
7673static inline VkCompareOp toVkCompareOp(QRhiGraphicsPipeline::CompareOp op)
7674{
7675 switch (op) {
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;
7692 default:
7693 Q_UNREACHABLE_RETURN(VK_COMPARE_OP_ALWAYS);
7694 }
7695}
7696
7697static inline VkStencilOp toVkStencilOp(QRhiGraphicsPipeline::StencilOp op)
7698{
7699 switch (op) {
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;
7716 default:
7717 Q_UNREACHABLE_RETURN(VK_STENCIL_OP_KEEP);
7718 }
7719}
7720
7721static inline VkPolygonMode toVkPolygonMode(QRhiGraphicsPipeline::PolygonMode mode)
7722{
7723 switch (mode) {
7724 case QRhiGraphicsPipeline::Fill:
7725 return VK_POLYGON_MODE_FILL;
7726 case QRhiGraphicsPipeline::Line:
7727 return VK_POLYGON_MODE_LINE;
7728 default:
7729 Q_UNREACHABLE_RETURN(VK_POLYGON_MODE_FILL);
7730 }
7731}
7732
7733static inline void fillVkStencilOpState(VkStencilOpState *dst, const QRhiGraphicsPipeline::StencilOpState &src)
7734{
7735 dst->failOp = toVkStencilOp(src.failOp);
7736 dst->passOp = toVkStencilOp(src.passOp);
7737 dst->depthFailOp = toVkStencilOp(src.depthFailOp);
7738 dst->compareOp = toVkCompareOp(src.compareOp);
7739}
7740
7741static inline VkDescriptorType toVkDescriptorType(const QRhiShaderResourceBinding::Data *b)
7742{
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;
7747
7748 case QRhiShaderResourceBinding::SampledTexture:
7749 return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
7750
7751 case QRhiShaderResourceBinding::Texture:
7752 return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
7753
7754 case QRhiShaderResourceBinding::Sampler:
7755 return VK_DESCRIPTOR_TYPE_SAMPLER;
7756
7757 case QRhiShaderResourceBinding::ImageLoad:
7758 case QRhiShaderResourceBinding::ImageStore:
7759 case QRhiShaderResourceBinding::ImageLoadStore:
7760 return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
7761
7762 case QRhiShaderResourceBinding::BufferLoad:
7763 case QRhiShaderResourceBinding::BufferStore:
7764 case QRhiShaderResourceBinding::BufferLoadStore:
7765 return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
7766
7767 default:
7768 Q_UNREACHABLE_RETURN(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
7769 }
7770}
7771
7772static inline VkShaderStageFlags toVkShaderStageFlags(QRhiShaderResourceBinding::StageFlags stage)
7773{
7774 int s = 0;
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);
7788}
7789
7790static inline VkCompareOp toVkTextureCompareOp(QRhiSampler::CompareOp op)
7791{
7792 switch (op) {
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;
7809 default:
7810 Q_UNREACHABLE_RETURN(VK_COMPARE_OP_NEVER);
7811 }
7812}
7813
7814QVkBuffer::QVkBuffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
7816{
7817 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
7818 buffers[i] = stagingBuffers[i] = VK_NULL_HANDLE;
7819 allocations[i] = stagingAllocations[i] = nullptr;
7820 }
7821}
7822
7824{
7825 destroy();
7826}
7827
7829{
7830 if (!buffers[0])
7831 return;
7832
7836
7837 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
7838 e.buffer.buffers[i] = buffers[i];
7839 e.buffer.allocations[i] = allocations[i];
7840 e.buffer.stagingBuffers[i] = stagingBuffers[i];
7841 e.buffer.stagingAllocations[i] = stagingAllocations[i];
7842
7843 buffers[i] = VK_NULL_HANDLE;
7844 allocations[i] = nullptr;
7845 stagingBuffers[i] = VK_NULL_HANDLE;
7846 stagingAllocations[i] = nullptr;
7847 pendingDynamicUpdates[i].clear();
7848 }
7849
7850 QRHI_RES_RHI(QRhiVulkan);
7851 // destroy() implementations, unlike other functions, are expected to test
7852 // for m_rhi being null, to allow surviving in case one attempts to destroy
7853 // a (leaked) resource after the QRhi.
7854 if (rhiD) {
7855 rhiD->releaseQueue.append(e);
7856 rhiD->unregisterResource(this);
7857 }
7858}
7859
7861{
7862 if (buffers[0])
7863 destroy();
7864
7865 if (m_usage.testFlag(QRhiBuffer::StorageBuffer) && m_type == Dynamic) {
7866 qWarning("StorageBuffer cannot be combined with Dynamic");
7867 return false;
7868 }
7869
7870 const quint32 nonZeroSize = m_size <= 0 ? 256 : m_size;
7871
7872 VkBufferCreateInfo bufferInfo = {};
7873 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
7874 bufferInfo.size = nonZeroSize;
7875 bufferInfo.usage = toVkBufferUsage(m_usage);
7876
7877 VmaAllocationCreateInfo allocInfo = {};
7878
7879 if (m_type == Dynamic) {
7880#ifndef Q_OS_DARWIN // not for MoltenVK
7881 // Keep mapped all the time. Essential f.ex. with some mobile GPUs,
7882 // where mapping and unmapping an entire allocation every time updating
7883 // a suballocated buffer presents a significant perf. hit.
7884 allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
7885#endif
7886 // host visible, frequent changes
7887 allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
7888 } else {
7889 allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
7890 bufferInfo.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
7891 }
7892
7893 QRHI_RES_RHI(QRhiVulkan);
7894 VkResult err = VK_SUCCESS;
7895 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
7896 buffers[i] = VK_NULL_HANDLE;
7897 allocations[i] = nullptr;
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)
7903 break;
7904 allocations[i] = allocation;
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);
7908 }
7909 }
7910
7911 if (err != VK_SUCCESS) {
7912 qWarning("Failed to create buffer of size %u: %d", nonZeroSize, err);
7913 rhiD->printExtraErrorInfo(err);
7914 return false;
7915 }
7916
7918 generation += 1;
7919 rhiD->registerResource(this);
7920 return true;
7921}
7922
7924{
7925 if (m_type == Dynamic) {
7926 QRHI_RES_RHI(QRhiVulkan);
7927 NativeBuffer b;
7928 Q_ASSERT(sizeof(b.objects) / sizeof(b.objects[0]) >= size_t(QVK_FRAMES_IN_FLIGHT));
7929 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
7931 b.objects[i] = &buffers[i];
7932 }
7933 b.slotCount = QVK_FRAMES_IN_FLIGHT;
7934 return b;
7935 }
7936 return { { &buffers[0] }, 1 };
7937}
7938
7940{
7941 // Shortcut the entire buffer update mechanism and allow the client to do
7942 // the host writes directly to the buffer. This will lead to unexpected
7943 // results when combined with QRhiResourceUpdateBatch-based updates for the
7944 // buffer, but provides a fast path for dynamic buffers that have all their
7945 // content changed in every frame.
7946 Q_ASSERT(m_type == Dynamic);
7947 QRHI_RES_RHI(QRhiVulkan);
7948 Q_ASSERT(rhiD->inFrame);
7949 const int slot = rhiD->currentFrameSlot;
7950 void *p = nullptr;
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);
7955 return nullptr;
7956 }
7957 return static_cast<char *>(p);
7958}
7959
7961{
7962 QRHI_RES_RHI(QRhiVulkan);
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);
7967}
7968
7969QVkRenderBuffer::QVkRenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize,
7970 int sampleCount, Flags flags,
7971 QRhiTexture::Format backingFormatHint)
7973{
7974}
7975
7977{
7978 destroy();
7979 delete backingTexture;
7980}
7981
7983{
7984 if (!memory && !backingTexture)
7985 return;
7986
7990
7991 e.renderBuffer.memory = memory;
7992 e.renderBuffer.image = image;
7993 e.renderBuffer.imageView = imageView;
7994
7995 memory = VK_NULL_HANDLE;
7996 image = VK_NULL_HANDLE;
7997 imageView = VK_NULL_HANDLE;
7998
7999 if (backingTexture) {
8003 }
8004
8005 QRHI_RES_RHI(QRhiVulkan);
8006 if (rhiD) {
8007 rhiD->releaseQueue.append(e);
8008 rhiD->unregisterResource(this);
8009 }
8010}
8011
8013{
8014 if (memory || backingTexture)
8015 destroy();
8016
8017 if (m_pixelSize.isEmpty())
8018 return false;
8019
8020 QRHI_RES_RHI(QRhiVulkan);
8021 samples = rhiD->effectiveSampleCountBits(m_sampleCount);
8022
8023 switch (m_type) {
8024 case QRhiRenderBuffer::Color:
8025 {
8026 if (!backingTexture) {
8027 backingTexture = QRHI_RES(QVkTexture, rhiD->createTexture(backingFormat(),
8028 m_pixelSize,
8029 1,
8030 0,
8031 m_sampleCount,
8032 QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource));
8033 } else {
8034 backingTexture->setPixelSize(m_pixelSize);
8035 backingTexture->setSampleCount(m_sampleCount);
8036 }
8037 backingTexture->setName(m_objectName);
8039 return false;
8040 vkformat = backingTexture->vkformat;
8041 }
8042 break;
8043 case QRhiRenderBuffer::DepthStencil:
8044 vkformat = rhiD->optimalDepthStencilFormat();
8045 if (!rhiD->createTransientImage(vkformat,
8046 m_pixelSize,
8047 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
8048 VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
8049 samples,
8050 &memory,
8051 &image,
8052 &imageView,
8053 1))
8054 {
8055 return false;
8056 }
8057 rhiD->setObjectName(uint64_t(image), VK_OBJECT_TYPE_IMAGE, m_objectName);
8058 break;
8059 default:
8060 Q_UNREACHABLE();
8061 break;
8062 }
8063
8065 generation += 1;
8066 rhiD->registerResource(this);
8067 return true;
8068}
8069
8071{
8072 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
8073 return m_backingFormatHint;
8074 else
8075 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
8076}
8077
8078QVkTexture::QVkTexture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth,
8079 int arraySize, int sampleCount, Flags flags)
8081{
8082 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
8083 stagingBuffers[i] = VK_NULL_HANDLE;
8084 stagingAllocations[i] = nullptr;
8085 }
8086 for (int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i)
8087 perLevelImageViews[i] = VK_NULL_HANDLE;
8088}
8089
8091{
8092 destroy();
8093}
8094
8096{
8097 if (!image)
8098 return;
8099
8103
8104 e.texture.image = owns ? image : VK_NULL_HANDLE;
8105 e.texture.imageView = imageView;
8106 e.texture.allocation = owns ? imageAlloc : nullptr;
8107
8108 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
8109 e.texture.stagingBuffers[i] = stagingBuffers[i];
8110 e.texture.stagingAllocations[i] = stagingAllocations[i];
8111
8112 stagingBuffers[i] = VK_NULL_HANDLE;
8113 stagingAllocations[i] = nullptr;
8114 }
8115
8116 for (int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i) {
8117 e.texture.extraImageViews[i] = perLevelImageViews[i];
8118 perLevelImageViews[i] = VK_NULL_HANDLE;
8119 }
8120
8121 image = VK_NULL_HANDLE;
8122 imageView = VK_NULL_HANDLE;
8123 imageAlloc = nullptr;
8124
8125 QRHI_RES_RHI(QRhiVulkan);
8126 if (rhiD) {
8127 rhiD->releaseQueue.append(e);
8128 rhiD->unregisterResource(this);
8129 }
8130}
8131
8132bool QVkTexture::prepareCreate(QSize *adjustedSize)
8133{
8134 if (image)
8135 destroy();
8136
8137 QRHI_RES_RHI(QRhiVulkan);
8138 vkformat = toVkTextureFormat(m_format, m_flags);
8139 if (m_writeViewFormat.format != UnknownFormat)
8140 viewFormat = toVkTextureFormat(m_writeViewFormat.format, m_writeViewFormat.srgb ? sRGB : Flags());
8141 else
8142 viewFormat = vkformat;
8143 if (m_readViewFormat.format != UnknownFormat)
8144 viewFormatForSampling = toVkTextureFormat(m_readViewFormat.format, m_readViewFormat.srgb ? sRGB : Flags());
8145 else
8146 viewFormatForSampling = vkformat;
8147
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);
8153 return false;
8154 }
8155
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);
8161
8162 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
8163 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
8164
8165 mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1);
8166 const int maxLevels = QRhi::MAX_MIP_LEVELS;
8167 if (mipLevelCount > maxLevels) {
8168 qWarning("Too many mip levels (%d, max is %d), truncating mip chain", mipLevelCount, maxLevels);
8169 mipLevelCount = maxLevels;
8170 }
8171 samples = rhiD->effectiveSampleCountBits(m_sampleCount);
8172 if (samples > VK_SAMPLE_COUNT_1_BIT) {
8173 if (isCube) {
8174 qWarning("Cubemap texture cannot be multisample");
8175 return false;
8176 }
8177 if (is3D) {
8178 qWarning("3D texture cannot be multisample");
8179 return false;
8180 }
8181 if (hasMipMaps) {
8182 qWarning("Multisample texture cannot have mipmaps");
8183 return false;
8184 }
8185 }
8186 if (isCube && is3D) {
8187 qWarning("Texture cannot be both cube and 3D");
8188 return false;
8189 }
8190 if (isArray && is3D) {
8191 qWarning("Texture cannot be both array and 3D");
8192 return false;
8193 }
8194 if (isCube && is1D) {
8195 qWarning("Texture cannot be both cube and 1D");
8196 return false;
8197 }
8198 if (is1D && is3D) {
8199 qWarning("Texture cannot be both 1D and 3D");
8200 return false;
8201 }
8202 if (m_depth > 1 && !is3D) {
8203 qWarning("Texture cannot have a depth of %d when it is not 3D", m_depth);
8204 return false;
8205 }
8206 if (m_arraySize > 0 && !isArray) {
8207 qWarning("Texture cannot have an array size of %d when it is not an array", m_arraySize);
8208 return false;
8209 }
8210 if (m_arraySize < 1 && isArray) {
8211 qWarning("Texture is an array but array size is %d", m_arraySize);
8212 return false;
8213 }
8214
8215 usageState.layout = VK_IMAGE_LAYOUT_UNDEFINED;
8216 usageState.access = 0;
8217 usageState.stage = 0;
8218
8219 if (!rhiD->textureFormatInfo(m_format, size, nullptr, nullptr, nullptr))
8220 return false;
8221
8222 if (adjustedSize)
8223 *adjustedSize = size;
8224
8225 return true;
8226}
8227
8229{
8230 QRHI_RES_RHI(QRhiVulkan);
8231
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);
8237
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;
8252 // Force-remove the VK_IMAGE_ASPECT_STENCIL_BIT
8253 // Another view with this bit is probably needed for stencil
8254 viewInfo.subresourceRange.aspectMask &= ~VK_IMAGE_ASPECT_STENCIL_BIT;
8255 viewInfo.subresourceRange.levelCount = mipLevelCount;
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);
8259 } else {
8260 viewInfo.subresourceRange.layerCount = isCube ? 6 : (isArray ? qMax(0, m_arraySize) : 1);
8261 }
8262
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);
8266 return false;
8267 }
8268
8270 generation += 1;
8271
8272 return true;
8273}
8274
8276{
8277 QSize size;
8278 if (!prepareCreate(&size))
8279 return false;
8280
8281 QRHI_RES_RHI(QRhiVulkan);
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);
8288
8289 VkImageCreateInfo imageInfo = {};
8290 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
8291 imageInfo.flags = 0;
8292 if (isCube)
8293 imageInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
8294 if (viewFormat != vkformat || viewFormatForSampling != vkformat)
8295 imageInfo.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
8296
8297 if (is3D && isRenderTarget) {
8298 // This relies on a Vulkan 1.1 constant. For guaranteed proper behavior
8299 // this also requires that at run time the VkInstance has at least API 1.1
8300 // enabled. (though it works as expected with some Vulkan (1.2)
8301 // implementations regardless of the requested API version, but f.ex. the
8302 // validation layer complains when using this without enabling >=1.1)
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;
8307#else
8308 imageInfo.flags |= 0x00000020;
8309#endif
8310 }
8311
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;
8317 imageInfo.mipLevels = mipLevelCount;
8318 imageInfo.arrayLayers = isCube ? 6 : (isArray ? qMax(0, m_arraySize) : 1);
8319 imageInfo.samples = samples;
8320 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
8321 // Must be UNDEFINED (and not PREINITIALIZED) with optimal tiling. The
8322 // image is device local and is never written by the host anyway.
8323 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
8324
8325 imageInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
8326 if (isRenderTarget) {
8327 if (isDepth)
8328 imageInfo.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
8329 else
8330 imageInfo.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
8331 }
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;
8341#endif
8342
8343 VmaAllocationCreateInfo allocInfo = {};
8344 allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
8345
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),
8355 err);
8356 rhiD->printExtraErrorInfo(err);
8357 return false;
8358 }
8359 imageAlloc = allocation;
8360 rhiD->setAllocationName(allocation, m_objectName);
8361
8362 if (!finishCreate())
8363 return false;
8364
8365 rhiD->setObjectName(uint64_t(image), VK_OBJECT_TYPE_IMAGE, m_objectName);
8366
8367 owns = true;
8368 rhiD->registerResource(this);
8369 return true;
8370}
8371
8372bool QVkTexture::createFrom(QRhiTexture::NativeTexture src)
8373{
8374 VkImage img = VkImage(src.object);
8375 if (img == 0)
8376 return false;
8377
8378 if (!prepareCreate())
8379 return false;
8380
8381 image = img;
8382
8383 if (!finishCreate())
8384 return false;
8385
8386 usageState.layout = VkImageLayout(src.layout);
8387
8388 owns = false;
8389 QRHI_RES_RHI(QRhiVulkan);
8390 rhiD->registerResource(this);
8391 return true;
8392}
8393
8395{
8396 return {quint64(image), usageState.layout};
8397}
8398
8400{
8401 usageState.layout = VkImageLayout(layout);
8402}
8403
8405{
8406 Q_ASSERT(level >= 0 && level < int(mipLevelCount));
8407 if (perLevelImageViews[level] != VK_NULL_HANDLE)
8408 return perLevelImageViews[level];
8409
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);
8415
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; // this is writeViewFormat, regardless of Load, Store, or LoadStore; intentional
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);
8434
8435 VkImageView v = VK_NULL_HANDLE;
8436 QRHI_RES_RHI(QRhiVulkan);
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;
8441 }
8442
8443 perLevelImageViews[level] = v;
8444 return v;
8445}
8446
8447QVkSampler::QVkSampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode,
8448 AddressMode u, AddressMode v, AddressMode w)
8450{
8451}
8452
8454{
8455 destroy();
8456}
8457
8459{
8460 if (!sampler)
8461 return;
8462
8466
8467 e.sampler.sampler = sampler;
8468 sampler = VK_NULL_HANDLE;
8469
8470 QRHI_RES_RHI(QRhiVulkan);
8471 if (rhiD) {
8472 rhiD->releaseQueue.append(e);
8473 rhiD->unregisterResource(this);
8474 }
8475}
8476
8478{
8479 if (sampler)
8480 destroy();
8481
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;
8494
8495 QRHI_RES_RHI(QRhiVulkan);
8496 VkResult err = rhiD->df->vkCreateSampler(rhiD->dev, &samplerInfo, nullptr, &sampler);
8497 if (err != VK_SUCCESS) {
8498 qWarning("Failed to create sampler: %d", err);
8499 return false;
8500 }
8501
8503 generation += 1;
8504 rhiD->registerResource(this);
8505 return true;
8506}
8507
8510{
8511 serializedFormatData.reserve(64);
8512}
8513
8518
8520{
8521 if (!rp)
8522 return;
8523
8524 if (!ownsRp) {
8525 rp = VK_NULL_HANDLE;
8526 return;
8527 }
8528
8532
8533 e.renderPass.rp = rp;
8534
8535 rp = VK_NULL_HANDLE;
8536
8537 QRHI_RES_RHI(QRhiVulkan);
8538 if (rhiD) {
8539 rhiD->releaseQueue.append(e);
8540 rhiD->unregisterResource(this);
8541 }
8542}
8543
8544static inline bool attachmentDescriptionEquals(const VkAttachmentDescription &a, const VkAttachmentDescription &b)
8545{
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;
8554}
8555
8556bool QVkRenderPassDescriptor::isCompatible(const QRhiRenderPassDescriptor *other) const
8557{
8558 if (other == this)
8559 return true;
8560
8561 if (!other)
8562 return false;
8563
8565
8566 if (attDescs.size() != o->attDescs.size())
8567 return false;
8568 if (colorRefs.size() != o->colorRefs.size())
8569 return false;
8570 if (resolveRefs.size() != o->resolveRefs.size())
8571 return false;
8573 return false;
8575 return false;
8576 if (multiViewCount != o->multiViewCount)
8577 return false;
8579 return false;
8580
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)
8584 return false;
8585 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8586 return false;
8587 }
8588
8589 if (hasDepthStencil) {
8590 const uint32_t attIdx = dsRef.attachment;
8591 if (attIdx != o->dsRef.attachment)
8592 return false;
8593 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8594 return false;
8595 }
8596
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)
8600 return false;
8601 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8602 return false;
8603 }
8604
8606 const uint32_t attIdx = dsResolveRef.attachment;
8607 if (attIdx != o->dsResolveRef.attachment)
8608 return false;
8609 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8610 return false;
8611 }
8612
8613 if (hasShadingRateMap) {
8614 const uint32_t attIdx = shadingRateRef.attachment;
8615 if (attIdx != o->shadingRateRef.attachment)
8616 return false;
8617 if (attIdx != VK_ATTACHMENT_UNUSED && !attachmentDescriptionEquals(attDescs[attIdx], o->attDescs[attIdx]))
8618 return false;
8619 }
8620
8621 // subpassDeps is not included
8622
8623 return true;
8624}
8625
8627{
8628 serializedFormatData.clear();
8629 auto p = std::back_inserter(serializedFormatData);
8630
8631 *p++ = attDescs.size();
8632 *p++ = colorRefs.size();
8633 *p++ = resolveRefs.size();
8634 *p++ = hasDepthStencil;
8636 *p++ = hasShadingRateMap;
8637 *p++ = multiViewCount;
8638
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;
8650 };
8651
8652 for (int i = 0, ie = colorRefs.size(); i != ie; ++i) {
8653 const uint32_t attIdx = colorRefs[i].attachment;
8654 *p++ = attIdx;
8655 serializeAttachmentData(attIdx);
8656 }
8657
8658 if (hasDepthStencil) {
8659 const uint32_t attIdx = dsRef.attachment;
8660 *p++ = attIdx;
8661 serializeAttachmentData(attIdx);
8662 }
8663
8664 for (int i = 0, ie = resolveRefs.size(); i != ie; ++i) {
8665 const uint32_t attIdx = resolveRefs[i].attachment;
8666 *p++ = attIdx;
8667 serializeAttachmentData(attIdx);
8668 }
8669
8671 const uint32_t attIdx = dsResolveRef.attachment;
8672 *p++ = attIdx;
8673 serializeAttachmentData(attIdx);
8674 }
8675
8676 if (hasShadingRateMap) {
8677 const uint32_t attIdx = shadingRateRef.attachment;
8678 *p++ = attIdx;
8679 serializeAttachmentData(attIdx);
8680 }
8681}
8682
8684{
8685 QVkRenderPassDescriptor *rpD = new QVkRenderPassDescriptor(m_rhi);
8686
8687 rpD->ownsRp = true;
8688 rpD->attDescs = attDescs;
8689 rpD->colorRefs = colorRefs;
8690 rpD->resolveRefs = resolveRefs;
8691 rpD->subpassDeps = subpassDeps;
8695 rpD->multiViewCount = multiViewCount;
8696 rpD->dsRef = dsRef;
8697 rpD->dsResolveRef = dsResolveRef;
8698 rpD->shadingRateRef = shadingRateRef;
8699
8700 VkRenderPassCreateInfo rpInfo;
8701 VkSubpassDescription subpassDesc;
8702 fillRenderPassCreateInfo(&rpInfo, &subpassDesc, rpD);
8703
8704 QRHI_RES_RHI(QRhiVulkan);
8705 MultiViewRenderPassSetupHelper multiViewHelper;
8706 if (!multiViewHelper.prepare(&rpInfo, multiViewCount, rhiD->caps.multiView)) {
8707 delete rpD;
8708 return nullptr;
8709 }
8710
8711#ifdef VK_KHR_create_renderpass2
8712 if (rhiD->caps.renderPass2KHR) {
8713 // Use the KHR extension, not the 1.2 core API, in order to support Vulkan 1.1.
8714 VkRenderPassCreateInfo2KHR rpInfo2;
8715 RenderPass2SetupHelper rp2Helper(rhiD);
8716 if (!rp2Helper.prepare(&rpInfo2, &rpInfo, rpD, multiViewCount)) {
8717 delete rpD;
8718 return nullptr;
8719 }
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);
8723 delete rpD;
8724 return nullptr;
8725 }
8726 } else
8727#endif
8728 {
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);
8732 delete rpD;
8733 return nullptr;
8734 }
8735 }
8736
8738 rhiD->registerResource(rpD);
8739 return rpD;
8740}
8741
8743{
8744 return serializedFormatData;
8745}
8746
8748{
8749 nativeHandlesStruct.renderPass = rp;
8750 return &nativeHandlesStruct;
8751}
8752
8753QVkShadingRateMap::QVkShadingRateMap(QRhiImplementation *rhi)
8755{
8756}
8757
8762
8764{
8765 if (!texture)
8766 return;
8767
8768 texture = nullptr;
8769}
8770
8771bool QVkShadingRateMap::createFrom(QRhiTexture *src)
8772{
8773 if (texture)
8774 destroy();
8775
8776 texture = QRHI_RES(QVkTexture, src);
8777
8778 return true;
8779}
8780
8781QVkSwapChainRenderTarget::QVkSwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
8783{
8784}
8785
8790
8792{
8793 // nothing to do here
8794}
8795
8797{
8798 return d.pixelSize;
8799}
8800
8802{
8803 return d.dpr;
8804}
8805
8807{
8808 return d.sampleCount;
8809}
8810
8812 const QRhiTextureRenderTargetDescription &desc,
8813 Flags flags)
8815{
8816 for (int att = 0; att < QVkRenderTargetData::MAX_COLOR_ATTACHMENTS; ++att) {
8817 rtv[att] = VK_NULL_HANDLE;
8818 resrtv[att] = VK_NULL_HANDLE;
8819 }
8820}
8821
8826
8828{
8829 if (!d.fb)
8830 return;
8831
8835
8836 e.textureRenderTarget.fb = d.fb;
8837 d.fb = VK_NULL_HANDLE;
8838
8839 for (int att = 0; att < QVkRenderTargetData::MAX_COLOR_ATTACHMENTS; ++att) {
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;
8844 }
8845
8846 e.textureRenderTarget.dsv = dsv;
8847 dsv = VK_NULL_HANDLE;
8848 e.textureRenderTarget.resdsv = resdsv;
8849 resdsv = VK_NULL_HANDLE;
8850
8851 e.textureRenderTarget.shadingRateMapView = shadingRateMapView;
8852 shadingRateMapView = VK_NULL_HANDLE;
8853
8854 QRHI_RES_RHI(QRhiVulkan);
8855 if (rhiD) {
8856 rhiD->releaseQueue.append(e);
8857 rhiD->unregisterResource(this);
8858 }
8859}
8860
8862{
8863 // not yet built so cannot rely on data computed in create()
8864
8865 QRHI_RES_RHI(QRhiVulkan);
8866 QVkRenderPassDescriptor *rp = new QVkRenderPassDescriptor(m_rhi);
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()))
8878 {
8879 delete rp;
8880 return nullptr;
8881 }
8882
8883 rp->ownsRp = true;
8885 rhiD->registerResource(rp);
8886 return rp;
8887}
8888
8890{
8891 if (d.fb)
8892 destroy();
8893
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();
8897
8898 QRHI_RES_RHI(QRhiVulkan);
8899 QVarLengthArray<VkImageView, 8> views;
8900 d.multiViewCount = 0;
8901
8902 d.colorAttCount = 0;
8903 int attIndex = 0;
8904 for (auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
8905 d.colorAttCount += 1;
8906 QVkTexture *texD = QRHI_RES(QVkTexture, it->texture());
8907 QVkRenderBuffer *rbD = QRHI_RES(QVkRenderBuffer, it->renderBuffer());
8908 Q_ASSERT(texD || rbD);
8909 if (texD) {
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);
8934 return false;
8935 }
8936 views.append(rtv[attIndex]);
8937 if (attIndex == 0) {
8938 d.pixelSize = rhiD->q->sizeForMipLevel(it->level(), texD->pixelSize());
8939 d.sampleCount = texD->samples;
8940 }
8941 } else if (rbD) {
8942 Q_ASSERT(rbD->backingTexture);
8943 views.append(rbD->backingTexture->imageView);
8944 if (attIndex == 0) {
8945 d.pixelSize = rbD->pixelSize();
8946 d.sampleCount = rbD->samples;
8947 }
8948 }
8949 }
8950 d.dpr = 1;
8951
8952 if (hasDepthStencil) {
8953 if (m_desc.depthTexture()) {
8954 QVkTexture *depthTexD = QRHI_RES(QVkTexture, m_desc.depthTexture());
8955 // need a dedicated view just because viewFormat may differ from vkformat
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;
8970 }
8971 else
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);
8976 return false;
8977 }
8978 views.append(dsv);
8979 if (d.colorAttCount == 0) {
8980 d.pixelSize = depthTexD->pixelSize();
8981 d.sampleCount = depthTexD->samples;
8982 }
8983 } else {
8984 QVkRenderBuffer *depthRbD = QRHI_RES(QVkRenderBuffer, m_desc.depthStencilBuffer());
8985 views.append(depthRbD->imageView);
8986 if (d.colorAttCount == 0) {
8987 d.pixelSize = depthRbD->pixelSize();
8988 d.sampleCount = depthRbD->samples;
8989 }
8990 }
8991 d.dsAttCount = 1;
8992 } else {
8993 d.dsAttCount = 0;
8994 }
8995
8996 d.resolveAttCount = 0;
8997 attIndex = 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()) {
9001 QVkTexture *resTexD = QRHI_RES(QVkTexture, it->resolveTexture());
9002 Q_ASSERT(resTexD->flags().testFlag(QRhiTexture::RenderTarget));
9003 d.resolveAttCount += 1;
9004
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);
9023 return false;
9024 }
9025 views.append(resrtv[attIndex]);
9026 }
9027 }
9028
9029 if (m_desc.depthResolveTexture()) {
9030 QVkTexture *resTexD = QRHI_RES(QVkTexture, m_desc.depthResolveTexture());
9031 Q_ASSERT(resTexD->flags().testFlag(QRhiTexture::RenderTarget));
9032
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);
9051 return false;
9052 }
9053 views.append(resdsv);
9054 d.dsResolveAttCount = 1;
9055 } else {
9056 d.dsResolveAttCount = 0;
9057 }
9058
9059 if (m_desc.shadingRateMap() && rhiD->caps.renderPass2KHR && rhiD->caps.imageBasedShadingRate) {
9060 QVkTexture *texD = QRHI_RES(QVkShadingRateMap, m_desc.shadingRateMap())->texture;
9061 Q_ASSERT(texD->flags().testFlag(QRhiTexture::UsedAsShadingRateMap));
9062
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);
9081 return false;
9082 }
9083 views.append(shadingRateMapView);
9084 d.shadingRateAttCount = 1;
9085 } else {
9086 d.shadingRateAttCount = 0;
9087 }
9088
9089 if (!m_renderPassDesc)
9090 qWarning("QVkTextureRenderTarget: No renderpass descriptor set. See newCompatibleRenderPassDescriptor() and setRenderPassDescriptor().");
9091
9092 d.rp = QRHI_RES(QVkRenderPassDescriptor, m_renderPassDesc);
9093 Q_ASSERT(d.rp && d.rp->rp);
9094
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());
9102 fbInfo.layers = 1;
9103
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);
9107 return false;
9108 }
9109
9110 QRhiRenderTargetAttachmentTracker::updateResIdList<QVkTexture, QVkRenderBuffer>(m_desc, &d.currentResIdList);
9111
9113 rhiD->registerResource(this);
9114 return true;
9115}
9116
9118{
9119 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QVkTexture, QVkRenderBuffer>(m_desc, d.currentResIdList))
9120 const_cast<QVkTextureRenderTarget *>(this)->create();
9121
9122 return d.pixelSize;
9123}
9124
9126{
9127 return d.dpr;
9128}
9129
9131{
9132 return d.sampleCount;
9133}
9134
9139
9144
9146{
9147 if (!layout)
9148 return;
9149
9150 sortedBindings.clear();
9151 sortedDynamicOffsetBindingNumbers.clear();
9152
9156
9157 e.shaderResourceBindings.poolIndex = poolIndex;
9158 e.shaderResourceBindings.layout = layout;
9159
9160 poolIndex = -1;
9161 layout = VK_NULL_HANDLE;
9162 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i)
9163 descSets[i] = VK_NULL_HANDLE;
9164
9165 QRHI_RES_RHI(QRhiVulkan);
9166 if (rhiD) {
9167 rhiD->releaseQueue.append(e);
9168 rhiD->unregisterResource(this);
9169 }
9170}
9171
9173{
9174 if (layout)
9175 destroy();
9176
9177 QRHI_RES_RHI(QRhiVulkan);
9178 if (!rhiD->sanityCheckShaderResourceBindings(this))
9179 return false;
9180
9181 rhiD->updateLayoutDesc(this);
9182
9183 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i)
9184 descSets[i] = VK_NULL_HANDLE;
9185
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);
9189
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);
9196 }
9197 }
9198
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();
9208 else
9209 vkbinding.descriptorCount = 1;
9210 vkbinding.stageFlags = toVkShaderStageFlags(b->stage);
9211 }
9212
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();
9217
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);
9221 return false;
9222 }
9223 rhiD->setObjectName(uint64_t(layout), VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, m_objectName);
9224
9225 VkDescriptorSetAllocateInfo allocInfo = {};
9226 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
9227 allocInfo.descriptorSetCount = QVK_FRAMES_IN_FLIGHT;
9228 VkDescriptorSetLayout layouts[QVK_FRAMES_IN_FLIGHT];
9229 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i)
9230 layouts[i] = layout;
9231 allocInfo.pSetLayouts = layouts;
9232 if (!rhiD->allocateDescriptorSet(&allocInfo, descSets, &poolIndex))
9233 return false;
9234
9235 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
9236 boundResourceData[i].resize(sortedBindings.size());
9237 for (BoundResourceData &bd : boundResourceData[i])
9238 bd = {};
9239 }
9240
9241 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i)
9242 rhiD->setObjectName(uint64_t(descSets[i]), VK_OBJECT_TYPE_DESCRIPTOR_SET, m_objectName, i);
9243
9245 generation += 1;
9246 rhiD->registerResource(this);
9247 return true;
9248}
9249
9251{
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);
9256
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);
9263 }
9264 }
9265
9266 // Reset the state tracking table too - it can deal with assigning a
9267 // different QRhiBuffer/Texture/Sampler for a binding point, but it cannot
9268 // detect changes in the associated data, such as the buffer offset. And
9269 // just like after a create(), a call to updateResources() may lead to now
9270 // specifying a different offset for the same QRhiBuffer for a given binding
9271 // point. The same applies to other type of associated data that is not part
9272 // of the layout, such as the mip level for a StorageImage. Instead of
9273 // complicating the checks in setShaderResources(), reset the table here
9274 // just like we do in create().
9275 for (int i = 0; i < QVK_FRAMES_IN_FLIGHT; ++i) {
9276 Q_ASSERT(boundResourceData[i].size() == sortedBindings.size());
9277 for (BoundResourceData &bd : boundResourceData[i])
9278 bd = {};
9279 }
9280
9281 generation += 1;
9282}
9283
9286{
9287}
9288
9293
9295{
9296 if (!pipeline && !layout)
9297 return;
9298
9302
9303 e.pipelineState.pipeline = pipeline;
9304 e.pipelineState.layout = layout;
9305
9306 pipeline = VK_NULL_HANDLE;
9307 layout = VK_NULL_HANDLE;
9308
9309 QRHI_RES_RHI(QRhiVulkan);
9310 if (rhiD) {
9311 rhiD->releaseQueue.append(e);
9312 rhiD->unregisterResource(this);
9313 }
9314}
9315
9317{
9318 if (pipeline || layout)
9319 destroy();
9320
9321 QRHI_RES_RHI(QRhiVulkan);
9322 rhiD->pipelineCreationStart();
9323 if (!rhiD->sanityCheckGraphicsPipeline(this))
9324 return false;
9325
9326 if (!rhiD->ensurePipelineCache())
9327 return false;
9328
9329 VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
9330 pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
9331 pipelineLayoutInfo.setLayoutCount = 1;
9332 QVkShaderResourceBindings *srbD = QRHI_RES(QVkShaderResourceBindings, m_shaderResourceBindings);
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));
9340 }
9341 }
9342 if (pushConstantRange.size) {
9343 pipelineLayoutInfo.pushConstantRangeCount = 1;
9344 pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange;
9345 }
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);
9350 return false;
9351 }
9352 auto pipelineLayoutCleanup = qScopeGuard([this, rhiD] {
9353 rhiD->df->vkDestroyPipelineLayout(rhiD->dev, layout, nullptr);
9354 layout = VK_NULL_HANDLE;
9355 });
9356
9357 VkGraphicsPipelineCreateInfo pipelineInfo = {};
9358 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
9359
9360 QVarLengthArray<VkShaderModule, 4> shaders;
9361 auto shaderModuleCleanup = qScopeGuard([rhiD, &shaders] {
9362 for (VkShaderModule shader : shaders)
9363 rhiD->df->vkDestroyShaderModule(rhiD->dev, shader, nullptr);
9364 });
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;
9372 return false;
9373 }
9374 VkShaderModule shader = rhiD->createShader(spirv.shader());
9375 if (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);
9384 }
9385 else
9386 return false;
9387 }
9388 for (qsizetype i = 0, ie = shaders.count(); i != ie; ++i)
9389 shaderStageCreateInfos[i].pName = entryPointNames[i].constData();
9390
9391 pipelineInfo.stageCount = uint32_t(shaderStageCreateInfos.size());
9392 pipelineInfo.pStages = shaderStageCreateInfos.constData();
9393
9394 QVarLengthArray<VkVertexInputBindingDescription, 4> vertexBindings;
9395#ifdef VK_EXT_vertex_attribute_divisor
9396 QVarLengthArray<VkVertexInputBindingDivisorDescriptionEXT> nonOneStepRates;
9397#endif
9398 int bindingIndex = 0;
9399 for (auto it = m_vertexInputLayout.cbeginBindings(), itEnd = m_vertexInputLayout.cendBindings();
9400 it != itEnd; ++it, ++bindingIndex)
9401 {
9402 VkVertexInputBindingDescription bindingInfo = {
9403 uint32_t(bindingIndex),
9404 it->stride(),
9405 it->classification() == QRhiVertexInputBinding::PerVertex
9406 ? VK_VERTEX_INPUT_RATE_VERTEX : VK_VERTEX_INPUT_RATE_INSTANCE
9407 };
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() });
9412 } else
9413#endif
9414 {
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");
9418 }
9419 }
9420 vertexBindings.append(bindingInfo);
9421 }
9422 QVarLengthArray<VkVertexInputAttributeDescription, 4> vertexAttributes;
9423 for (auto it = m_vertexInputLayout.cbeginAttributes(), itEnd = m_vertexInputLayout.cendAttributes();
9424 it != itEnd; ++it)
9425 {
9426 VkVertexInputAttributeDescription attributeInfo = {
9427 uint32_t(it->location()),
9428 uint32_t(it->binding()),
9429 toVkAttributeFormat(it->format()),
9430 it->offset()
9431 };
9432 vertexAttributes.append(attributeInfo);
9433 }
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;
9447 }
9448#endif
9449 pipelineInfo.pVertexInputState = &vertexInputInfo;
9450
9451 QVarLengthArray<VkDynamicState, 8> dynEnable;
9452 dynEnable << VK_DYNAMIC_STATE_VIEWPORT;
9453 dynEnable << VK_DYNAMIC_STATE_SCISSOR; // ignore UsesScissor - Vulkan requires a scissor for the viewport always
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;
9461#endif
9462
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;
9468
9469 VkPipelineViewportStateCreateInfo viewportInfo = {};
9470 viewportInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
9471 viewportInfo.viewportCount = viewportInfo.scissorCount = 1;
9472 pipelineInfo.pViewportState = &viewportInfo;
9473
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;
9479
9480 VkPipelineTessellationStateCreateInfo tessInfo = {};
9481#ifdef VK_VERSION_1_1
9482 VkPipelineTessellationDomainOriginStateCreateInfo originInfo = {};
9483#endif
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));
9487
9488 // To be able to use the same tess.evaluation shader with both OpenGL
9489 // and Vulkan, flip the tessellation domain origin to be lower left.
9490 // This allows declaring the winding order in the shader to be CCW and
9491 // still have it working with both APIs. This requires Vulkan 1.1 (or
9492 // VK_KHR_maintenance2 but don't bother with that).
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;
9498 } else {
9499 qWarning("Proper tessellation support requires Vulkan 1.1 or newer, leaving domain origin unset");
9500 }
9501#else
9502 qWarning("QRhi was built without Vulkan 1.1 headers, this is not sufficient for proper tessellation support");
9503#endif
9504
9505 pipelineInfo.pTessellationState = &tessInfo;
9506 }
9507
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;
9518 }
9519 rastInfo.lineWidth = rhiD->caps.wideLines ? m_lineWidth : 1.0f;
9520 rastInfo.polygonMode = toVkPolygonMode(m_polygonMode);
9521 pipelineInfo.pRasterizationState = &rastInfo;
9522
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;
9527
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;
9541 }
9542 pipelineInfo.pDepthStencilState = &dsInfo;
9543
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);
9558 }
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);
9564 }
9565 blendInfo.attachmentCount = uint32_t(vktargetBlends.size());
9566 blendInfo.pAttachments = vktargetBlends.constData();
9567 pipelineInfo.pColorBlendState = &blendInfo;
9568
9569 pipelineInfo.layout = layout;
9570
9571 Q_ASSERT(m_renderPassDesc && QRHI_RES(const QVkRenderPassDescriptor, m_renderPassDesc)->rp);
9572 pipelineInfo.renderPass = QRHI_RES(const QVkRenderPassDescriptor, m_renderPassDesc)->rp;
9573
9574 err = rhiD->df->vkCreateGraphicsPipelines(rhiD->dev, rhiD->pipelineCache, 1, &pipelineInfo, nullptr, &pipeline);
9575
9576 if (err != VK_SUCCESS) {
9577 qWarning("Failed to create graphics pipeline: %d", err);
9578 return false;
9579 }
9580 pipelineLayoutCleanup.dismiss();
9581
9582 rhiD->setObjectName(uint64_t(pipeline), VK_OBJECT_TYPE_PIPELINE, m_objectName);
9583
9584 rhiD->pipelineCreationEnd();
9585 lastActiveFrameSlot = -1;
9586 generation += 1;
9587 rhiD->registerResource(this);
9588 return true;
9589}
9590
9591QVkComputePipeline::QVkComputePipeline(QRhiImplementation *rhi)
9592 : QRhiComputePipeline(rhi)
9593{
9594}
9595
9596QVkComputePipeline::~QVkComputePipeline()
9597{
9598 destroy();
9599}
9600
9601void QVkComputePipeline::destroy()
9602{
9603 if (!pipeline && !layout)
9604 return;
9605
9606 QRhiVulkan::DeferredReleaseEntry e;
9607 e.type = QRhiVulkan::DeferredReleaseEntry::Pipeline;
9608 e.lastActiveFrameSlot = lastActiveFrameSlot;
9609
9610 e.pipelineState.pipeline = pipeline;
9611 e.pipelineState.layout = layout;
9612
9613 pipeline = VK_NULL_HANDLE;
9614 layout = VK_NULL_HANDLE;
9615
9616 QRHI_RES_RHI(QRhiVulkan);
9617 if (rhiD) {
9618 rhiD->releaseQueue.append(e);
9619 rhiD->unregisterResource(this);
9620 }
9621}
9622
9623bool QVkComputePipeline::create()
9624{
9625 if (pipeline || layout)
9626 destroy();
9627
9628 QRHI_RES_RHI(QRhiVulkan);
9629 rhiD->pipelineCreationStart();
9630 if (!rhiD->ensurePipelineCache())
9631 return false;
9632
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));
9643 }
9644 if (pushConstantRange.size) {
9645 pipelineLayoutInfo.pushConstantRangeCount = 1;
9646 pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange;
9647 }
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);
9652 return false;
9653 }
9654 auto pipelineLayoutCleanup = qScopeGuard([this, rhiD] {
9655 rhiD->df->vkDestroyPipelineLayout(rhiD->dev, layout, nullptr);
9656 layout = VK_NULL_HANDLE;
9657 });
9658
9659 VkComputePipelineCreateInfo pipelineInfo = {};
9660 pipelineInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
9661 pipelineInfo.layout = layout;
9662
9663 if (m_shaderStage.type() != QRhiShaderStage::Compute) {
9664 qWarning("Compute pipeline requires a compute shader stage");
9665 return false;
9666 }
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;
9671 return false;
9672 }
9673 if (bakedShader.stage() != QShader::ComputeStage) {
9674 qWarning() << bakedShader << "is not a compute shader";
9675 return false;
9676 }
9677 VkShaderModule shader = rhiD->createShader(spirv.shader());
9678 if (!shader)
9679 return false;
9680 auto shaderModuleCleanup = qScopeGuard([rhiD, shader] {
9681 rhiD->df->vkDestroyShaderModule(rhiD->dev, shader, nullptr);
9682 });
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;
9690
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);
9694 return false;
9695 }
9696 pipelineLayoutCleanup.dismiss();
9697
9698 rhiD->setObjectName(uint64_t(pipeline), VK_OBJECT_TYPE_PIPELINE, m_objectName);
9699
9700 rhiD->pipelineCreationEnd();
9701 lastActiveFrameSlot = -1;
9702 generation += 1;
9703 rhiD->registerResource(this);
9704 return true;
9705}
9706
9707QVkCommandBuffer::QVkCommandBuffer(QRhiImplementation *rhi)
9708 : QRhiCommandBuffer(rhi)
9709{
9710 resetState();
9711}
9712
9713QVkCommandBuffer::~QVkCommandBuffer()
9714{
9715 destroy();
9716}
9717
9718void QVkCommandBuffer::destroy()
9719{
9720 // nothing to do here, cb is not owned by us
9721}
9722
9723const QRhiNativeHandles *QVkCommandBuffer::nativeHandles()
9724{
9725 // Ok this is messy but no other way has been devised yet. Outside
9726 // begin(Compute)Pass - end(Compute)Pass it is simple - just return the
9727 // primary VkCommandBuffer. Inside, however, we need to provide the current
9728 // secondary command buffer (typically the one started by beginExternal(),
9729 // in case we are between beginExternal - endExternal inside a pass).
9730
9731 if (recordingPass == QVkCommandBuffer::NoPass) {
9732 nativeHandlesStruct.commandBuffer = cb;
9733 } else {
9734 if (passUsesSecondaryCb && !activeSecondaryCbStack.isEmpty())
9735 nativeHandlesStruct.commandBuffer = activeSecondaryCbStack.last();
9736 else
9737 nativeHandlesStruct.commandBuffer = cb;
9738 }
9739
9740 return &nativeHandlesStruct;
9741}
9742
9743QVkSwapChain::QVkSwapChain(QRhiImplementation *rhi)
9744 : QRhiSwapChain(rhi),
9745 rtWrapper(rhi, this),
9746 rtWrapperRight(rhi, this),
9747 cbWrapper(rhi)
9748{
9749}
9750
9751QVkSwapChain::~QVkSwapChain()
9752{
9753 destroy();
9754}
9755
9756void QVkSwapChain::destroy()
9757{
9758 if (sc == VK_NULL_HANDLE)
9759 return;
9760
9761 QRHI_RES_RHI(QRhiVulkan);
9762 if (rhiD) {
9763 rhiD->swapchains.remove(this);
9764 rhiD->releaseSwapChainResources(this);
9765 }
9766
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;
9771 }
9772
9773 surface = lastConnectedSurface = VK_NULL_HANDLE;
9774
9775 if (rhiD)
9776 rhiD->unregisterResource(this);
9777}
9778
9779QRhiCommandBuffer *QVkSwapChain::currentFrameCommandBuffer()
9780{
9781 return &cbWrapper;
9782}
9783
9784QRhiRenderTarget *QVkSwapChain::currentFrameRenderTarget()
9785{
9786 return &rtWrapper;
9787}
9788
9789QRhiRenderTarget *QVkSwapChain::currentFrameRenderTarget(StereoTargetBuffer targetBuffer)
9790{
9791 return !stereo || targetBuffer == StereoTargetBuffer::LeftBuffer ? &rtWrapper : &rtWrapperRight;
9792}
9793
9794QSize QVkSwapChain::surfacePixelSize()
9795{
9796 if (!ensureSurface())
9797 return QSize();
9798
9799 // The size from the QWindow may not exactly match the surface... so if a
9800 // size is reported from the surface, use that.
9801 VkSurfaceCapabilitiesKHR surfaceCaps = {};
9802 QRHI_RES_RHI(QRhiVulkan);
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();
9808 }
9809 return QSize(int(bufferSize.width), int(bufferSize.height));
9810}
9811
9812static inline bool hdrFormatMatchesVkSurfaceFormat(QRhiSwapChain::Format f, const VkSurfaceFormatKHR &s)
9813{
9814 switch (f) {
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;
9824 default:
9825 break;
9826 }
9827 return false;
9828}
9829
9830bool QVkSwapChain::isFormatSupported(Format f)
9831{
9832 if (f == SDR)
9833 return true;
9834
9835 if (!m_window) {
9836 qWarning("Attempted to call isFormatSupported() without a window set");
9837 return false;
9838 }
9839
9840 // we may be called before create so query the surface
9841 VkSurfaceKHR surf = QVulkanInstance::surfaceForWindow(m_window);
9842
9843 QRHI_RES_RHI(QRhiVulkan);
9844 uint32_t formatCount = 0;
9845 rhiD->vkGetPhysicalDeviceSurfaceFormatsKHR(rhiD->physDev, surf, &formatCount, nullptr);
9846 QVarLengthArray<VkSurfaceFormatKHR, 8> formats(formatCount);
9847 if (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]))
9851 return true;
9852 }
9853 }
9854
9855 return false;
9856}
9857
9858QRhiSwapChainHdrInfo QVkSwapChain::hdrInfo()
9859{
9860 QRhiSwapChainHdrInfo info = QRhiSwapChain::hdrInfo();
9861#ifdef Q_OS_WIN
9862 QRHI_RES_RHI(QRhiVulkan);
9863 // Must use m_window, not window, given this may be called before createOrResize().
9864 if (m_window && rhiD->adapterLuidValid)
9865 info = rhiD->dxgiHdrInfo->queryHdrInfo(m_window);
9866#endif
9867 return info;
9868}
9869
9870QRhiRenderPassDescriptor *QVkSwapChain::newCompatibleRenderPassDescriptor()
9871{
9872 // not yet built so cannot rely on data computed in createOrResize()
9873
9874 if (!ensureSurface()) // make sure sampleCount and colorFormat reflect what was requested
9875 return nullptr;
9876
9877 QRHI_RES_RHI(QRhiVulkan);
9878 QVkRenderPassDescriptor *rp = new QVkRenderPassDescriptor(m_rhi);
9879 if (!rhiD->createDefaultRenderPass(rp,
9880 m_depthStencil != nullptr,
9881 samples,
9882 colorFormat,
9883 m_shadingRateMap))
9884 {
9885 delete rp;
9886 return nullptr;
9887 }
9888
9889 rp->ownsRp = true;
9890 rp->updateSerializedFormat();
9891 rhiD->registerResource(rp);
9892 return rp;
9893}
9894
9895static inline bool isSrgbFormat(VkFormat format)
9896{
9897 switch (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:
9905 return true;
9906 default:
9907 return false;
9908 }
9909}
9910
9911bool QVkSwapChain::ensureSurface()
9912{
9913 // Do nothing when already done, however window may change so check the
9914 // surface is still the same. Some of the queries below are very expensive
9915 // with some implementations so it is important to do the rest only once
9916 // per surface.
9917
9918 Q_ASSERT(m_window);
9919 VkSurfaceKHR surf = QVulkanInstance::surfaceForWindow(m_window);
9920 if (!surf) {
9921 qWarning("Failed to get surface for window");
9922 return false;
9923 }
9924 if (surface == surf)
9925 return true;
9926
9927 surface = surf;
9928
9929 QRHI_RES_RHI(QRhiVulkan);
9930 if (!rhiD->inst->supportsPresent(rhiD->physDev, rhiD->gfxQueueFamilyIdx, m_window)) {
9931 qWarning("Presenting not supported on this window");
9932 return false;
9933 }
9934
9935 quint32 formatCount = 0;
9936 rhiD->vkGetPhysicalDeviceSurfaceFormatsKHR(rhiD->physDev, surface, &formatCount, nullptr);
9937 QList<VkSurfaceFormatKHR> formats(formatCount);
9938 rhiD->vkGetPhysicalDeviceSurfaceFormatsKHR(rhiD->physDev, surface, &formatCount,
9939 formats.data());
9940
9941 // Initially select the first available format, will only be used as a worst-case fallback
9942 colorFormat = formats.constFirst().format;
9943 colorSpace = formats.constFirst().colorSpace;
9944
9945 // See if we can find the preferred SDR format
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) {
9950 bool ok;
9951 if (srgbRequested) {
9952 ok = defaultSrgbColorFormat == formats[i].format;
9953 } else {
9954 ok = defaultColorFormat == formats[i].format;
9955 }
9956 if (ok) {
9957 foundBestFormat = true;
9958 colorFormat = formats[i].format;
9959 colorSpace = formats[i].colorSpace;
9960 break;
9961 }
9962 }
9963 }
9964
9965 // Otherwise pick one that fits our requirements:
9966 if (!foundBestFormat && (m_format != SDR || srgbRequested)) {
9967 for (int i = 0; i < int(formatCount); ++i) {
9968 bool ok = false;
9969 if (m_format != SDR) {
9970 ok = hdrFormatMatchesVkSurfaceFormat(m_format, formats[i]);
9971 } else if (srgbRequested) {
9972 ok = isSrgbFormat(formats[i].format);
9973 }
9974 if (ok) {
9975 colorFormat = formats[i].format;
9976 colorSpace = formats[i].colorSpace;
9977 break;
9978 }
9979 }
9980 }
9981
9982 // Although this should be rare, warn when we fail to select a suitable format
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",
9989 colorFormat);
9990 }
9991 } else {
9992 if (srgbRequested && !isSrgbFormat(colorFormat)) {
9993 qWarning("Failed to select a suitable VkFormat for sRGB, using format %d as fallback",
9994 colorFormat);
9995 }
9996 }
9997
9998#if QT_CONFIG(wayland)
9999 // On Wayland, only one color management surface can be created at a time without
10000 // triggering a protocol error, and we create one ourselves in some situations.
10001 // To avoid this problem, use VK_COLOR_SPACE_PASS_THROUGH_EXT when supported,
10002 // so that the driver doesn't create a color management surface as well.
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;
10007 });
10008 if (hasPassThrough) {
10009 colorSpace = VK_COLOR_SPACE_PASS_THROUGH_EXT;
10010 }
10011#endif
10012
10013 samples = rhiD->effectiveSampleCountBits(m_sampleCount);
10014
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());
10020
10021 return true;
10022}
10023
10024bool QVkSwapChain::createOrResize()
10025{
10026 QRHI_RES_RHI(QRhiVulkan);
10027 const bool needsRegistration = !window || window != m_window;
10028
10029 // Can be called multiple times due to window resizes - that is not the
10030 // same as a simple destroy+create (as with other resources). Thus no
10031 // destroy() here. See recreateSwapChain().
10032
10033 // except if the window actually changes
10034 if (window && window != m_window)
10035 destroy();
10036
10037 window = m_window;
10038 pixelSize = surfacePixelSize();
10039
10040 if (!rhiD->recreateSwapChain(this)) {
10041 qWarning("Failed to create new swapchain");
10042 return false;
10043 }
10044
10045 if (needsRegistration || !rhiD->swapchains.contains(this))
10046 rhiD->swapchains.insert(this);
10047
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);
10051 }
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());
10058 } else {
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());
10062 }
10063 }
10064
10065 if (!m_renderPassDesc)
10066 qWarning("QVkSwapChain: No renderpass descriptor set. See newCompatibleRenderPassDescriptor() and setRenderPassDescriptor().");
10067
10068 rtWrapper.setRenderPassDescriptor(m_renderPassDesc); // for the public getter in QRhiRenderTarget
10069 rtWrapper.d.rp = QRHI_RES(QVkRenderPassDescriptor, m_renderPassDesc);
10070 Q_ASSERT(rtWrapper.d.rp && rtWrapper.d.rp->rp);
10071
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);
10079 } else {
10080 rtWrapper.d.dsAttCount = 0;
10081 ds = nullptr;
10082 }
10083 rtWrapper.d.dsResolveAttCount = 0;
10084 if (samples > VK_SAMPLE_COUNT_1_BIT)
10085 rtWrapper.d.resolveAttCount = 1;
10086 else
10087 rtWrapper.d.resolveAttCount = 0;
10088
10089 if (shadingRateMapView)
10090 rtWrapper.d.shadingRateAttCount = 1;
10091 else
10092 rtWrapper.d.shadingRateAttCount = 0;
10093
10094 for (int i = 0; i < bufferCount; ++i) {
10095 QVkSwapChain::ImageResources &image(imageRes[i]);
10096 // color, ds, resolve, shading rate
10097 QVarLengthArray<VkImageView, 4> views;
10098 views.append(samples > VK_SAMPLE_COUNT_1_BIT ? image.msaaImageView : image.imageView);
10099 if (ds)
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);
10105
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());
10113 fbInfo.layers = 1;
10114
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);
10118 return false;
10119 }
10120 }
10121
10122 if (stereo) {
10123 rtWrapperRight.setRenderPassDescriptor(
10124 m_renderPassDesc); // for the public getter in QRhiRenderTarget
10125 rtWrapperRight.d.rp = QRHI_RES(QVkRenderPassDescriptor, m_renderPassDesc);
10126 Q_ASSERT(rtWrapperRight.d.rp && rtWrapperRight.d.rp->rp);
10127
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);
10135 } else {
10136 rtWrapperRight.d.dsAttCount = 0;
10137 ds = nullptr;
10138 }
10139 rtWrapperRight.d.dsResolveAttCount = 0;
10140 if (samples > VK_SAMPLE_COUNT_1_BIT)
10141 rtWrapperRight.d.resolveAttCount = 1;
10142 else
10143 rtWrapperRight.d.resolveAttCount = 0;
10144
10145 for (int i = 0; i < bufferCount; ++i) {
10146 QVkSwapChain::ImageResources &image(imageRes[i + bufferCount]);
10147 // color, ds, resolve, shading rate
10148 QVarLengthArray<VkImageView, 4> views;
10149 views.append(samples > VK_SAMPLE_COUNT_1_BIT ? image.msaaImageView : image.imageView);
10150 if (ds)
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);
10156
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());
10164 fbInfo.layers = 1;
10165
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);
10169 return false;
10170 }
10171 }
10172 }
10173
10174 frameCount = 0;
10175
10176 if (needsRegistration)
10177 rhiD->registerResource(this);
10178
10179 m_currentPixelSize = pixelSize;
10180 return true;
10181}
10182
10183QT_END_NAMESPACE
bool isEmpty() const
Definition qrhi.cpp:13820
const QRhiPassResourceMap< QRhiTexture *, Texture, 12 > & textures() const
Definition qrhi_p.h:978
void registerBuffer(QRhiBuffer *buf, int slot, BufferAccess *access, BufferStage *stage, const UsageState &state)
Definition qrhi.cpp:13837
void registerTexture(QRhiTexture *tex, TextureAccess *access, TextureStage *stage, const UsageState &state)
Definition qrhi.cpp:13877
const QRhiPassResourceMap< QRhiBuffer *, Buffer, 12 > & buffers() const
Definition qrhi_p.h:970
static QRhiResourceUpdateBatchPrivate * get(QRhiResourceUpdateBatch *b)
Definition qrhi_p.h:756
void recordTransitionPassResources(QVkCommandBuffer *cbD, const QRhiPassResourceTracker &tracker)
QVulkanFunctions * f
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)
bool importedDevice
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
void destroy() 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
QWindow * maybeWindow
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
QVkAllocator allocator
bool importedAllocator
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.
@ UnBounded
Definition qrhi_p.h:392
@ Bounded
Definition qrhi_p.h:393
#define QRHI_RES_RHI(t)
Definition qrhi_p.h:33
#define QRHI_RES(t, x)
Definition qrhi_p.h:32
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)
void * QVkAllocator
static const int QVK_MAX_ACTIVE_TIMESTAMP_PAIRS
static const int QVK_DESC_SETS_PER_POOL
void * QVkAlloc
static const int QVK_FRAMES_IN_FLIGHT
bool prepare(VkRenderPassCreateInfo *rpInfo, int multiViewCount, bool multiViewCap)
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:2016
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QVkBuffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
uint generation
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
int lastActiveFrameSlot
PassType recordingPass
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
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
int lastActiveFrameSlot
bool create() override
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.
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)
QVkTexture * texture
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(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool supportsReadback
QVkRenderBuffer * ds
QVkTextureRenderTarget(QRhiImplementation *rhi, const QRhiTextureRenderTargetDescription &desc, Flags flags)
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.
bool finishCreate()
VkImageView perLevelImageViewForLoadStore(int level)
int lastActiveFrameSlot
QVkAlloc stagingAllocations[QVK_FRAMES_IN_FLIGHT]
bool createFrom(NativeTexture src) override
Similar to create(), except that no new native textures are created.
QVkAlloc imageAlloc
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)
uint mipLevelCount