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
qrhid3d11.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 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 "qrhid3d11_p.h"
6#include "qshader.h"
7#include "qshader_p.h"
8#include "vs_test_p.h"
9#include <QWindow>
10#include <qmath.h>
11#include <QtCore/qcryptographichash.h>
12#include <QtCore/qendian.h>
13#include <QtCore/private/qsystemerror_p.h>
15
16#include <cstdio>
17
18QT_BEGIN_NAMESPACE
19
20using namespace Qt::StringLiterals;
21
22/*
23 Direct3D 11 backend. Provides a double-buffered flip model swapchain.
24 Textures and "static" buffers are USAGE_DEFAULT, leaving it to
25 UpdateSubResource to upload the data in any way it sees fit. "Dynamic"
26 buffers are USAGE_DYNAMIC and updating is done by mapping with WRITE_DISCARD.
27 (so here QRhiBuffer keeps a copy of the buffer contents and all of it is
28 memcpy'd every time, leaving the rest (juggling with the memory area Map
29 returns) to the driver).
30*/
31
32/*!
33 \class QRhiD3D11InitParams
34 \inmodule QtGuiPrivate
35 \inheaderfile rhi/qrhi.h
36 \since 6.6
37 \brief Direct3D 11 specific initialization parameters.
38
39 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
40 for details.
41
42 A D3D11-based QRhi needs no special parameters for initialization. If
43 desired, enableDebugLayer can be set to \c true to enable the Direct3D
44 debug layer. This can be useful during development, but should be avoided
45 in production builds.
46
47 \badcode
48 QRhiD3D11InitParams params;
49 params.enableDebugLayer = true;
50 rhi = QRhi::create(QRhi::D3D11, &params);
51 \endcode
52
53 \note QRhiSwapChain should only be used in combination with QWindow
54 instances that have their surface type set to QSurface::Direct3DSurface.
55
56 \section2 Working with existing Direct3D 11 devices
57
58 When interoperating with another graphics engine, it may be necessary to
59 get a QRhi instance that uses the same Direct3D device. This can be
60 achieved by passing a pointer to a QRhiD3D11NativeHandles to
61 QRhi::create(). When the device is set to a non-null value, the device
62 context must be specified as well. QRhi does not take ownership of any of
63 the external objects.
64
65 Sometimes, for example when using QRhi in combination with OpenXR, one will
66 want to specify which adapter to use, and optionally, which feature level
67 to request on the device, while leaving the device creation to QRhi. This
68 is achieved by leaving the device and context pointers set to null, while
69 specifying the adapter LUID and feature level.
70
71 \note QRhi works with immediate contexts only. Deferred contexts are not
72 used in any way.
73
74 \note Regardless of using an imported or a QRhi-created device context, the
75 \c ID3D11DeviceContext1 interface (Direct3D 11.1) must be supported.
76 Initialization will fail otherwise.
77 */
78
79/*!
80 \variable QRhiD3D11InitParams::enableDebugLayer
81
82 When set to true, a debug device is created, assuming the debug layer is
83 available. The default value is false.
84*/
85
86/*!
87 \class QRhiD3D11NativeHandles
88 \inmodule QtGuiPrivate
89 \inheaderfile rhi/qrhi.h
90 \since 6.6
91 \brief Holds the D3D device and device context used by the QRhi.
92
93 \note The class uses \c{void *} as the type since including the COM-based
94 \c{d3d11.h} headers is not acceptable here. The actual types are
95 \c{ID3D11Device *} and \c{ID3D11DeviceContext *}.
96
97 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
98 for details.
99 */
100
101/*!
102 \variable QRhiD3D11NativeHandles::dev
103
104 Points to a
105 \l{https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nn-d3d11-id3d11device}{ID3D11Device}
106 or left set to \nullptr if no existing device is to be imported.
107
108 \note When importing a device, both the device and the device context must be set to valid objects.
109*/
110
111/*!
112 \variable QRhiD3D11NativeHandles::context
113
114 Points to a \l{https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nn-d3d11-id3d11devicecontext}{ID3D11DeviceContext}
115 or left set to \nullptr if no existing device context is to be imported.
116
117 \note When importing a device, both the device and the device context must be set to valid objects.
118*/
119
120/*!
121 \variable QRhiD3D11NativeHandles::featureLevel
122
123 Specifies the feature level passed to
124 \l{https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-d3d11createdevice}{D3D11CreateDevice()}.
125 Relevant only when QRhi creates the device, ignored when importing a device
126 and device context. When not set, the default rules outlined in the D3D
127 documentation apply.
128*/
129
130/*!
131 \variable QRhiD3D11NativeHandles::adapterLuidLow
132
133 The low part of the local identifier (LUID) of the DXGI adapter to use.
134 Relevant only when QRhi creates the device, ignored when importing a device
135 and device context.
136*/
137
138/*!
139 \variable QRhiD3D11NativeHandles::adapterLuidHigh
140
141 The high part of the local identifier (LUID) of the DXGI adapter to use.
142 Relevant only when QRhi creates the device, ignored when importing a device
143 and device context.
144*/
145
146// help mingw with its ancient sdk headers
147#ifndef DXGI_ADAPTER_FLAG_SOFTWARE
148#define DXGI_ADAPTER_FLAG_SOFTWARE 2
149#endif
150
151#ifndef D3D11_1_UAV_SLOT_COUNT
152#define D3D11_1_UAV_SLOT_COUNT 64
153#endif
154
155#ifndef D3D11_VS_INPUT_REGISTER_COUNT
156#define D3D11_VS_INPUT_REGISTER_COUNT 32
157#endif
158
159QRhiD3D11::QRhiD3D11(QRhiD3D11InitParams *params, QRhiD3D11NativeHandles *importParams)
160 : ofr(this)
161{
162 debugLayer = params->enableDebugLayer;
163
164 if (importParams) {
165 if (importParams->dev && importParams->context) {
166 dev = reinterpret_cast<ID3D11Device *>(importParams->dev);
167 ID3D11DeviceContext *ctx = reinterpret_cast<ID3D11DeviceContext *>(importParams->context);
168 if (SUCCEEDED(ctx->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void **>(&context)))) {
169 // get rid of the ref added by QueryInterface
170 ctx->Release();
172 } else {
173 qWarning("ID3D11DeviceContext1 not supported by context, cannot import");
174 }
175 }
176 featureLevel = D3D_FEATURE_LEVEL(importParams->featureLevel);
177 adapterLuid.LowPart = importParams->adapterLuidLow;
178 adapterLuid.HighPart = importParams->adapterLuidHigh;
179 }
180}
181
182template <class Int>
183inline Int aligned(Int v, Int byteAlign)
184{
185 return (v + byteAlign - 1) & ~(byteAlign - 1);
186}
187
189{
190 IDXGIFactory1 *result = nullptr;
191 const HRESULT hr = CreateDXGIFactory2(0, __uuidof(IDXGIFactory2), reinterpret_cast<void **>(&result));
192 if (FAILED(hr)) {
193 qWarning("CreateDXGIFactory2() failed to create DXGI factory: %s",
194 qPrintable(QSystemError::windowsComString(hr)));
195 result = nullptr;
196 }
197 return result;
198}
199
200bool QRhiD3D11::create(QRhi::Flags flags)
201{
202 rhiFlags = flags;
203
204 uint devFlags = 0;
205 if (debugLayer)
206 devFlags |= D3D11_CREATE_DEVICE_DEBUG;
207
208 dxgiFactory = createDXGIFactory2();
209 if (!dxgiFactory)
210 return false;
211
212 // For a FLIP_* swapchain Present(0, 0) is not necessarily
213 // sufficient to get non-blocking behavior, try using ALLOW_TEARING
214 // when available.
215 supportsAllowTearing = false;
216 IDXGIFactory5 *factory5 = nullptr;
217 if (SUCCEEDED(dxgiFactory->QueryInterface(__uuidof(IDXGIFactory5), reinterpret_cast<void **>(&factory5)))) {
218 BOOL allowTearing = false;
219 if (SUCCEEDED(factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing))))
220 supportsAllowTearing = allowTearing;
221 factory5->Release();
222 }
223
224 if (qEnvironmentVariableIntValue("QT_D3D_FLIP_DISCARD"))
225 qWarning("The default swap effect is FLIP_DISCARD, QT_D3D_FLIP_DISCARD is now ignored");
226
227 // Support for flip model swapchains is required now (since we are
228 // targeting Windows 10+), but the option for using the old model is still
229 // there. (some features are not supported then, however)
230 useLegacySwapchainModel = qEnvironmentVariableIntValue("QT_D3D_NO_FLIP");
231
233 if (qEnvironmentVariableIsSet("QT_D3D_MAX_FRAME_LATENCY"))
234 maxFrameLatency = UINT(qMax(0, qEnvironmentVariableIntValue("QT_D3D_MAX_FRAME_LATENCY")));
235 } else {
236 maxFrameLatency = 0;
237 }
238
239 qCDebug(QRHI_LOG_INFO, "FLIP_* swapchain supported = true, ALLOW_TEARING supported = %s, use legacy (non-FLIP) model = %s, max frame latency = %u",
240 supportsAllowTearing ? "true" : "false",
241 useLegacySwapchainModel ? "true" : "false",
242 maxFrameLatency);
243 if (maxFrameLatency == 0)
244 qCDebug(QRHI_LOG_INFO, "Disabling FRAME_LATENCY_WAITABLE_OBJECT usage");
245
246 activeAdapter = nullptr;
247
249 IDXGIAdapter1 *adapter;
250 int requestedAdapterIndex = -1;
251 if (qEnvironmentVariableIsSet("QT_D3D_ADAPTER_INDEX"))
252 requestedAdapterIndex = qEnvironmentVariableIntValue("QT_D3D_ADAPTER_INDEX");
253
254 if (requestedRhiAdapter)
255 adapterLuid = static_cast<QD3D11Adapter *>(requestedRhiAdapter)->luid;
256
257 // importParams or requestedRhiAdapter may specify an adapter by the luid, use that in the absence of an env.var. override.
258 if (requestedAdapterIndex < 0 && (adapterLuid.LowPart || adapterLuid.HighPart)) {
259 for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
260 DXGI_ADAPTER_DESC1 desc;
261 adapter->GetDesc1(&desc);
262 adapter->Release();
263 if (desc.AdapterLuid.LowPart == adapterLuid.LowPart
264 && desc.AdapterLuid.HighPart == adapterLuid.HighPart)
265 {
266 requestedAdapterIndex = adapterIndex;
267 break;
268 }
269 }
270 }
271
272 if (requestedAdapterIndex < 0 && flags.testFlag(QRhi::PreferSoftwareRenderer)) {
273 for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
274 DXGI_ADAPTER_DESC1 desc;
275 adapter->GetDesc1(&desc);
276 adapter->Release();
277 if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) {
278 requestedAdapterIndex = adapterIndex;
279 break;
280 }
281 }
282 }
283
284 for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
285 DXGI_ADAPTER_DESC1 desc;
286 adapter->GetDesc1(&desc);
287 const QString name = QString::fromUtf16(reinterpret_cast<char16_t *>(desc.Description));
288 qCDebug(QRHI_LOG_INFO, "Adapter %d: '%s' (vendor 0x%X device 0x%X flags 0x%X)",
289 adapterIndex,
290 qPrintable(name),
291 desc.VendorId,
292 desc.DeviceId,
293 desc.Flags);
294 if (!activeAdapter && (requestedAdapterIndex < 0 || requestedAdapterIndex == adapterIndex)) {
295 activeAdapter = adapter;
296 adapterLuid = desc.AdapterLuid;
297 QRhiD3D::fillDriverInfo(&driverInfoStruct, desc);
298 qCDebug(QRHI_LOG_INFO, " using this adapter");
299 } else {
300 adapter->Release();
301 }
302 }
303 if (!activeAdapter) {
304 qWarning("No adapter");
305 return false;
306 }
307
308 // Normally we won't specify a requested feature level list,
309 // except when a level was specified in importParams.
310 QVarLengthArray<D3D_FEATURE_LEVEL, 4> requestedFeatureLevels;
311 bool requestFeatureLevels = false;
312 if (featureLevel) {
313 requestFeatureLevels = true;
314 requestedFeatureLevels.append(featureLevel);
315 }
316
317 ID3D11DeviceContext *ctx = nullptr;
318 HRESULT hr = D3D11CreateDevice(activeAdapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, devFlags,
319 requestFeatureLevels ? requestedFeatureLevels.constData() : nullptr,
320 requestFeatureLevels ? requestedFeatureLevels.count() : 0,
321 D3D11_SDK_VERSION,
322 &dev, &featureLevel, &ctx);
323 // We cannot assume that D3D11_CREATE_DEVICE_DEBUG is always available. Retry without it, if needed.
324 if (hr == DXGI_ERROR_SDK_COMPONENT_MISSING && debugLayer) {
325 qCDebug(QRHI_LOG_INFO, "Debug layer was requested but is not available. "
326 "Attempting to create D3D11 device without it.");
327 devFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
328 hr = D3D11CreateDevice(activeAdapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, devFlags,
329 requestFeatureLevels ? requestedFeatureLevels.constData() : nullptr,
330 requestFeatureLevels ? requestedFeatureLevels.count() : 0,
331 D3D11_SDK_VERSION,
332 &dev, &featureLevel, &ctx);
333 }
334 if (FAILED(hr)) {
335 qWarning("Failed to create D3D11 device and context: %s",
336 qPrintable(QSystemError::windowsComString(hr)));
337 return false;
338 }
339
340 const bool supports11_1 = SUCCEEDED(ctx->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void **>(&context)));
341 ctx->Release();
342 if (!supports11_1) {
343 qWarning("ID3D11DeviceContext1 not supported");
344 return false;
345 }
346
347 // Test if creating a Shader Model 5.0 vertex shader works; we want to
348 // fail already in create() if that's not the case.
349 ID3D11VertexShader *testShader = nullptr;
350 if (SUCCEEDED(dev->CreateVertexShader(g_testVertexShader, sizeof(g_testVertexShader), nullptr, &testShader))) {
351 testShader->Release();
352 } else {
353 static const char *msg = "D3D11 smoke test: Failed to create vertex shader";
354 if (flags.testFlag(QRhi::SuppressSmokeTestWarnings))
355 qCDebug(QRHI_LOG_INFO, "%s", msg);
356 else
357 qWarning("%s", msg);
358 return false;
359 }
360
361 D3D11_FEATURE_DATA_D3D11_OPTIONS features = {};
362 if (SUCCEEDED(dev->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &features, sizeof(features)))) {
363 // The D3D _runtime_ may be 11.1, but the underlying _driver_ may
364 // still not support this D3D_FEATURE_LEVEL_11_1 feature. (e.g.
365 // because it only does 11_0)
366 if (!features.ConstantBufferOffsetting) {
367 static const char *msg = "D3D11 smoke test: Constant buffer offsetting is not supported by the driver";
368 if (flags.testFlag(QRhi::SuppressSmokeTestWarnings))
369 qCDebug(QRHI_LOG_INFO, "%s", msg);
370 else
371 qWarning("%s", msg);
372 return false;
373 }
374 } else {
375 static const char *msg = "D3D11 smoke test: Failed to query D3D11_FEATURE_D3D11_OPTIONS";
376 if (flags.testFlag(QRhi::SuppressSmokeTestWarnings))
377 qCDebug(QRHI_LOG_INFO, "%s", msg);
378 else
379 qWarning("%s", msg);
380 return false;
381 }
382 } else {
383 Q_ASSERT(dev && context);
384 featureLevel = dev->GetFeatureLevel();
385 IDXGIDevice *dxgiDev = nullptr;
386 if (SUCCEEDED(dev->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void **>(&dxgiDev)))) {
387 IDXGIAdapter *adapter = nullptr;
388 if (SUCCEEDED(dxgiDev->GetAdapter(&adapter))) {
389 IDXGIAdapter1 *adapter1 = nullptr;
390 if (SUCCEEDED(adapter->QueryInterface(__uuidof(IDXGIAdapter1), reinterpret_cast<void **>(&adapter1)))) {
391 DXGI_ADAPTER_DESC1 desc;
392 adapter1->GetDesc1(&desc);
393 adapterLuid = desc.AdapterLuid;
394 QRhiD3D::fillDriverInfo(&driverInfoStruct, desc);
395 activeAdapter = adapter1;
396 }
397 adapter->Release();
398 }
399 dxgiDev->Release();
400 }
401 if (!activeAdapter) {
402 qWarning("Failed to query adapter from imported device");
403 return false;
404 }
405 qCDebug(QRHI_LOG_INFO, "Using imported device %p", dev);
406 }
407
408 QDxgiVSyncService::instance()->refAdapter(adapterLuid);
409
410 if (FAILED(context->QueryInterface(__uuidof(ID3DUserDefinedAnnotation), reinterpret_cast<void **>(&annotations))))
411 annotations = nullptr;
412
413 deviceLost = false;
414
415 nativeHandlesStruct.dev = dev;
416 nativeHandlesStruct.context = context;
417 nativeHandlesStruct.featureLevel = featureLevel;
418 nativeHandlesStruct.adapterLuidLow = adapterLuid.LowPart;
419 nativeHandlesStruct.adapterLuidHigh = adapterLuid.HighPart;
420
421 return true;
422}
423
425{
426 for (const Shader &s : std::as_const(m_shaderCache))
427 s.s->Release();
428
429 m_shaderCache.clear();
430}
431
433{
435
437
438 if (pushConstantBuffer) {
439 pushConstantBuffer->Release();
440 pushConstantBuffer = nullptr;
441 }
442
443 if (ofr.tsDisjointQuery) {
444 ofr.tsDisjointQuery->Release();
445 ofr.tsDisjointQuery = nullptr;
446 }
447 for (int i = 0; i < 2; ++i) {
448 if (ofr.tsQueries[i]) {
449 ofr.tsQueries[i]->Release();
450 ofr.tsQueries[i] = nullptr;
451 }
452 }
453
454 if (annotations) {
455 annotations->Release();
456 annotations = nullptr;
457 }
458
460 if (context) {
461 context->Release();
462 context = nullptr;
463 }
464 if (dev) {
465 dev->Release();
466 dev = nullptr;
467 }
468 }
469
470 if (dcompDevice) {
471 dcompDevice->Release();
472 dcompDevice = nullptr;
473 }
474
475 if (activeAdapter) {
476 activeAdapter->Release();
477 activeAdapter = nullptr;
478 }
479
480 if (dxgiFactory) {
481 dxgiFactory->Release();
482 dxgiFactory = nullptr;
483 }
484
485 QDxgiVSyncService::instance()->derefAdapter(adapterLuid);
486
488 adapterLuid = {};
489}
490
491void QRhiD3D11::reportLiveObjects(ID3D11Device *device)
492{
493 // this works only when params.enableDebugLayer was true
494 ID3D11Debug *debug;
495 if (SUCCEEDED(device->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void **>(&debug)))) {
496 debug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
497 debug->Release();
498 }
499}
500
501QRhi::AdapterList QRhiD3D11::enumerateAdaptersBeforeCreate(QRhiNativeHandles *nativeHandles) const
502{
503 LUID requestedLuid = {};
504 if (nativeHandles) {
505 QRhiD3D11NativeHandles *h = static_cast<QRhiD3D11NativeHandles *>(nativeHandles);
506 const LUID adapterLuid = { h->adapterLuidLow, h->adapterLuidHigh };
507 if (adapterLuid.LowPart || adapterLuid.HighPart)
508 requestedLuid = adapterLuid;
509 }
510
511 IDXGIFactory1 *dxgi = createDXGIFactory2();
512 if (!dxgi)
513 return {};
514
515 QRhi::AdapterList list;
516 IDXGIAdapter1 *adapter;
517 for (int adapterIndex = 0; dxgi->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
518 DXGI_ADAPTER_DESC1 desc;
519 adapter->GetDesc1(&desc);
520 adapter->Release();
521 if (requestedLuid.LowPart || requestedLuid.HighPart) {
522 if (desc.AdapterLuid.LowPart != requestedLuid.LowPart
523 || desc.AdapterLuid.HighPart != requestedLuid.HighPart)
524 {
525 continue;
526 }
527 }
528 QD3D11Adapter *a = new QD3D11Adapter;
529 a->luid = desc.AdapterLuid;
530 QRhiD3D::fillDriverInfo(&a->adapterInfo, desc);
531 list.append(a);
532 }
533
534 dxgi->Release();
535 return list;
536}
537
539{
540 return adapterInfo;
541}
542
544{
545 return { 1, 2, 4, 8 };
546}
547
549{
550 Q_UNUSED(sampleCount);
551 return { QSize(1, 1) };
552}
553
555{
556 DXGI_SAMPLE_DESC desc;
557 desc.Count = 1;
558 desc.Quality = 0;
559
560 const int s = effectiveSampleCount(sampleCount);
561
562 desc.Count = UINT(s);
563 if (s > 1)
564 desc.Quality = UINT(D3D11_STANDARD_MULTISAMPLE_PATTERN);
565 else
566 desc.Quality = 0;
567
568 return desc;
569}
570
571QRhiSwapChain *QRhiD3D11::createSwapChain()
572{
573 return new QD3D11SwapChain(this);
574}
575
576QRhiBuffer *QRhiD3D11::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
577{
578 return new QD3D11Buffer(this, type, usage, size);
579}
580
582{
583 return 256;
584}
585
587{
588 return false;
589}
590
592{
593 return true;
594}
595
597{
598 return true;
599}
600
602{
603 // Like with Vulkan, but Y is already good.
604
605 // NB the ctor takes row-major
606 static constexpr QMatrix4x4 m(1.0f, 0.0f, 0.0f, 0.0f,
607 0.0f, 1.0f, 0.0f, 0.0f,
608 0.0f, 0.0f, 0.5f, 0.5f,
609 0.0f, 0.0f, 0.0f, 1.0f);
610 return m;
611}
612
613bool QRhiD3D11::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
614{
615 Q_UNUSED(flags);
616
617 if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ASTC_12x12)
618 return false;
619
620 return true;
621}
622
623bool QRhiD3D11::isFeatureSupported(QRhi::Feature feature) const
624{
625 switch (feature) {
626 case QRhi::MultisampleTexture:
627 return true;
628 case QRhi::MultisampleRenderBuffer:
629 return true;
630 case QRhi::DebugMarkers:
631 return annotations != nullptr;
632 case QRhi::Timestamps:
633 return true;
634 case QRhi::Instancing:
635 return true;
636 case QRhi::CustomInstanceStepRate:
637 return true;
638 case QRhi::PrimitiveRestart:
639 return true;
640 case QRhi::NonDynamicUniformBuffers:
641 return false; // because UpdateSubresource cannot deal with this
642 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
643 return true;
644 case QRhi::NPOTTextureRepeat:
645 return true;
646 case QRhi::RedOrAlpha8IsRed:
647 return true;
648 case QRhi::ElementIndexUint:
649 return true;
650 case QRhi::Compute:
651 // Not a real restriction since all shaders need to be shader model 5.0
652 // anyway, but for example typed UAVs are only guaranteed with 11_0.
653 return featureLevel >= D3D_FEATURE_LEVEL_11_0;
654 case QRhi::FragmentStoresAndAtomics:
655 return featureLevel >= D3D_FEATURE_LEVEL_11_0;
656 case QRhi::WideLines:
657 return false;
658 case QRhi::VertexShaderPointSize:
659 return false;
660 case QRhi::BaseVertex:
661 return true;
662 case QRhi::BaseInstance:
663 return true;
664 case QRhi::TriangleFanTopology:
665 return false;
666 case QRhi::ReadBackNonUniformBuffer:
667 return true;
668 case QRhi::ReadBackNonBaseMipLevel:
669 return true;
670 case QRhi::TexelFetch:
671 return true;
672 case QRhi::RenderToNonBaseMipLevel:
673 return true;
674 case QRhi::IntAttributes:
675 return true;
676 case QRhi::ScreenSpaceDerivatives:
677 return true;
678 case QRhi::ReadBackAnyTextureFormat:
679 return true;
680 case QRhi::PipelineCacheDataLoadSave:
681 return true;
682 case QRhi::ImageDataStride:
683 return true;
684 case QRhi::RenderBufferImport:
685 return false;
686 case QRhi::ThreeDimensionalTextures:
687 return true;
688 case QRhi::RenderTo3DTextureSlice:
689 return true;
690 case QRhi::TextureArrays:
691 return true;
692 case QRhi::Tessellation:
693 return true;
694 case QRhi::GeometryShader:
695 return true;
696 case QRhi::TextureArrayRange:
697 return true;
698 case QRhi::NonFillPolygonMode:
699 return true;
700 case QRhi::OneDimensionalTextures:
701 return true;
702 case QRhi::OneDimensionalTextureMipmaps:
703 return true;
704 case QRhi::HalfAttributes:
705 return true;
706 case QRhi::RenderToOneDimensionalTexture:
707 return true;
708 case QRhi::ThreeDimensionalTextureMipmaps:
709 return true;
710 case QRhi::MultiView:
711 return false;
712 case QRhi::TextureViewFormat:
713 return false; // because we use fully typed formats for textures and relaxed casting is a D3D12 thing
714 case QRhi::ResolveDepthStencil:
715 return false;
716 case QRhi::VariableRateShading:
717 return false;
718 case QRhi::VariableRateShadingMap:
719 case QRhi::VariableRateShadingMapWithTexture:
720 return false;
721 case QRhi::DualSourceBlend:
722 return featureLevel >= D3D_FEATURE_LEVEL_10_0;
723 case QRhi::PerRenderTargetBlending:
724 case QRhi::SampleVariables:
725 return true;
726 case QRhi::InstanceIndexIncludesBaseInstance:
727 return false;
728 case QRhi::DepthClamp:
729 return true;
730 case QRhi::DrawIndirect:
731 case QRhi::BaseInstanceIndirect:
732 return featureLevel >= D3D_FEATURE_LEVEL_11_0;
733 case QRhi::DrawIndirectMulti:
734 case QRhi::ShaderDrawParameters:
735 return false;
736 case QRhi::PushConstants:
737 return true;
738 case QRhi::DrawIndirectCount:
739 return false;
740 case QRhi::DispatchIndirect:
741 return featureLevel >= D3D_FEATURE_LEVEL_11_0;
742 case QRhi::BufferToBufferCopy:
743 return true;
744 case QRhi::StaticBuffersOnGpuTimeline:
745 return true;
746 default:
747 Q_UNREACHABLE();
748 return false;
749 }
750}
751
752int QRhiD3D11::resourceLimit(QRhi::ResourceLimit limit) const
753{
754 switch (limit) {
755 case QRhi::TextureSizeMin:
756 return 1;
757 case QRhi::TextureSizeMax:
758 return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
759 case QRhi::MaxColorAttachments:
760 return 8;
761 case QRhi::FramesInFlight:
762 // From our perspective. What D3D does internally is another question
763 // (there could be pipelining, helped f.ex. by our MAP_DISCARD based
764 // uniform buffer update strategy), but that's out of our hands and
765 // does not concern us here.
766 return 1;
767 case QRhi::MaxAsyncReadbackFrames:
768 return 1;
769 case QRhi::MaxThreadGroupsPerDimension:
770 return D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
771 case QRhi::MaxThreadsPerThreadGroup:
772 return D3D11_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP;
773 case QRhi::MaxThreadGroupX:
774 return D3D11_CS_THREAD_GROUP_MAX_X;
775 case QRhi::MaxThreadGroupY:
776 return D3D11_CS_THREAD_GROUP_MAX_Y;
777 case QRhi::MaxThreadGroupZ:
778 return D3D11_CS_THREAD_GROUP_MAX_Z;
779 case QRhi::TextureArraySizeMax:
780 return D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION;
781 case QRhi::MaxUniformBufferRange:
782 return 65536;
783 case QRhi::MaxVertexInputs:
785 case QRhi::MaxVertexOutputs:
786 return D3D11_VS_OUTPUT_REGISTER_COUNT;
787 case QRhi::MaxVertexStorageBuffers:
788 return 0;
789 case QRhi::MaxPushConstantsSize:
790 // Emulated with a small dynamic constant buffer; match what D3D12 reports.
791 return int(MAX_PUSH_CONSTANTS_SIZE);
792 case QRhi::MaxFragmentStorageBuffers:
793 return featureLevel >= D3D_FEATURE_LEVEL_11_1
794 ? D3D11_1_UAV_SLOT_COUNT : D3D11_PS_CS_UAV_REGISTER_COUNT;
795 case QRhi::MaxStorageBufferBindings:
796 case QRhi::MaxStorageImageBindings:
797 return INT_MAX; // binding numbers are mapped to native slots
798 case QRhi::ShadingRateImageTileSize:
799 return 0;
800 default:
801 Q_UNREACHABLE();
802 return 0;
803 }
804}
805
807{
808 return &nativeHandlesStruct;
809}
810
812{
813 return driverInfoStruct;
814}
815
817{
818 QRhiStats result;
819 result.totalPipelineCreationTime = totalPipelineCreationTime();
820 return result;
821}
822
824{
825 // not applicable
826 return false;
827}
828
829void QRhiD3D11::setQueueSubmitParams(QRhiNativeHandles *)
830{
831 // not applicable
832}
833
835{
837 m_bytecodeCache.clear();
838}
839
841{
842 return deviceLost;
843}
844
846{
849 // no need for driver specifics
852};
853
855{
856 QByteArray data;
857 if (m_bytecodeCache.data.isEmpty())
858 return data;
859
861 memset(&header, 0, sizeof(header));
862 header.rhiId = pipelineCacheRhiId();
863 header.arch = quint32(sizeof(void*));
864 header.count = m_bytecodeCache.data.count();
865
866 const size_t dataOffset = sizeof(header);
867 size_t dataSize = 0;
868 for (auto it = m_bytecodeCache.data.cbegin(), end = m_bytecodeCache.data.cend(); it != end; ++it) {
869 BytecodeCacheKey key = it.key();
870 QByteArray bytecode = it.value();
871 dataSize +=
872 sizeof(quint32) + key.sourceHash.size()
873 + sizeof(quint32) + key.target.size()
874 + sizeof(quint32) + key.entryPoint.size()
875 + sizeof(quint32) // compileFlags
876 + sizeof(quint32) + bytecode.size();
877 }
878
879 QByteArray buf(dataOffset + dataSize, Qt::Uninitialized);
880 char *p = buf.data() + dataOffset;
881 for (auto it = m_bytecodeCache.data.cbegin(), end = m_bytecodeCache.data.cend(); it != end; ++it) {
882 BytecodeCacheKey key = it.key();
883 QByteArray bytecode = it.value();
884
885 quint32 i = key.sourceHash.size();
886 memcpy(p, &i, 4);
887 p += 4;
888 memcpy(p, key.sourceHash.constData(), key.sourceHash.size());
889 p += key.sourceHash.size();
890
891 i = key.target.size();
892 memcpy(p, &i, 4);
893 p += 4;
894 memcpy(p, key.target.constData(), key.target.size());
895 p += key.target.size();
896
897 i = key.entryPoint.size();
898 memcpy(p, &i, 4);
899 p += 4;
900 memcpy(p, key.entryPoint.constData(), key.entryPoint.size());
901 p += key.entryPoint.size();
902
903 quint32 f = key.compileFlags;
904 memcpy(p, &f, 4);
905 p += 4;
906
907 i = bytecode.size();
908 memcpy(p, &i, 4);
909 p += 4;
910 memcpy(p, bytecode.constData(), bytecode.size());
911 p += bytecode.size();
912 }
913 Q_ASSERT(p == buf.data() + dataOffset + dataSize);
914
915 header.dataSize = quint32(dataSize);
916 memcpy(buf.data(), &header, sizeof(header));
917
918 return buf;
919}
920
921void QRhiD3D11::setPipelineCacheData(const QByteArray &data)
922{
923 if (data.isEmpty())
924 return;
925
926 const size_t headerSize = sizeof(QD3D11PipelineCacheDataHeader);
927 if (data.size() < qsizetype(headerSize)) {
928 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob size (header incomplete)");
929 return;
930 }
931 const size_t dataOffset = headerSize;
933 memcpy(&header, data.constData(), headerSize);
934
935 const quint32 rhiId = pipelineCacheRhiId();
936 if (header.rhiId != rhiId) {
937 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: The data is for a different QRhi version or backend (%u, %u)",
938 rhiId, header.rhiId);
939 return;
940 }
941 const quint32 arch = quint32(sizeof(void*));
942 if (header.arch != arch) {
943 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Architecture does not match (%u, %u)",
944 arch, header.arch);
945 return;
946 }
947 if (header.count == 0)
948 return;
949
950 if (quint64(data.size()) < quint64(dataOffset) + header.dataSize) {
951 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob size (data incomplete)");
952 return;
953 }
954
955 m_bytecodeCache.clear();
956
957 QRhiPipelineCacheDataReader reader(data.constData() + dataOffset, header.dataSize);
958 for (quint32 i = 0; i < header.count; ++i) {
959 BytecodeCacheKey cacheKey;
960 QByteArray bytecode;
961 quint32 flags = 0;
962 if (!reader.readByteArray(&cacheKey.sourceHash)
963 || !reader.readByteArray(&cacheKey.target)
964 || !reader.readByteArray(&cacheKey.entryPoint)
965 || !reader.readUInt32(&flags)
966 || !reader.readByteArray(&bytecode))
967 {
968 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob (truncated or corrupt bytecode data)");
969 m_bytecodeCache.clear();
970 return;
971 }
972 cacheKey.compileFlags = flags;
973
974 m_bytecodeCache.insertWithCapacityLimit(cacheKey, bytecode);
975 }
976
977 qCDebug(QRHI_LOG_INFO, "Seeded bytecode cache with %d shaders", int(m_bytecodeCache.data.count()));
978}
979
980QRhiRenderBuffer *QRhiD3D11::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
981 int sampleCount, QRhiRenderBuffer::Flags flags,
982 QRhiTexture::Format backingFormatHint)
983{
984 return new QD3D11RenderBuffer(this, type, pixelSize, sampleCount, flags, backingFormatHint);
985}
986
987QRhiTexture *QRhiD3D11::createTexture(QRhiTexture::Format format,
988 const QSize &pixelSize, int depth, int arraySize,
989 int sampleCount, QRhiTexture::Flags flags)
990{
991 return new QD3D11Texture(this, format, pixelSize, depth, arraySize, sampleCount, flags);
992}
993
994QRhiSampler *QRhiD3D11::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
995 QRhiSampler::Filter mipmapMode,
996 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
997{
998 return new QD3D11Sampler(this, magFilter, minFilter, mipmapMode, u, v, w);
999}
1000
1001QRhiTextureRenderTarget *QRhiD3D11::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
1002 QRhiTextureRenderTarget::Flags flags)
1003{
1004 return new QD3D11TextureRenderTarget(this, desc, flags);
1005}
1006
1007QRhiShadingRateMap *QRhiD3D11::createShadingRateMap()
1008{
1009 return nullptr;
1010}
1011
1013{
1014 return new QD3D11GraphicsPipeline(this);
1015}
1016
1018{
1019 return new QD3D11ComputePipeline(this);
1020}
1021
1023{
1024 return new QD3D11ShaderResourceBindings(this);
1025}
1026
1027void QRhiD3D11::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps)
1028{
1029 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1032 const bool pipelineChanged = cbD->currentGraphicsPipeline != ps || cbD->currentPipelineGeneration != psD->generation;
1033
1034 if (pipelineChanged) {
1035 cbD->currentGraphicsPipeline = ps;
1036 cbD->currentComputePipeline = nullptr;
1038
1039 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1041 cmd.args.bindGraphicsPipeline.topology = psD->d3dTopology;
1042 cmd.args.bindGraphicsPipeline.inputLayout = psD->inputLayout; // may be null, that's ok
1043 cmd.args.bindGraphicsPipeline.dsState = psD->dsState;
1044 cmd.args.bindGraphicsPipeline.stencilRef = psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)
1045 ? cbD->currentStencilRef : 0;
1046 cmd.args.bindGraphicsPipeline.blendState = psD->blendState;
1047 cmd.args.bindGraphicsPipeline.rastState = psD->rastState;
1048 cmd.args.bindGraphicsPipeline.vs = psD->vs.shader;
1049 cmd.args.bindGraphicsPipeline.hs = psD->hs.shader;
1050 cmd.args.bindGraphicsPipeline.ds = psD->ds.shader;
1051 cmd.args.bindGraphicsPipeline.gs = psD->gs.shader;
1052 cmd.args.bindGraphicsPipeline.fs = psD->fs.shader;
1053 }
1054}
1055
1056static const int RBM_SUPPORTED_STAGES = 6;
1057static const int RBM_VERTEX = 0;
1058static const int RBM_HULL = 1;
1059static const int RBM_DOMAIN = 2;
1060static const int RBM_GEOMETRY = 3;
1061static const int RBM_FRAGMENT = 4;
1062static const int RBM_COMPUTE = 5;
1063
1064static inline int rbmStageIndex(QRhiShaderStage::Type type)
1065{
1066 switch (type) {
1067 case QRhiShaderStage::Vertex:
1068 return RBM_VERTEX;
1069 case QRhiShaderStage::TessellationControl:
1070 return RBM_HULL;
1071 case QRhiShaderStage::TessellationEvaluation:
1072 return RBM_DOMAIN;
1073 case QRhiShaderStage::Geometry:
1074 return RBM_GEOMETRY;
1075 case QRhiShaderStage::Fragment:
1076 return RBM_FRAGMENT;
1077 case QRhiShaderStage::Compute:
1078 return RBM_COMPUTE;
1079 }
1080 return -1;
1081}
1082
1083// A push constant block becomes a constant buffer, bound to the register qsb
1084// reserved for it (e.g. b0; the uniform blocks of a stage that has a push
1085// constant block then start at b1)
1086static void getPushConstantInfo(const QShader &shader, const QShaderKey &key, int *reg, quint32 *size)
1087{
1088 const QList<QShaderDescription::PushConstantBlock> blocks = shader.description().pushConstantBlocks();
1089 if (blocks.isEmpty())
1090 return;
1091 *reg = shader.nativeShaderInfo(key).extraBufferBindings.value(QShaderPrivate::HlslPushConstantBufferBinding, -1);
1092 *size = quint32((blocks.first().size + 3) & ~3); // multiple of 4 always
1093}
1094
1095void QRhiD3D11::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb,
1096 int dynamicOffsetCount,
1097 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
1098{
1099 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1101 QD3D11GraphicsPipeline *gfxPsD = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentGraphicsPipeline);
1102 QD3D11ComputePipeline *compPsD = QRHI_RES(QD3D11ComputePipeline, cbD->currentComputePipeline);
1103
1104 if (!srb) {
1105 if (gfxPsD)
1106 srb = gfxPsD->m_shaderResourceBindings;
1107 else
1108 srb = compPsD->m_shaderResourceBindings;
1109 }
1110
1112
1113 bool pipelineChanged = false;
1114 if (gfxPsD) {
1115 pipelineChanged = srbD->lastUsedGraphicsPipeline != gfxPsD;
1116 srbD->lastUsedGraphicsPipeline = gfxPsD;
1117 } else {
1118 pipelineChanged = srbD->lastUsedComputePipeline != compPsD;
1119 srbD->lastUsedComputePipeline = compPsD;
1120 }
1121
1122 bool srbUpdate = false;
1123 for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
1124 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings.at(i));
1125 QD3D11ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
1126 switch (b->type()) {
1127 case QRhiShaderResourceBinding::UniformBuffer:
1128 {
1129 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, b->ubuf().buf);
1130 // NonDynamicUniformBuffers is not supported by this backend
1131 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic && bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
1132 sanityCheckResourceOwnership(bufD);
1133
1135
1136 if (bufD->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
1137 srbUpdate = true;
1138 bd.ubuf.id = bufD->m_id;
1139 bd.ubuf.generation = bufD->generation;
1140 }
1141 }
1142 break;
1143 case QRhiShaderResourceBinding::SampledTexture:
1144 case QRhiShaderResourceBinding::Texture:
1145 case QRhiShaderResourceBinding::Sampler:
1146 {
1147 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
1148 if (bd.stex.d.size() != data->count()) {
1149 bd.stex.d.resize(data->count());
1150 srbUpdate = true;
1151 }
1152 for (int elem = 0; elem < data->count(); ++elem) {
1153 QD3D11Texture *texD = QRHI_RES(QD3D11Texture, data->texSamplers[elem].tex);
1154 QD3D11Sampler *samplerD = QRHI_RES(QD3D11Sampler, data->texSamplers[elem].sampler);
1155 // We use the same code path for both combined and separate
1156 // images and samplers, so tex or sampler (but not both) can be
1157 // null here.
1158 Q_ASSERT(texD || samplerD);
1159 sanityCheckResourceOwnership(texD);
1160 sanityCheckResourceOwnership(samplerD);
1161 const quint64 texId = texD ? texD->m_id : 0;
1162 const uint texGen = texD ? texD->generation : 0;
1163 const quint64 samplerId = samplerD ? samplerD->m_id : 0;
1164 const uint samplerGen = samplerD ? samplerD->generation : 0;
1165 if (texGen != bd.stex.d[elem].texGeneration
1166 || texId != bd.stex.d[elem].texId
1167 || samplerGen != bd.stex.d[elem].samplerGeneration
1168 || samplerId != bd.stex.d[elem].samplerId)
1169 {
1170 srbUpdate = true;
1171 bd.stex.d[elem].texId = texId;
1172 bd.stex.d[elem].texGeneration = texGen;
1173 bd.stex.d[elem].samplerId = samplerId;
1174 bd.stex.d[elem].samplerGeneration = samplerGen;
1175 }
1176 }
1177 }
1178 break;
1179 case QRhiShaderResourceBinding::ImageLoad:
1180 case QRhiShaderResourceBinding::ImageStore:
1181 case QRhiShaderResourceBinding::ImageLoadStore:
1182 {
1183 QD3D11Texture *texD = QRHI_RES(QD3D11Texture, b->simage().tex);
1184 sanityCheckResourceOwnership(texD);
1185 if (texD->generation != bd.simage.generation || texD->m_id != bd.simage.id) {
1186 srbUpdate = true;
1187 bd.simage.id = texD->m_id;
1188 bd.simage.generation = texD->generation;
1189 }
1190 }
1191 break;
1192 case QRhiShaderResourceBinding::BufferLoad:
1193 case QRhiShaderResourceBinding::BufferStore:
1194 case QRhiShaderResourceBinding::BufferLoadStore:
1195 {
1196 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, b->sbuf().buf);
1197 sanityCheckResourceOwnership(bufD);
1198 if (bufD->generation != bd.sbuf.generation || bufD->m_id != bd.sbuf.id) {
1199 srbUpdate = true;
1200 bd.sbuf.id = bufD->m_id;
1201 bd.sbuf.generation = bufD->generation;
1202 }
1203 }
1204 break;
1205 default:
1206 Q_UNREACHABLE();
1207 break;
1208 }
1209 }
1210
1211 if (srbUpdate || pipelineChanged) {
1212 const QShader::NativeResourceBindingMap *resBindMaps[RBM_SUPPORTED_STAGES];
1213 memset(resBindMaps, 0, sizeof(resBindMaps));
1214 uint pushConstantStages = 0;
1215 if (gfxPsD) {
1216 resBindMaps[RBM_VERTEX] = &gfxPsD->vs.nativeResourceBindingMap;
1217 resBindMaps[RBM_HULL] = &gfxPsD->hs.nativeResourceBindingMap;
1218 resBindMaps[RBM_DOMAIN] = &gfxPsD->ds.nativeResourceBindingMap;
1219 resBindMaps[RBM_GEOMETRY] = &gfxPsD->gs.nativeResourceBindingMap;
1220 resBindMaps[RBM_FRAGMENT] = &gfxPsD->fs.nativeResourceBindingMap;
1221 pushConstantStages = gfxPsD->pushConstants.stages;
1222 } else {
1223 resBindMaps[RBM_COMPUTE] = &compPsD->cs.nativeResourceBindingMap;
1224 if (compPsD->pushConstants.reg >= 0 && compPsD->pushConstants.size)
1225 pushConstantStages = 1u << uint(RBM_COMPUTE);
1226 }
1227 updateShaderResourceBindings(srbD, resBindMaps, pushConstantStages);
1228 }
1229
1230 const bool srbChanged = gfxPsD ? (cbD->currentGraphicsSrb != srb) : (cbD->currentComputeSrb != srb);
1231 const bool srbRebuilt = cbD->currentSrbGeneration != srbD->generation;
1232
1233 if (pipelineChanged || srbChanged || srbRebuilt || srbUpdate || srbD->hasDynamicOffset) {
1234 if (gfxPsD) {
1235 cbD->currentGraphicsSrb = srb;
1236 cbD->currentComputeSrb = nullptr;
1237 } else {
1238 cbD->currentGraphicsSrb = nullptr;
1239 cbD->currentComputeSrb = srb;
1240 }
1242
1243 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1245 cmd.args.bindShaderResources.resourceBatchesIndex = cbD->retainResourceBatches(srbD->resourceBatches);
1246 // dynamic offsets have to be applied at the time of executing the bind
1247 // operations, not here. A pipeline change means the batches may have
1248 // been rebuilt above for a different native resource binding map, so
1249 // that must lead to a full rebind, not just updating the offsets.
1250 cmd.args.bindShaderResources.offsetOnlyChange = !pipelineChanged && !srbChanged
1251 && !srbRebuilt && !srbUpdate && srbD->hasDynamicOffset;
1252 cmd.args.bindShaderResources.dynamicOffsetCount = 0;
1253 if (srbD->hasDynamicOffset) {
1254 if (dynamicOffsetCount < QD3D11CommandBuffer::MAX_DYNAMIC_OFFSET_COUNT) {
1255 cmd.args.bindShaderResources.dynamicOffsetCount = dynamicOffsetCount;
1256 uint *p = cmd.args.bindShaderResources.dynamicOffsetPairs;
1257 for (int i = 0; i < dynamicOffsetCount; ++i) {
1258 const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]);
1259 const uint binding = uint(dynOfs.first);
1260 Q_ASSERT(aligned(dynOfs.second, 256u) == dynOfs.second);
1261 const quint32 offsetInConstants = dynOfs.second / 16;
1262 *p++ = binding;
1263 *p++ = offsetInConstants;
1264 }
1265 } else {
1266 qWarning("Too many dynamic offsets (%d, max is %d)",
1268 }
1269 }
1270 }
1271}
1272
1273void QRhiD3D11::setVertexInput(QRhiCommandBuffer *cb,
1274 int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings,
1275 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
1276{
1277 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1279
1281 if (bindingCount > maxBindings)
1282 qWarning("Too many vertex buffer bindings (%d, max is %d)", bindingCount, maxBindings);
1283
1284 const auto *psD = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentGraphicsPipeline);
1285 const QRhiVertexInputLayout *inputLayout = psD ? &psD->m_vertexInputLayout : nullptr;
1286 const int inputBindingCount = inputLayout
1287 ? inputLayout->cendBindings() - inputLayout->cbeginBindings() : 0;
1288 const int vertexBindingCount = qMin(qMin(bindingCount, maxBindings),
1289 inputBindingCount - startBinding);
1290
1291 // The stride is part of IASetVertexBuffers state and can change with the
1292 // pipeline even when the buffer and offset are reused.
1293 bool needsBindVBuf = false;
1294 for (int i = 0; i < vertexBindingCount; ++i) {
1295 const int inputSlot = startBinding + i;
1296 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, bindings[i].first);
1297 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
1298 if (bufD->m_type == QRhiBuffer::Dynamic)
1300
1301 const quint32 offset = bindings[i].second;
1302 const quint32 stride = inputLayout->bindingAt(inputSlot)->stride();
1303 if (cbD->currentVertexBuffers[inputSlot] != bufD->buffer
1304 || cbD->currentVertexOffsets[inputSlot] != offset
1305 || cbD->currentVertexStrides[inputSlot] != stride)
1306 {
1307 needsBindVBuf = true;
1308 cbD->currentVertexBuffers[inputSlot] = bufD->buffer;
1309 cbD->currentVertexOffsets[inputSlot] = offset;
1310 cbD->currentVertexStrides[inputSlot] = stride;
1311 }
1312 }
1313
1314 if (needsBindVBuf) {
1315 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1317 cmd.args.bindVertexBuffers.startSlot = startBinding;
1318 cmd.args.bindVertexBuffers.slotCount = vertexBindingCount;
1319 for (int i = 0; i < vertexBindingCount; ++i) {
1320 const int inputSlot = startBinding + i;
1321 cmd.args.bindVertexBuffers.buffers[i] = cbD->currentVertexBuffers[inputSlot];
1322 cmd.args.bindVertexBuffers.offsets[i] = cbD->currentVertexOffsets[inputSlot];
1323 cmd.args.bindVertexBuffers.strides[i] = cbD->currentVertexStrides[inputSlot];
1324 }
1325 }
1326
1327 if (indexBuf) {
1328 QD3D11Buffer *ibufD = QRHI_RES(QD3D11Buffer, indexBuf);
1329 Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
1330 if (ibufD->m_type == QRhiBuffer::Dynamic)
1332
1333 const DXGI_FORMAT dxgiFormat = indexFormat == QRhiCommandBuffer::IndexUInt16 ? DXGI_FORMAT_R16_UINT
1334 : DXGI_FORMAT_R32_UINT;
1335 if (cbD->currentIndexBuffer != ibufD->buffer
1336 || cbD->currentIndexOffset != indexOffset
1337 || cbD->currentIndexFormat != dxgiFormat)
1338 {
1339 cbD->currentIndexBuffer = ibufD->buffer;
1340 cbD->currentIndexOffset = indexOffset;
1341 cbD->currentIndexFormat = dxgiFormat;
1342
1343 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1345 cmd.args.bindIndexBuffer.buffer = ibufD->buffer;
1346 cmd.args.bindIndexBuffer.offset = indexOffset;
1347 cmd.args.bindIndexBuffer.format = dxgiFormat;
1348 }
1349 }
1350}
1351
1352void QRhiD3D11::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
1353{
1354 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1356 Q_ASSERT(cbD->currentTarget);
1357 const QSize outputSize = cbD->currentTarget->pixelSize();
1358
1359 // d3d expects top-left, QRhiViewport is bottom-left
1360 float x, y, w, h;
1361 if (!qrhi_toTopLeftRenderTargetRect<UnBounded>(outputSize, viewport.viewport(), &x, &y, &w, &h))
1362 return;
1363
1364 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1366 cmd.args.viewport.x = x;
1367 cmd.args.viewport.y = y;
1368 cmd.args.viewport.w = w;
1369 cmd.args.viewport.h = h;
1370 cmd.args.viewport.d0 = viewport.minDepth();
1371 cmd.args.viewport.d1 = viewport.maxDepth();
1372}
1373
1374void QRhiD3D11::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
1375{
1376 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1378 Q_ASSERT(cbD->currentTarget);
1379 const QSize outputSize = cbD->currentTarget->pixelSize();
1380
1381 // d3d expects top-left, QRhiScissor is bottom-left
1382 int x, y, w, h;
1383 if (!qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, scissor.scissor(), &x, &y, &w, &h))
1384 return;
1385
1386 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1388 cmd.args.scissor.x = x;
1389 cmd.args.scissor.y = y;
1390 cmd.args.scissor.w = w;
1391 cmd.args.scissor.h = h;
1392}
1393
1394void QRhiD3D11::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c)
1395{
1396 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1398
1399 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1401 cmd.args.blendConstants.blendState = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentGraphicsPipeline)->blendState;
1402 cmd.args.blendConstants.c[0] = float(c.redF());
1403 cmd.args.blendConstants.c[1] = float(c.greenF());
1404 cmd.args.blendConstants.c[2] = float(c.blueF());
1405 cmd.args.blendConstants.c[3] = float(c.alphaF());
1406}
1407
1408void QRhiD3D11::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
1409{
1410 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1412
1413 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1415 cmd.args.stencilRef.dsState = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentGraphicsPipeline)->dsState;
1416 cmd.args.stencilRef.ref = refValue;
1417 cbD->currentStencilRef = refValue;
1418}
1419
1420void QRhiD3D11::setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data)
1421{
1422 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1424
1425 int reg = -1;
1426 quint32 blockSize = 0;
1427 uint stages = 0;
1429 QD3D11ComputePipeline *psD = QRHI_RES(QD3D11ComputePipeline, cbD->currentComputePipeline);
1430 if (!psD)
1431 return;
1432 reg = psD->pushConstants.reg;
1433 blockSize = psD->pushConstants.size;
1434 stages = 1u << uint(RBM_COMPUTE);
1435 } else {
1436 QD3D11GraphicsPipeline *psD = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentGraphicsPipeline);
1437 if (!psD)
1438 return;
1439 reg = psD->pushConstants.reg;
1440 blockSize = psD->pushConstants.size;
1441 stages = psD->pushConstants.stages;
1442 }
1443 if (reg < 0 || !blockSize || !stages) {
1444 qWarning("No pipeline with a push constant block is active; setPushConstants ignored");
1445 return;
1446 }
1447
1448 if (offset + size > MAX_PUSH_CONSTANTS_SIZE) {
1449 qWarning("Push constant data of %u bytes at offset %u exceeds the %u byte maximum; "
1450 "setPushConstants ignored", size, offset, MAX_PUSH_CONSTANTS_SIZE);
1451 return;
1452 }
1453
1455 return;
1456
1457 // The constant buffer is written in full every time, so a partial update
1458 // has to be merged into the copy kept on the command buffer.
1459 const quint32 total = qMin(qMax(blockSize, offset + size), MAX_PUSH_CONSTANTS_SIZE);
1460 if (quint32(cbD->pushConstantData.size()) < total)
1461 cbD->pushConstantData.resize(int(total), 0);
1462 memcpy(cbD->pushConstantData.data() + offset, data, size);
1463
1464 const quint32 dataOffset = quint32(cbD->pushConstantPool.size());
1465 cbD->pushConstantPool.append(cbD->pushConstantData.constData(), total);
1466
1467 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1469 cmd.args.setPushConstants.buffer = pushConstantBuffer;
1470 cmd.args.setPushConstants.dataOffset = dataOffset;
1471 cmd.args.setPushConstants.size = total;
1472 cmd.args.setPushConstants.startSlot = uint(reg);
1473 cmd.args.setPushConstants.stages = stages;
1474}
1475
1477{
1478 if (pushConstantBuffer)
1479 return true;
1480
1481 D3D11_BUFFER_DESC desc = {};
1482 desc.ByteWidth = aligned(MAX_PUSH_CONSTANTS_SIZE, 256u);
1483 desc.Usage = D3D11_USAGE_DYNAMIC;
1484 desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1485 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
1486 HRESULT hr = dev->CreateBuffer(&desc, nullptr, &pushConstantBuffer);
1487 if (FAILED(hr)) {
1488 qWarning("Failed to create push constant buffer: %s",
1489 qPrintable(QSystemError::windowsComString(hr)));
1490 pushConstantBuffer = nullptr;
1491 return false;
1492 }
1493 return true;
1494}
1495
1496void QRhiD3D11::setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize)
1497{
1498 Q_UNUSED(cb);
1499 Q_UNUSED(coarsePixelSize);
1500}
1501
1502void QRhiD3D11::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
1503 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
1504{
1505 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1507
1508 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1510 cmd.args.draw.vertexCount = vertexCount;
1511 cmd.args.draw.instanceCount = instanceCount;
1512 cmd.args.draw.firstVertex = firstVertex;
1513 cmd.args.draw.firstInstance = firstInstance;
1514}
1515
1516void QRhiD3D11::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
1517 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
1518{
1519 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1521
1522 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1524 cmd.args.drawIndexed.indexCount = indexCount;
1525 cmd.args.drawIndexed.instanceCount = instanceCount;
1526 cmd.args.drawIndexed.firstIndex = firstIndex;
1527 cmd.args.drawIndexed.vertexOffset = vertexOffset;
1528 cmd.args.drawIndexed.firstInstance = firstInstance;
1529}
1530
1531void QRhiD3D11::drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
1532 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
1533{
1534 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1536
1537 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1539 cmd.args.drawIndirect.indirectBuffer = QRHI_RES(QD3D11Buffer, indirectBuffer)->buffer;
1540 cmd.args.drawIndirect.indirectBufferOffset = indirectBufferOffset;
1541 cmd.args.drawIndirect.drawCount = drawCount;
1542 cmd.args.drawIndirect.stride = stride;
1543}
1544
1545static inline QD3D11RenderTargetData *rtData(QRhiRenderTarget *rt)
1546{
1547 switch (rt->resourceType()) {
1548 case QRhiResource::SwapChainRenderTarget:
1549 return &QRHI_RES(QD3D11SwapChainRenderTarget, rt)->d;
1550 case QRhiResource::TextureRenderTarget:
1551 return &QRHI_RES(QD3D11TextureRenderTarget, rt)->d;
1552 default:
1553 Q_UNREACHABLE();
1554 return nullptr;
1555 }
1556}
1557
1558void QRhiD3D11::drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
1559 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
1560{
1561 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1563
1564 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1566 cmd.args.drawIndexedIndirect.indirectBuffer = QRHI_RES(QD3D11Buffer, indirectBuffer)->buffer;
1567 cmd.args.drawIndexedIndirect.indirectBufferOffset = indirectBufferOffset;
1568 cmd.args.drawIndexedIndirect.drawCount = drawCount;
1569 cmd.args.drawIndexedIndirect.stride = stride;
1570}
1571
1572void QRhiD3D11::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
1573{
1574 if (!debugMarkers || !annotations)
1575 return;
1576
1577 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1578 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1580 qstrncpy(cmd.args.debugMark.s, name.constData(), sizeof(cmd.args.debugMark.s));
1581}
1582
1583void QRhiD3D11::debugMarkEnd(QRhiCommandBuffer *cb)
1584{
1585 if (!debugMarkers || !annotations)
1586 return;
1587
1588 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1589 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1591}
1592
1593void QRhiD3D11::debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg)
1594{
1595 if (!debugMarkers || !annotations)
1596 return;
1597
1598 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1599 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
1601 qstrncpy(cmd.args.debugMark.s, msg.constData(), sizeof(cmd.args.debugMark.s));
1602}
1603
1604const QRhiNativeHandles *QRhiD3D11::nativeHandles(QRhiCommandBuffer *cb)
1605{
1606 Q_UNUSED(cb);
1607 return nullptr;
1608}
1609
1610void QRhiD3D11::beginExternal(QRhiCommandBuffer *cb)
1611{
1612 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1615}
1616
1617void QRhiD3D11::endExternal(QRhiCommandBuffer *cb)
1618{
1619 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1620 Q_ASSERT(cbD->commands.isEmpty());
1622 if (cbD->currentTarget) { // could be compute, no rendertarget then
1623 QD3D11RenderTargetData *rtD = rtData(cbD->currentTarget);
1624 QD3D11CommandBuffer::Command &fbCmd(cbD->commands.get());
1626 fbCmd.args.setRenderTarget.rtViews = rtD->views;
1627 }
1628}
1629
1630double QRhiD3D11::lastCompletedGpuTime(QRhiCommandBuffer *cb)
1631{
1632 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1633 return cbD->lastGpuTime;
1634}
1635
1636QRhi::FrameOpResult QRhiD3D11::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags)
1637{
1638 Q_UNUSED(flags);
1639
1640 if (deviceLost)
1641 return QRhi::FrameOpDeviceLost;
1642
1643 QD3D11SwapChain *swapChainD = QRHI_RES(QD3D11SwapChain, swapChain);
1644 contextState.currentSwapChain = swapChainD;
1645 const int currentFrameSlot = swapChainD->currentFrameSlot;
1646
1647 // if we have a waitable object, now is the time to wait on it
1648 if (swapChainD->frameLatencyWaitableObject) {
1649 // only wait when endFrame() called Present(), otherwise this would become a 1 sec timeout
1650 if (swapChainD->lastFrameLatencyWaitSlot != currentFrameSlot) {
1651 WaitForSingleObjectEx(swapChainD->frameLatencyWaitableObject, 1000, true);
1652 swapChainD->lastFrameLatencyWaitSlot = currentFrameSlot;
1653 }
1654 }
1655
1656 swapChainD->cb.resetState();
1657
1658 swapChainD->rt.d.views.setFrom(1,
1659 swapChainD->sampleDesc.Count > 1 ? &swapChainD->msaaRtv[currentFrameSlot] : &swapChainD->backBufferRtv,
1660 swapChainD->ds ? swapChainD->ds->dsv : nullptr);
1661
1663
1664 if (swapChainD->timestamps.active[swapChainD->currentTimestampPairIndex]) {
1665 double elapsedSec = 0;
1666 if (swapChainD->timestamps.tryQueryTimestamps(swapChainD->currentTimestampPairIndex, context, &elapsedSec))
1667 swapChainD->cb.lastGpuTime = elapsedSec;
1668 }
1669
1670 ID3D11Query *tsStart = swapChainD->timestamps.query[swapChainD->currentTimestampPairIndex * 2];
1671 ID3D11Query *tsDisjoint = swapChainD->timestamps.disjointQuery[swapChainD->currentTimestampPairIndex];
1672 const bool recordTimestamps = tsStart && tsDisjoint && !swapChainD->timestamps.active[swapChainD->currentTimestampPairIndex];
1673
1674 QD3D11CommandBuffer::Command &cmd(swapChainD->cb.commands.get());
1676 cmd.args.beginFrame.tsQuery = recordTimestamps ? tsStart : nullptr;
1677 cmd.args.beginFrame.tsDisjointQuery = recordTimestamps ? tsDisjoint : nullptr;
1678 cmd.args.beginFrame.swapchainRtv = swapChainD->rt.d.views.rtv[0];
1679 cmd.args.beginFrame.swapchainDsv = swapChainD->rt.d.views.dsv;
1680
1681 QDxgiVSyncService::instance()->beginFrame(adapterLuid);
1682
1683 return QRhi::FrameOpSuccess;
1684}
1685
1686QRhi::FrameOpResult QRhiD3D11::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
1687{
1688 QD3D11SwapChain *swapChainD = QRHI_RES(QD3D11SwapChain, swapChain);
1689 Q_ASSERT(contextState.currentSwapChain = swapChainD);
1690 const int currentFrameSlot = swapChainD->currentFrameSlot;
1691
1692 QD3D11CommandBuffer::Command &cmd(swapChainD->cb.commands.get());
1694 cmd.args.endFrame.tsQuery = nullptr; // done later manually, see below
1695 cmd.args.endFrame.tsDisjointQuery = nullptr;
1696
1697 // send all commands to the context
1698 executeCommandBuffer(&swapChainD->cb);
1699
1700 if (swapChainD->sampleDesc.Count > 1) {
1701 context->ResolveSubresource(swapChainD->backBufferTex, 0,
1702 swapChainD->msaaTex[currentFrameSlot], 0,
1703 swapChainD->colorFormat);
1704 }
1705
1706 // this is here because we want to include the time spent on the ResolveSubresource as well
1707 ID3D11Query *tsEnd = swapChainD->timestamps.query[swapChainD->currentTimestampPairIndex * 2 + 1];
1708 ID3D11Query *tsDisjoint = swapChainD->timestamps.disjointQuery[swapChainD->currentTimestampPairIndex];
1709 const bool recordTimestamps = tsEnd && tsDisjoint && !swapChainD->timestamps.active[swapChainD->currentTimestampPairIndex];
1710 if (recordTimestamps) {
1711 context->End(tsEnd);
1712 context->End(tsDisjoint);
1713 swapChainD->timestamps.active[swapChainD->currentTimestampPairIndex] = true;
1715 }
1716
1717 if (!flags.testFlag(QRhi::SkipPresent)) {
1718 UINT presentFlags = 0;
1719 if (swapChainD->swapInterval == 0 && (swapChainD->swapChainFlags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING))
1720 presentFlags |= DXGI_PRESENT_ALLOW_TEARING;
1721 if (!swapChainD->swapChain) {
1722 qWarning("Failed to present: IDXGISwapChain is unavailable");
1723 return QRhi::FrameOpError;
1724 }
1725 HRESULT hr = swapChainD->swapChain->Present(swapChainD->swapInterval, presentFlags);
1726 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
1727 qWarning("Device loss detected in Present()");
1728 deviceLost = true;
1729 return QRhi::FrameOpDeviceLost;
1730 } else if (FAILED(hr)) {
1731 qWarning("Failed to present: %s",
1732 qPrintable(QSystemError::windowsComString(hr)));
1733 return QRhi::FrameOpError;
1734 }
1735
1736 if (dcompDevice && swapChainD->dcompTarget && swapChainD->dcompVisual)
1737 dcompDevice->Commit();
1738
1739 // move on to the next buffer
1741 } else {
1742 context->Flush();
1743 }
1744
1745 swapChainD->frameCount += 1;
1746 contextState.currentSwapChain = nullptr;
1747
1748 return QRhi::FrameOpSuccess;
1749}
1750
1751QRhi::FrameOpResult QRhiD3D11::beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags)
1752{
1753 Q_UNUSED(flags);
1754 ofr.active = true;
1755
1756 ofr.cbWrapper.resetState();
1757 *cb = &ofr.cbWrapper;
1758
1759 if (rhiFlags.testFlag(QRhi::EnableTimestamps)) {
1760 D3D11_QUERY_DESC queryDesc = {};
1761 if (!ofr.tsDisjointQuery) {
1762 queryDesc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
1763 HRESULT hr = dev->CreateQuery(&queryDesc, &ofr.tsDisjointQuery);
1764 if (FAILED(hr)) {
1765 qWarning("Failed to create timestamp disjoint query: %s",
1766 qPrintable(QSystemError::windowsComString(hr)));
1767 return QRhi::FrameOpError;
1768 }
1769 }
1770 queryDesc.Query = D3D11_QUERY_TIMESTAMP;
1771 for (int i = 0; i < 2; ++i) {
1772 if (!ofr.tsQueries[i]) {
1773 HRESULT hr = dev->CreateQuery(&queryDesc, &ofr.tsQueries[i]);
1774 if (FAILED(hr)) {
1775 qWarning("Failed to create timestamp query: %s",
1776 qPrintable(QSystemError::windowsComString(hr)));
1777 return QRhi::FrameOpError;
1778 }
1779 }
1780 }
1781 }
1782
1783 QD3D11CommandBuffer::Command &cmd(ofr.cbWrapper.commands.get());
1785 cmd.args.beginFrame.tsQuery = ofr.tsQueries[0] ? ofr.tsQueries[0] : nullptr;
1786 cmd.args.beginFrame.tsDisjointQuery = ofr.tsDisjointQuery ? ofr.tsDisjointQuery : nullptr;
1787 cmd.args.beginFrame.swapchainRtv = nullptr;
1788 cmd.args.beginFrame.swapchainDsv = nullptr;
1789
1790 return QRhi::FrameOpSuccess;
1791}
1792
1793QRhi::FrameOpResult QRhiD3D11::endOffscreenFrame(QRhi::EndFrameFlags flags)
1794{
1795 Q_UNUSED(flags);
1796 ofr.active = false;
1797
1798 QD3D11CommandBuffer::Command &cmd(ofr.cbWrapper.commands.get());
1800 cmd.args.endFrame.tsQuery = ofr.tsQueries[1] ? ofr.tsQueries[1] : nullptr;
1801 cmd.args.endFrame.tsDisjointQuery = ofr.tsDisjointQuery ? ofr.tsDisjointQuery : nullptr;
1802
1803 executeCommandBuffer(&ofr.cbWrapper);
1804 context->Flush();
1805
1807
1808 if (ofr.tsQueries[0]) {
1809 quint64 timestamps[2];
1810 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT dj;
1811 HRESULT hr;
1812 bool ok = true;
1813 do {
1814 hr = context->GetData(ofr.tsDisjointQuery, &dj, sizeof(dj), 0);
1815 } while (hr == S_FALSE);
1816 ok &= hr == S_OK;
1817 do {
1818 hr = context->GetData(ofr.tsQueries[1], &timestamps[1], sizeof(quint64), 0);
1819 } while (hr == S_FALSE);
1820 ok &= hr == S_OK;
1821 do {
1822 hr = context->GetData(ofr.tsQueries[0], &timestamps[0], sizeof(quint64), 0);
1823 } while (hr == S_FALSE);
1824 ok &= hr == S_OK;
1825 if (ok) {
1826 if (!dj.Disjoint && dj.Frequency) {
1827 const float elapsedMs = (timestamps[1] - timestamps[0]) / float(dj.Frequency) * 1000.0f;
1828 ofr.cbWrapper.lastGpuTime = elapsedMs / 1000.0;
1829 }
1830 }
1831 }
1832
1833 return QRhi::FrameOpSuccess;
1834}
1835
1836static inline DXGI_FORMAT toD3DTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
1837{
1838 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
1839 switch (format) {
1840 case QRhiTexture::RGBA8:
1841 return srgb ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
1842 case QRhiTexture::BGRA8:
1843 return srgb ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : DXGI_FORMAT_B8G8R8A8_UNORM;
1844 case QRhiTexture::R8:
1845 return DXGI_FORMAT_R8_UNORM;
1846 case QRhiTexture::R8SI:
1847 return DXGI_FORMAT_R8_SINT;
1848 case QRhiTexture::R8UI:
1849 return DXGI_FORMAT_R8_UINT;
1850 case QRhiTexture::RG8:
1851 return DXGI_FORMAT_R8G8_UNORM;
1852 case QRhiTexture::R16:
1853 return DXGI_FORMAT_R16_UNORM;
1854 case QRhiTexture::RG16:
1855 return DXGI_FORMAT_R16G16_UNORM;
1856 case QRhiTexture::RED_OR_ALPHA8:
1857 return DXGI_FORMAT_R8_UNORM;
1858
1859 case QRhiTexture::RGBA16F:
1860 return DXGI_FORMAT_R16G16B16A16_FLOAT;
1861 case QRhiTexture::RGBA32F:
1862 return DXGI_FORMAT_R32G32B32A32_FLOAT;
1863 case QRhiTexture::R16F:
1864 return DXGI_FORMAT_R16_FLOAT;
1865 case QRhiTexture::R32F:
1866 return DXGI_FORMAT_R32_FLOAT;
1867
1868 case QRhiTexture::RGB10A2:
1869 return DXGI_FORMAT_R10G10B10A2_UNORM;
1870
1871 case QRhiTexture::R32SI:
1872 return DXGI_FORMAT_R32_SINT;
1873 case QRhiTexture::R32UI:
1874 return DXGI_FORMAT_R32_UINT;
1875 case QRhiTexture::RG32SI:
1876 return DXGI_FORMAT_R32G32_SINT;
1877 case QRhiTexture::RG32UI:
1878 return DXGI_FORMAT_R32G32_UINT;
1879 case QRhiTexture::RGBA32SI:
1880 return DXGI_FORMAT_R32G32B32A32_SINT;
1881 case QRhiTexture::RGBA32UI:
1882 return DXGI_FORMAT_R32G32B32A32_UINT;
1883
1884 case QRhiTexture::D16:
1885 return DXGI_FORMAT_R16_TYPELESS;
1886 case QRhiTexture::D24:
1887 return DXGI_FORMAT_R24G8_TYPELESS;
1888 case QRhiTexture::D24S8:
1889 return DXGI_FORMAT_R24G8_TYPELESS;
1890 case QRhiTexture::D32F:
1891 return DXGI_FORMAT_R32_TYPELESS;
1892 case QRhiTexture::D32FS8:
1893 return DXGI_FORMAT_R32G8X24_TYPELESS;
1894
1895 case QRhiTexture::BC1:
1896 return srgb ? DXGI_FORMAT_BC1_UNORM_SRGB : DXGI_FORMAT_BC1_UNORM;
1897 case QRhiTexture::BC2:
1898 return srgb ? DXGI_FORMAT_BC2_UNORM_SRGB : DXGI_FORMAT_BC2_UNORM;
1899 case QRhiTexture::BC3:
1900 return srgb ? DXGI_FORMAT_BC3_UNORM_SRGB : DXGI_FORMAT_BC3_UNORM;
1901 case QRhiTexture::BC4:
1902 return DXGI_FORMAT_BC4_UNORM;
1903 case QRhiTexture::BC5:
1904 return DXGI_FORMAT_BC5_UNORM;
1905 case QRhiTexture::BC6H:
1906 return DXGI_FORMAT_BC6H_UF16;
1907 case QRhiTexture::BC7:
1908 return srgb ? DXGI_FORMAT_BC7_UNORM_SRGB : DXGI_FORMAT_BC7_UNORM;
1909
1910 case QRhiTexture::ETC2_RGB8:
1911 case QRhiTexture::ETC2_RGB8A1:
1912 case QRhiTexture::ETC2_RGBA8:
1913 qWarning("QRhiD3D11 does not support ETC2 textures");
1914 return DXGI_FORMAT_R8G8B8A8_UNORM;
1915
1916 case QRhiTexture::ASTC_4x4:
1917 case QRhiTexture::ASTC_5x4:
1918 case QRhiTexture::ASTC_5x5:
1919 case QRhiTexture::ASTC_6x5:
1920 case QRhiTexture::ASTC_6x6:
1921 case QRhiTexture::ASTC_8x5:
1922 case QRhiTexture::ASTC_8x6:
1923 case QRhiTexture::ASTC_8x8:
1924 case QRhiTexture::ASTC_10x5:
1925 case QRhiTexture::ASTC_10x6:
1926 case QRhiTexture::ASTC_10x8:
1927 case QRhiTexture::ASTC_10x10:
1928 case QRhiTexture::ASTC_12x10:
1929 case QRhiTexture::ASTC_12x12:
1930 qWarning("QRhiD3D11 does not support ASTC textures");
1931 return DXGI_FORMAT_R8G8B8A8_UNORM;
1932
1933 default:
1934 Q_UNREACHABLE();
1935 return DXGI_FORMAT_R8G8B8A8_UNORM;
1936 }
1937}
1938
1939static inline QRhiTexture::Format swapchainReadbackTextureFormat(DXGI_FORMAT format, QRhiTexture::Flags *flags)
1940{
1941 switch (format) {
1942 case DXGI_FORMAT_R8G8B8A8_UNORM:
1943 return QRhiTexture::RGBA8;
1944 case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
1945 if (flags)
1946 (*flags) |= QRhiTexture::sRGB;
1947 return QRhiTexture::RGBA8;
1948 case DXGI_FORMAT_B8G8R8A8_UNORM:
1949 return QRhiTexture::BGRA8;
1950 case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
1951 if (flags)
1952 (*flags) |= QRhiTexture::sRGB;
1953 return QRhiTexture::BGRA8;
1954 case DXGI_FORMAT_R16G16B16A16_FLOAT:
1955 return QRhiTexture::RGBA16F;
1956 case DXGI_FORMAT_R32G32B32A32_FLOAT:
1957 return QRhiTexture::RGBA32F;
1958 case DXGI_FORMAT_R10G10B10A2_UNORM:
1959 return QRhiTexture::RGB10A2;
1960 default:
1961 qWarning("DXGI_FORMAT %d cannot be read back", format);
1962 break;
1963 }
1964 return QRhiTexture::UnknownFormat;
1965}
1966
1967static inline bool isDepthTextureFormat(QRhiTexture::Format format)
1968{
1969 switch (format) {
1970 case QRhiTexture::Format::D16:
1971 case QRhiTexture::Format::D24:
1972 case QRhiTexture::Format::D24S8:
1973 case QRhiTexture::Format::D32F:
1974 case QRhiTexture::Format::D32FS8:
1975 return true;
1976
1977 default:
1978 return false;
1979 }
1980}
1981
1983{
1984 if (inFrame) {
1985 if (ofr.active) {
1986 Q_ASSERT(!contextState.currentSwapChain);
1987 Q_ASSERT(ofr.cbWrapper.recordingPass == QD3D11CommandBuffer::NoPass);
1988 executeCommandBuffer(&ofr.cbWrapper);
1989 ofr.cbWrapper.resetCommands();
1990 } else {
1991 Q_ASSERT(contextState.currentSwapChain);
1992 Q_ASSERT(contextState.currentSwapChain->cb.recordingPass == QD3D11CommandBuffer::NoPass);
1993 executeCommandBuffer(&contextState.currentSwapChain->cb);
1994 contextState.currentSwapChain->cb.resetCommands();
1995 }
1996 }
1997
1999
2000 return QRhi::FrameOpSuccess;
2001}
2002
2004 int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc)
2005{
2006 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
2007 UINT subres = D3D11CalcSubresource(UINT(level), is3D ? 0u : UINT(layer), texD->mipLevelCount);
2008 D3D11_BOX box;
2009 box.front = is3D ? UINT(layer) : 0u;
2010 // back, right, bottom are exclusive
2011 box.back = box.front + 1;
2012 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2014 cmd.args.updateSubRes.dst = texD->textureResource();
2015 cmd.args.updateSubRes.dstSubRes = subres;
2016
2017 const QPoint dp = subresDesc.destinationTopLeft();
2018 if (!subresDesc.image().isNull()) {
2019 QImage img = subresDesc.image();
2020 QSize size = img.size();
2021 int bpl = img.bytesPerLine();
2022 if (!subresDesc.sourceSize().isEmpty() || !subresDesc.sourceTopLeft().isNull()) {
2023 const QPoint sp = subresDesc.sourceTopLeft();
2024 if (!subresDesc.sourceSize().isEmpty())
2025 size = subresDesc.sourceSize();
2026 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
2027 if (img.depth() == 32) {
2028 const int offset = sp.y() * img.bytesPerLine() + sp.x() * 4;
2029 cmd.args.updateSubRes.src = cbD->retainImage(img) + offset;
2030 } else {
2031 img = img.copy(sp.x(), sp.y(), size.width(), size.height());
2032 bpl = img.bytesPerLine();
2033 cmd.args.updateSubRes.src = cbD->retainImage(img);
2034 }
2035 } else {
2036 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
2037 cmd.args.updateSubRes.src = cbD->retainImage(img);
2038 }
2039 box.left = UINT(dp.x());
2040 box.top = UINT(dp.y());
2041 box.right = UINT(dp.x() + size.width());
2042 box.bottom = UINT(dp.y() + size.height());
2043 cmd.args.updateSubRes.hasDstBox = true;
2044 cmd.args.updateSubRes.dstBox = box;
2045 cmd.args.updateSubRes.srcRowPitch = UINT(bpl);
2046 } else if (!subresDesc.data().isEmpty() && isCompressedFormat(texD->m_format)) {
2047 QSize size = subresDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
2048 : subresDesc.sourceSize();
2049 size = clampedCompressedSubResourceUploadSizeForSourceData(texD->m_format, size,
2050 subresDesc.data().size());
2051 if (size.height() == 0) {
2052 cbD->commands.unget();
2053 return;
2054 }
2055 quint32 bpl = 0;
2056 QSize blockDim;
2057 compressedFormatInfo(texD->m_format, size, &bpl, nullptr, &blockDim);
2058 // Everything must be a multiple of the block width and
2059 // height, so e.g. a mip level of size 2x2 will be 4x4 when it
2060 // comes to the actual data.
2061 box.left = UINT(aligned(dp.x(), blockDim.width()));
2062 box.top = UINT(aligned(dp.y(), blockDim.height()));
2063 box.right = UINT(aligned(dp.x() + size.width(), blockDim.width()));
2064 box.bottom = UINT(aligned(dp.y() + size.height(), blockDim.height()));
2065 cmd.args.updateSubRes.hasDstBox = true;
2066 cmd.args.updateSubRes.dstBox = box;
2067 cmd.args.updateSubRes.src = cbD->retainData(subresDesc.data());
2068 cmd.args.updateSubRes.srcRowPitch = bpl;
2069 } else if (!subresDesc.data().isEmpty()) {
2070 QSize size = subresDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
2071 : subresDesc.sourceSize();
2072 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
2073 quint32 bytesPerPixel = 0;
2074 textureFormatInfo(texD->m_format, size, nullptr, nullptr, &bytesPerPixel);
2075 size = clampedSubResourceUploadSizeForSourceData(size, subresDesc.dataStride(),
2076 bytesPerPixel, subresDesc.data().size());
2077 if (size.isEmpty()) {
2078 cbD->commands.unget();
2079 return;
2080 }
2081 quint32 bpl = 0;
2082 if (subresDesc.dataStride())
2083 bpl = subresDesc.dataStride();
2084 else
2085 textureFormatInfo(texD->m_format, size, &bpl, nullptr, nullptr);
2086 box.left = UINT(dp.x());
2087 box.top = UINT(dp.y());
2088 box.right = UINT(dp.x() + size.width());
2089 box.bottom = UINT(dp.y() + size.height());
2090 cmd.args.updateSubRes.hasDstBox = true;
2091 cmd.args.updateSubRes.dstBox = box;
2092 cmd.args.updateSubRes.src = cbD->retainData(subresDesc.data());
2093 cmd.args.updateSubRes.srcRowPitch = bpl;
2094 } else {
2095 qWarning("Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
2096 cbD->commands.unget();
2097 }
2098}
2099
2100void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2101{
2102 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
2104
2105 for (int opIdx = 0; opIdx < ud->activeBufferOpCount; ++opIdx) {
2106 const QRhiResourceUpdateBatchPrivate::BufferOp &u(ud->bufferOps[opIdx]);
2108 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf);
2109 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
2110 memcpy(bufD->dynBuf + u.offset, u.data.constData(), size_t(u.data.size()));
2111 bufD->hasPendingDynamicUpdates = true;
2113 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf);
2114 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
2115 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
2116 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2118 cmd.args.updateSubRes.dst = bufD->buffer;
2119 cmd.args.updateSubRes.dstSubRes = 0;
2120 cmd.args.updateSubRes.src = cbD->retainBufferData(u.data);
2121 cmd.args.updateSubRes.srcRowPitch = 0;
2122 // Specify the region (even when offset is 0 and all data is provided)
2123 // since the ID3D11Buffer's size is rounded up to be a multiple of 256
2124 // while the data we have has the original size.
2125 D3D11_BOX box;
2126 box.left = u.offset;
2127 box.top = box.front = 0;
2128 box.back = box.bottom = 1;
2129 box.right = u.offset + u.data.size(); // no -1: right, bottom, back are exclusive, see D3D11_BOX doc
2130 cmd.args.updateSubRes.hasDstBox = true;
2131 cmd.args.updateSubRes.dstBox = box;
2133 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf);
2134 if (bufD->m_type == QRhiBuffer::Dynamic) {
2135 u.result->data.resize(u.readSize);
2136 memcpy(u.result->data.data(), bufD->dynBuf + u.offset, size_t(u.readSize));
2137 if (u.result->completed)
2138 u.result->completed();
2139 } else {
2140 BufferReadback readback;
2141 readback.result = u.result;
2142 readback.byteSize = u.readSize;
2143
2144 D3D11_BUFFER_DESC desc = {};
2145 desc.ByteWidth = readback.byteSize;
2146 desc.Usage = D3D11_USAGE_STAGING;
2147 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
2148 HRESULT hr = dev->CreateBuffer(&desc, nullptr, &readback.stagingBuf);
2149 if (FAILED(hr)) {
2150 qWarning("Failed to create buffer: %s",
2151 qPrintable(QSystemError::windowsComString(hr)));
2152 continue;
2153 }
2154
2155 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2157 cmd.args.copySubRes.dst = readback.stagingBuf;
2158 cmd.args.copySubRes.dstSubRes = 0;
2159 cmd.args.copySubRes.dstX = 0;
2160 cmd.args.copySubRes.dstY = 0;
2161 cmd.args.copySubRes.dstZ = 0;
2162 cmd.args.copySubRes.src = bufD->buffer;
2163 cmd.args.copySubRes.srcSubRes = 0;
2164 cmd.args.copySubRes.hasSrcBox = true;
2165 D3D11_BOX box;
2166 box.left = u.offset;
2167 box.top = box.front = 0;
2168 box.back = box.bottom = 1;
2169 box.right = u.offset + u.readSize;
2170 cmd.args.copySubRes.srcBox = box;
2171
2172 activeBufferReadbacks.append(readback);
2173 }
2175 QD3D11Buffer *dstD = QRHI_RES(QD3D11Buffer, u.buf);
2176 QD3D11Buffer *srcD = QRHI_RES(QD3D11Buffer, u.src);
2177 Q_ASSERT(dstD->m_type != QRhiBuffer::Dynamic && srcD->m_type != QRhiBuffer::Dynamic);
2178
2179 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2181 cmd.args.copySubRes.dst = dstD->buffer;
2182 cmd.args.copySubRes.dstSubRes = 0;
2183 cmd.args.copySubRes.dstX = u.offset;
2184 cmd.args.copySubRes.dstY = 0;
2185 cmd.args.copySubRes.dstZ = 0;
2186 cmd.args.copySubRes.src = srcD->buffer;
2187 cmd.args.copySubRes.srcSubRes = 0;
2188 cmd.args.copySubRes.hasSrcBox = true;
2189 D3D11_BOX box;
2190 box.left = u.srcOffset;
2191 box.top = box.front = 0;
2192 box.back = box.bottom = 1;
2193 box.right = u.srcOffset + u.readSize;
2194 cmd.args.copySubRes.srcBox = box;
2196 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf);
2197 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
2198
2199 ID3D11UnorderedAccessView *uav = bufD->createClearUnorderedAccessView(u.offset, u.readSize);
2200 if (!uav)
2201 continue;
2202 cbD->ownedUavs.append(uav);
2203
2204 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2206 cmd.args.clearUav.uav = uav;
2207 for (UINT &v : cmd.args.clearUav.values)
2208 v = u.fillValue32();
2209 }
2210 }
2211 for (int opIdx = 0; opIdx < ud->activeTextureOpCount; ++opIdx) {
2212 const QRhiResourceUpdateBatchPrivate::TextureOp &u(ud->textureOps[opIdx]);
2214 QD3D11Texture *texD = QRHI_RES(QD3D11Texture, u.dst);
2215 for (const auto &subres : u.subresDesc)
2216 enqueueSubresUpload(texD, cbD, subres.layer, subres.level, subres.desc);
2218 Q_ASSERT(u.src && u.dst);
2219 QD3D11Texture *srcD = QRHI_RES(QD3D11Texture, u.src);
2220 QD3D11Texture *dstD = QRHI_RES(QD3D11Texture, u.dst);
2221 const bool srcIs3D = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
2222 const bool dstIs3D = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
2223 UINT srcSubRes = D3D11CalcSubresource(UINT(u.desc.sourceLevel()), srcIs3D ? 0u : UINT(u.desc.sourceLayer()), srcD->mipLevelCount);
2224 UINT dstSubRes = D3D11CalcSubresource(UINT(u.desc.destinationLevel()), dstIs3D ? 0u : UINT(u.desc.destinationLayer()), dstD->mipLevelCount);
2225 const QPoint dp = u.desc.destinationTopLeft();
2226 const QSize mipSize = q->sizeForMipLevel(u.desc.sourceLevel(), srcD->m_pixelSize);
2227 const QSize copySize = u.desc.pixelSize().isEmpty() ? mipSize : u.desc.pixelSize();
2228 const QPoint sp = u.desc.sourceTopLeft();
2229 D3D11_BOX srcBox;
2230 srcBox.left = UINT(sp.x());
2231 srcBox.top = UINT(sp.y());
2232 srcBox.front = srcIs3D ? UINT(u.desc.sourceLayer()) : 0u;
2233 // back, right, bottom are exclusive
2234 srcBox.right = srcBox.left + UINT(copySize.width());
2235 srcBox.bottom = srcBox.top + UINT(copySize.height());
2236 srcBox.back = srcBox.front + 1;
2237 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2239 cmd.args.copySubRes.dst = dstD->textureResource();
2240 cmd.args.copySubRes.dstSubRes = dstSubRes;
2241 cmd.args.copySubRes.dstX = UINT(dp.x());
2242 cmd.args.copySubRes.dstY = UINT(dp.y());
2243 cmd.args.copySubRes.dstZ = dstIs3D ? UINT(u.desc.destinationLayer()) : 0u;
2244 cmd.args.copySubRes.src = srcD->textureResource();
2245 cmd.args.copySubRes.srcSubRes = srcSubRes;
2246 cmd.args.copySubRes.hasSrcBox = true;
2247 cmd.args.copySubRes.srcBox = srcBox;
2249 TextureReadback readback;
2250 readback.desc = u.rb;
2251 readback.result = u.result;
2252
2253 ID3D11Resource *src;
2254 DXGI_FORMAT dxgiFormat;
2255 QRect rect; // what is asked for, and what the result holds
2256 QRect copyRect; // what is copied into the staging texture
2257 QPoint cropOrigin; // where rect starts in the staging texture
2258 QRhiTexture::Format format;
2259 UINT subres = 0;
2260 QD3D11Texture *texD = QRHI_RES(QD3D11Texture, u.rb.texture());
2261 QD3D11SwapChain *swapChainD = nullptr;
2262 bool is3D = false;
2263
2264 if (texD) {
2265 if (texD->sampleDesc.Count > 1) {
2266 qWarning("Multisample texture cannot be read back");
2267 continue;
2268 }
2269 src = texD->textureResource();
2270 dxgiFormat = texD->dxgiFormat;
2271 format = texD->m_format;
2272 const QRect levelRect(QPoint(0, 0), q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize));
2273 rect = u.rb.rect().isValid() ? u.rb.rect() : levelRect;
2274 copyRect = rect;
2275 if (isDepthTextureFormat(format)) {
2276 // CopySubresourceRegion() requires pSrcBox to be null (and
2277 // DstX/Y/Z to be 0, already the case below) whenever either
2278 // resource involved has the D3D11_BIND_DEPTH_STENCIL bind
2279 // flag, i.e. the whole subresource must be copied. The
2280 // requested rectangle is cropped out of it in
2281 // finishActiveReadbacks().
2282 rect = rect.intersected(levelRect);
2283 copyRect = levelRect;
2284 cropOrigin = rect.topLeft();
2285 }
2286 is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
2287 subres = D3D11CalcSubresource(UINT(u.rb.level()), UINT(is3D ? 0 : u.rb.layer()), texD->mipLevelCount);
2288 } else {
2289 Q_ASSERT(contextState.currentSwapChain);
2290 swapChainD = QRHI_RES(QD3D11SwapChain, contextState.currentSwapChain);
2291 if (swapChainD->sampleDesc.Count > 1) {
2292 // Unlike with textures, reading back a multisample swapchain image
2293 // has to be supported. Insert a resolve.
2294 QD3D11CommandBuffer::Command &rcmd(cbD->commands.get());
2296 rcmd.args.resolveSubRes.dst = swapChainD->backBufferTex;
2297 rcmd.args.resolveSubRes.dstSubRes = 0;
2298 rcmd.args.resolveSubRes.src = swapChainD->msaaTex[swapChainD->currentFrameSlot];
2299 rcmd.args.resolveSubRes.srcSubRes = 0;
2300 rcmd.args.resolveSubRes.format = swapChainD->colorFormat;
2301 }
2302 src = swapChainD->backBufferTex;
2303 dxgiFormat = swapChainD->colorFormat;
2304 if (u.rb.rect().isValid())
2305 rect = u.rb.rect();
2306 else
2307 rect = QRect({0, 0}, swapChainD->pixelSize);
2308 copyRect = rect;
2309 format = swapchainReadbackTextureFormat(dxgiFormat, nullptr);
2310 if (format == QRhiTexture::UnknownFormat)
2311 continue;
2312 }
2313 quint32 byteSize = 0;
2314 quint32 bpl = 0;
2315 quint32 bytesPerPixel = 0;
2316 textureFormatInfo(format, rect.size(), &bpl, &byteSize, &bytesPerPixel);
2317
2318 D3D11_TEXTURE2D_DESC desc = {};
2319 desc.Width = UINT(copyRect.width());
2320 desc.Height = UINT(copyRect.height());
2321 desc.MipLevels = 1;
2322 desc.ArraySize = 1;
2323 desc.Format = dxgiFormat;
2324 desc.SampleDesc.Count = 1;
2325 desc.Usage = D3D11_USAGE_STAGING;
2326 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
2327 ID3D11Texture2D *stagingTex;
2328 HRESULT hr = dev->CreateTexture2D(&desc, nullptr, &stagingTex);
2329 if (FAILED(hr)) {
2330 qWarning("Failed to create readback staging texture: %s",
2331 qPrintable(QSystemError::windowsComString(hr)));
2332 return;
2333 }
2334
2335 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2337 cmd.args.copySubRes.dst = stagingTex;
2338 cmd.args.copySubRes.dstSubRes = 0;
2339 cmd.args.copySubRes.dstX = 0;
2340 cmd.args.copySubRes.dstY = 0;
2341 cmd.args.copySubRes.dstZ = 0;
2342 cmd.args.copySubRes.src = src;
2343 cmd.args.copySubRes.srcSubRes = subres;
2344
2345 D3D11_BOX srcBox = {};
2346 srcBox.left = UINT(copyRect.left());
2347 srcBox.top = UINT(copyRect.top());
2348 srcBox.front = is3D ? UINT(u.rb.layer()) : 0u;
2349 // back, right, bottom are exclusive
2350 srcBox.right = srcBox.left + desc.Width;
2351 srcBox.bottom = srcBox.top + desc.Height;
2352 srcBox.back = srcBox.front + 1;
2353 // see the comment above: a depth/stencil source requires a null box
2354 cmd.args.copySubRes.hasSrcBox = !isDepthTextureFormat(format);
2355 cmd.args.copySubRes.srcBox = srcBox;
2356
2357 readback.stagingTex = stagingTex;
2358 readback.byteSize = byteSize;
2359 readback.bpl = bpl;
2360 readback.pixelSize = rect.size();
2361 readback.format = format;
2362 readback.cropOrigin = cropOrigin;
2363 readback.bytesPerPixel = bytesPerPixel;
2364
2365 activeTextureReadbacks.append(readback);
2367 Q_ASSERT(u.dst->flags().testFlag(QRhiTexture::UsedWithGenerateMips));
2368 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2370 cmd.args.genMip.srv = QRHI_RES(QD3D11Texture, u.dst)->srv;
2371 }
2372 }
2373
2374 ud->free();
2375}
2376
2378{
2379 QVarLengthArray<std::function<void()>, 4> completedCallbacks;
2380
2381 for (int i = activeTextureReadbacks.count() - 1; i >= 0; --i) {
2382 const QRhiD3D11::TextureReadback &readback(activeTextureReadbacks[i]);
2383 readback.result->format = readback.format;
2384 readback.result->pixelSize = readback.pixelSize;
2385
2386 D3D11_MAPPED_SUBRESOURCE mp;
2387 HRESULT hr = context->Map(readback.stagingTex, 0, D3D11_MAP_READ, 0, &mp);
2388 if (SUCCEEDED(hr)) {
2389 readback.result->data.resize(int(readback.byteSize));
2390 // nothing says the rows are tightly packed in the texture, must take
2391 // the stride into account
2392 char *dst = readback.result->data.data();
2393 char *src = static_cast<char *>(mp.pData)
2394 + readback.cropOrigin.y() * mp.RowPitch
2395 + readback.cropOrigin.x() * readback.bytesPerPixel;
2396 for (int y = 0, h = readback.pixelSize.height(); y != h; ++y) {
2397 memcpy(dst, src, readback.bpl);
2398 dst += readback.bpl;
2399 src += mp.RowPitch;
2400 }
2401 context->Unmap(readback.stagingTex, 0);
2402
2403 // The staging texture is in the native layout of the depth-stencil
2404 // format: with D24 and D24S8 the depth is in the lower 24 bits and
2405 // the stencil in the upper 8 bits, and with D32FS8 the upper 24 bits
2406 // of the second word are unused. Convert to the layout QRhi
2407 // guarantees: depth in the upper 24 bits and stencil in the lower 8
2408 // bits (D24, D24S8), and only the stencil in the second word of the
2409 // texel (D32FS8), with all unused bits zero.
2410 char *p = readback.result->data.data();
2411 if (readback.format == QRhiTexture::D24 || readback.format == QRhiTexture::D24S8) {
2412 const bool hasStencil = readback.format == QRhiTexture::D24S8;
2413 for (qsizetype px = 0, count = readback.result->data.size() / 4; px < count; ++px) {
2414 const quint32 texel = qFromUnaligned<quint32>(p + px * 4);
2415 const quint32 stencil = hasStencil ? texel >> 24 : 0;
2416 qToUnaligned(((texel & 0x00FFFFFFu) << 8) | stencil, p + px * 4);
2417 }
2418 } else if (readback.format == QRhiTexture::D32FS8) {
2419 for (qsizetype px = 1, count = readback.result->data.size() / 4; px < count; px += 2)
2420 qToUnaligned(qFromUnaligned<quint32>(p + px * 4) & 0xFFu, p + px * 4);
2421 }
2422 } else {
2423 qWarning("Failed to map readback staging texture: %s",
2424 qPrintable(QSystemError::windowsComString(hr)));
2425 }
2426
2427 readback.stagingTex->Release();
2428
2429 if (readback.result->completed)
2430 completedCallbacks.append(readback.result->completed);
2431
2432 activeTextureReadbacks.removeLast();
2433 }
2434
2435 for (int i = activeBufferReadbacks.count() - 1; i >= 0; --i) {
2436 const QRhiD3D11::BufferReadback &readback(activeBufferReadbacks[i]);
2437
2438 D3D11_MAPPED_SUBRESOURCE mp;
2439 HRESULT hr = context->Map(readback.stagingBuf, 0, D3D11_MAP_READ, 0, &mp);
2440 if (SUCCEEDED(hr)) {
2441 readback.result->data.resize(int(readback.byteSize));
2442 memcpy(readback.result->data.data(), mp.pData, readback.byteSize);
2443 context->Unmap(readback.stagingBuf, 0);
2444 } else {
2445 qWarning("Failed to map readback staging texture: %s",
2446 qPrintable(QSystemError::windowsComString(hr)));
2447 }
2448
2449 readback.stagingBuf->Release();
2450
2451 if (readback.result->completed)
2452 completedCallbacks.append(readback.result->completed);
2453
2454 activeBufferReadbacks.removeLast();
2455 }
2456
2457 for (auto f : completedCallbacks)
2458 f();
2459}
2460
2461void QRhiD3D11::resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2462{
2463 Q_ASSERT(QRHI_RES(QD3D11CommandBuffer, cb)->recordingPass == QD3D11CommandBuffer::NoPass);
2464
2465 enqueueResourceUpdates(cb, resourceUpdates);
2466}
2467
2468void QRhiD3D11::beginPass(QRhiCommandBuffer *cb,
2469 QRhiRenderTarget *rt,
2470 const QColor &colorClearValue,
2471 const QRhiDepthStencilClearValue &depthStencilClearValue,
2472 QRhiResourceUpdateBatch *resourceUpdates,
2474{
2475 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
2477
2478 if (resourceUpdates)
2479 enqueueResourceUpdates(cb, resourceUpdates);
2480
2481 bool wantsColorClear = true;
2482 bool wantsDsClear = true;
2484 if (rt->resourceType() == QRhiRenderTarget::TextureRenderTarget) {
2486 wantsColorClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
2487 wantsDsClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
2488 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QD3D11Texture, QD3D11RenderBuffer>(rtTex->description(), rtD->currentResIdList))
2489 rtTex->create();
2490 }
2491
2493
2494 QD3D11CommandBuffer::Command &fbCmd(cbD->commands.get());
2496 fbCmd.args.setRenderTarget.rtViews = rtD->views;
2497
2498 QD3D11CommandBuffer::Command &clearCmd(cbD->commands.get());
2500 clearCmd.args.clear.rtViews = rtD->views;
2501 clearCmd.args.clear.mask = 0;
2502 if (rtD->views.colorAttCount && wantsColorClear)
2503 clearCmd.args.clear.mask |= QD3D11CommandBuffer::Command::Color;
2504 if (rtD->views.dsv && wantsDsClear)
2506
2507 clearCmd.args.clear.c[0] = colorClearValue.redF();
2508 clearCmd.args.clear.c[1] = colorClearValue.greenF();
2509 clearCmd.args.clear.c[2] = colorClearValue.blueF();
2510 clearCmd.args.clear.c[3] = colorClearValue.alphaF();
2511 clearCmd.args.clear.d = depthStencilClearValue.depthClearValue();
2512 clearCmd.args.clear.s = depthStencilClearValue.stencilClearValue();
2513
2515 cbD->currentTarget = rt;
2516
2518}
2519
2520void QRhiD3D11::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2521{
2522 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
2524
2525 if (cbD->currentTarget->resourceType() == QRhiResource::TextureRenderTarget) {
2526 QD3D11TextureRenderTarget *rtTex = QRHI_RES(QD3D11TextureRenderTarget, cbD->currentTarget);
2527 for (auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments();
2528 it != itEnd; ++it)
2529 {
2530 const QRhiColorAttachment &colorAtt(*it);
2531 if (!colorAtt.resolveTexture())
2532 continue;
2533
2534 QD3D11Texture *dstTexD = QRHI_RES(QD3D11Texture, colorAtt.resolveTexture());
2535 QD3D11Texture *srcTexD = QRHI_RES(QD3D11Texture, colorAtt.texture());
2536 QD3D11RenderBuffer *srcRbD = QRHI_RES(QD3D11RenderBuffer, colorAtt.renderBuffer());
2537 Q_ASSERT(srcTexD || srcRbD);
2538 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2540 cmd.args.resolveSubRes.dst = dstTexD->textureResource();
2541 cmd.args.resolveSubRes.dstSubRes = D3D11CalcSubresource(UINT(colorAtt.resolveLevel()),
2542 UINT(colorAtt.resolveLayer()),
2543 dstTexD->mipLevelCount);
2544 if (srcTexD) {
2545 cmd.args.resolveSubRes.src = srcTexD->textureResource();
2546 if (srcTexD->dxgiFormat != dstTexD->dxgiFormat) {
2547 qWarning("Resolve source (%d) and destination (%d) formats do not match",
2548 int(srcTexD->dxgiFormat), int(dstTexD->dxgiFormat));
2549 cbD->commands.unget();
2550 continue;
2551 }
2552 if (srcTexD->sampleDesc.Count <= 1) {
2553 qWarning("Cannot resolve a non-multisample texture");
2554 cbD->commands.unget();
2555 continue;
2556 }
2557 if (srcTexD->m_pixelSize != dstTexD->m_pixelSize) {
2558 qWarning("Resolve source and destination sizes do not match");
2559 cbD->commands.unget();
2560 continue;
2561 }
2562 } else {
2563 cmd.args.resolveSubRes.src = srcRbD->tex;
2564 if (srcRbD->dxgiFormat != dstTexD->dxgiFormat) {
2565 qWarning("Resolve source (%d) and destination (%d) formats do not match",
2566 int(srcRbD->dxgiFormat), int(dstTexD->dxgiFormat));
2567 cbD->commands.unget();
2568 continue;
2569 }
2570 if (srcRbD->m_pixelSize != dstTexD->m_pixelSize) {
2571 qWarning("Resolve source and destination sizes do not match");
2572 cbD->commands.unget();
2573 continue;
2574 }
2575 }
2576 cmd.args.resolveSubRes.srcSubRes = D3D11CalcSubresource(0, UINT(colorAtt.layer()), 1);
2577 cmd.args.resolveSubRes.format = dstTexD->dxgiFormat;
2578 }
2579 if (rtTex->m_desc.depthResolveTexture())
2580 qWarning("Resolving multisample depth-stencil buffers is not supported with D3D");
2581 }
2582
2584 cbD->currentTarget = nullptr;
2585
2586 if (resourceUpdates)
2587 enqueueResourceUpdates(cb, resourceUpdates);
2588}
2589
2590void QRhiD3D11::beginComputePass(QRhiCommandBuffer *cb,
2591 QRhiResourceUpdateBatch *resourceUpdates,
2593{
2594 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
2596
2597 if (resourceUpdates)
2598 enqueueResourceUpdates(cb, resourceUpdates);
2599
2600 // If the compute shader uses any texture as shader resource, and the texture
2601 // was render target of previous beginPass, the render target needs to be cleared
2602 // before shader resources can be reset
2603 QD3D11CommandBuffer::Command &fbCmd(cbD->commands.get());
2605 fbCmd.args.setRenderTarget.rtViews.reset();
2606
2607 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2609
2611
2613}
2614
2615void QRhiD3D11::endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2616{
2617 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
2619
2621
2622 if (resourceUpdates)
2623 enqueueResourceUpdates(cb, resourceUpdates);
2624}
2625
2626void QRhiD3D11::setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps)
2627{
2628 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
2631 const bool pipelineChanged = cbD->currentComputePipeline != ps || cbD->currentPipelineGeneration != psD->generation;
2632
2633 if (pipelineChanged) {
2634 cbD->currentGraphicsPipeline = nullptr;
2635 cbD->currentComputePipeline = psD;
2637
2638 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2640 cmd.args.bindComputePipeline.cs = psD->cs.shader;
2641 }
2642}
2643
2644void QRhiD3D11::dispatch(QRhiCommandBuffer *cb, int x, int y, int z)
2645{
2646 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
2648
2649 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2651 cmd.args.dispatch.x = UINT(x);
2652 cmd.args.dispatch.y = UINT(y);
2653 cmd.args.dispatch.z = UINT(z);
2654}
2655
2656void QRhiD3D11::dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
2657 quint32 indirectBufferOffset)
2658{
2659 QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
2661
2662 QD3D11CommandBuffer::Command &cmd(cbD->commands.get());
2664 cmd.args.dispatchIndirect.indirectBuffer = QRHI_RES(QD3D11Buffer, indirectBuffer)->buffer;
2665 cmd.args.dispatchIndirect.indirectBufferOffset = indirectBufferOffset;
2666}
2667
2668void QRhiD3D11::drawIndirectCount(QRhiCommandBuffer *cb,
2669 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
2670 QRhiBuffer *countBuffer, quint32 countBufferOffset,
2671 quint32 maxDrawCount, quint32 stride)
2672{
2673 Q_UNUSED(cb);
2674 Q_UNUSED(indirectBuffer);
2675 Q_UNUSED(indirectBufferOffset);
2676 Q_UNUSED(countBuffer);
2677 Q_UNUSED(countBufferOffset);
2678 Q_UNUSED(maxDrawCount);
2679 Q_UNUSED(stride);
2680 qWarning("drawIndirectCount is not supported by the D3D11 backend");
2681}
2682
2683void QRhiD3D11::drawIndexedIndirectCount(QRhiCommandBuffer *cb,
2684 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
2685 QRhiBuffer *countBuffer, quint32 countBufferOffset,
2686 quint32 maxDrawCount, quint32 stride)
2687{
2688 Q_UNUSED(cb);
2689 Q_UNUSED(indirectBuffer);
2690 Q_UNUSED(indirectBufferOffset);
2691 Q_UNUSED(countBuffer);
2692 Q_UNUSED(countBufferOffset);
2693 Q_UNUSED(maxDrawCount);
2694 Q_UNUSED(stride);
2695 qWarning("drawIndexedIndirectCount is not supported by the D3D11 backend");
2696}
2697
2698static inline std::pair<int, int> mapBinding(int binding,
2699 int stageIndex,
2700 const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[],
2701 uint pushConstantStages)
2702{
2703 const QShader::NativeResourceBindingMap *map = nativeResourceBindingMaps[stageIndex];
2704 if (!map || map->isEmpty()) {
2705 // An empty map normally means an old qsb that did not generate one,
2706 // hence the 1:1 fallback. But the push constant register is only
2707 // known from qsb versions that always generate the map, so for a
2708 // stage with a push constant block an empty map really means the
2709 // shader has no other resources. Falling back would put a uniform
2710 // buffer at binding 0 on the register reserved for the push constant
2711 // block.
2712 if (pushConstantStages & (1u << uint(stageIndex)))
2713 return { -1, -1 };
2714 return { binding, binding }; // assume 1:1 mapping
2715 }
2716
2717 auto it = map->constFind(binding);
2718 if (it != map->cend())
2719 return *it;
2720
2721 // Hitting this path is normal too. It is not given that the resource is
2722 // present in the shaders for all the stages specified by the visibility
2723 // mask in the QRhiShaderResourceBinding.
2724 return { -1, -1 };
2725}
2726
2728 const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[],
2729 uint pushConstantStages)
2730{
2731 // Share resourceBatches with command buffers that recorded a bind of this
2732 // srb, so that retaining the batches for executeCommandBuffer() is cheap.
2733 // The batches may be retained by a command buffer for a bind that is
2734 // recorded but not yet executed. Those must stay intact, so build into
2735 // a new object in that case.
2736 if (!srbD->resourceBatches || srbD->resourceBatches.use_count() > 1)
2737 srbD->resourceBatches = std::make_shared<QD3D11ShaderResourceBindings::ResourceBatches>();
2738 else
2739 srbD->resourceBatches->clear();
2740
2741 QD3D11ShaderResourceBindings::ResourceBatches &batches(*srbD->resourceBatches);
2742
2743 struct Stage {
2744 struct Buffer {
2745 int binding; // stored and sent along in XXorigbindings just for applyDynamicOffsets()
2746 int breg; // b0, b1, ...
2747 ID3D11Buffer *buffer;
2748 uint offsetInConstants;
2749 uint sizeInConstants;
2750 };
2751 struct Texture {
2752 int treg; // t0, t1, ...
2753 ID3D11ShaderResourceView *srv;
2754 };
2755 struct Sampler {
2756 int sreg; // s0, s1, ...
2757 ID3D11SamplerState *sampler;
2758 };
2759 struct Uav {
2760 int ureg;
2761 ID3D11UnorderedAccessView *uav;
2762 };
2763 QVarLengthArray<Buffer, 8> buffers;
2764 QVarLengthArray<Texture, 8> textures;
2765 QVarLengthArray<Sampler, 8> samplers;
2766 QVarLengthArray<Uav, 8> uavs;
2767 void buildBufferBatches(QD3D11ShaderResourceBindings::StageUniformBufferBatches &batches) const
2768 {
2769 for (const Buffer &buf : buffers) {
2770 batches.ubufs.feed(buf.breg, buf.buffer);
2771 batches.ubuforigbindings.feed(buf.breg, UINT(buf.binding));
2772 batches.ubufoffsets.feed(buf.breg, buf.offsetInConstants);
2773 batches.ubufsizes.feed(buf.breg, buf.sizeInConstants);
2774 }
2775 batches.finish();
2776 }
2777 void buildSamplerBatches(QD3D11ShaderResourceBindings::StageSamplerBatches &batches) const
2778 {
2779 for (const Texture &t : textures)
2780 batches.shaderresources.feed(t.treg, t.srv);
2781 for (const Sampler &s : samplers)
2782 batches.samplers.feed(s.sreg, s.sampler);
2783 batches.finish();
2784 }
2785 void buildUavBatches(QD3D11ShaderResourceBindings::StageUavBatches &batches) const
2786 {
2787 for (const Stage::Uav &u : uavs)
2788 batches.uavs.feed(u.ureg, u.uav);
2789 batches.finish();
2790 }
2791 } res[RBM_SUPPORTED_STAGES];
2792
2793 for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
2794 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings.at(i));
2795 QD3D11ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
2796 switch (b->type()) {
2797 case QRhiShaderResourceBinding::UniformBuffer:
2798 {
2799 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, b->ubuf().buf);
2800 Q_ASSERT(aligned(b->ubuf().offset, 256u) == b->ubuf().offset);
2801 bd.ubuf.id = bufD->m_id;
2802 bd.ubuf.generation = bufD->generation;
2803 // Dynamic ubuf offsets are not considered here, those are baked in
2804 // at a later stage, which is good as vsubufoffsets and friends are
2805 // per-srb, not per-setShaderResources call. Other backends (GL,
2806 // Metal) are different in this respect since those do not store
2807 // per-srb vsubufoffsets etc. data so life's a bit easier for them.
2808 // But here we have to defer baking in the dynamic offset.
2809 const quint32 offsetInConstants = b->ubuf().offset / 16;
2810 // size must be 16 mult. (in constants, i.e. multiple of 256 bytes).
2811 // We can round up if needed since the buffers's actual size
2812 // (ByteWidth) is always a multiple of 256.
2813 const quint32 sizeInConstants = aligned(b->ubuf().maybeSize ? b->ubuf().maybeSize : bufD->m_size, 256u) / 16;
2814 if (b->stage.testFlag(QRhiShaderResourceBinding::VertexStage)) {
2815 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_VERTEX, nativeResourceBindingMaps, pushConstantStages);
2816 if (nativeBinding.first >= 0)
2817 res[RBM_VERTEX].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2818 }
2819 if (b->stage.testFlag(QRhiShaderResourceBinding::TessellationControlStage)) {
2820 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_HULL, nativeResourceBindingMaps, pushConstantStages);
2821 if (nativeBinding.first >= 0)
2822 res[RBM_HULL].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2823 }
2824 if (b->stage.testFlag(QRhiShaderResourceBinding::TessellationEvaluationStage)) {
2825 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_DOMAIN, nativeResourceBindingMaps, pushConstantStages);
2826 if (nativeBinding.first >= 0)
2827 res[RBM_DOMAIN].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2828 }
2829 if (b->stage.testFlag(QRhiShaderResourceBinding::GeometryStage)) {
2830 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_GEOMETRY, nativeResourceBindingMaps, pushConstantStages);
2831 if (nativeBinding.first >= 0)
2832 res[RBM_GEOMETRY].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2833 }
2834 if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
2835 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_FRAGMENT, nativeResourceBindingMaps, pushConstantStages);
2836 if (nativeBinding.first >= 0)
2837 res[RBM_FRAGMENT].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2838 }
2839 if (b->stage.testFlag(QRhiShaderResourceBinding::ComputeStage)) {
2840 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_COMPUTE, nativeResourceBindingMaps, pushConstantStages);
2841 if (nativeBinding.first >= 0)
2842 res[RBM_COMPUTE].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2843 }
2844 }
2845 break;
2846 case QRhiShaderResourceBinding::SampledTexture:
2847 case QRhiShaderResourceBinding::Texture:
2848 case QRhiShaderResourceBinding::Sampler:
2849 {
2850 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
2851 bd.stex.d.resize(data->count());
2852 const std::pair<int, int> nativeBindingVert = mapBinding(b->binding, RBM_VERTEX, nativeResourceBindingMaps, pushConstantStages);
2853 const std::pair<int, int> nativeBindingHull = mapBinding(b->binding, RBM_HULL, nativeResourceBindingMaps, pushConstantStages);
2854 const std::pair<int, int> nativeBindingDomain = mapBinding(b->binding, RBM_DOMAIN, nativeResourceBindingMaps, pushConstantStages);
2855 const std::pair<int, int> nativeBindingGeom = mapBinding(b->binding, RBM_GEOMETRY, nativeResourceBindingMaps, pushConstantStages);
2856 const std::pair<int, int> nativeBindingFrag = mapBinding(b->binding, RBM_FRAGMENT, nativeResourceBindingMaps, pushConstantStages);
2857 const std::pair<int, int> nativeBindingComp = mapBinding(b->binding, RBM_COMPUTE, nativeResourceBindingMaps, pushConstantStages);
2858 // if SPIR-V binding b is mapped to tN and sN in HLSL, and it
2859 // is an array, then it will use tN, tN+1, tN+2, ..., and sN,
2860 // sN+1, sN+2, ...
2861 for (int elem = 0; elem < data->count(); ++elem) {
2862 QD3D11Texture *texD = QRHI_RES(QD3D11Texture, data->texSamplers[elem].tex);
2863 QD3D11Sampler *samplerD = QRHI_RES(QD3D11Sampler, data->texSamplers[elem].sampler);
2864 bd.stex.d[elem].texId = texD ? texD->m_id : 0;
2865 bd.stex.d[elem].texGeneration = texD ? texD->generation : 0;
2866 bd.stex.d[elem].samplerId = samplerD ? samplerD->m_id : 0;
2867 bd.stex.d[elem].samplerGeneration = samplerD ? samplerD->generation : 0;
2868 // Must handle all three cases (combined, separate, separate):
2869 // first = texture binding, second = sampler binding
2870 // first = texture binding
2871 // first = sampler binding
2872 if (b->stage.testFlag(QRhiShaderResourceBinding::VertexStage)) {
2873 const int samplerBinding = texD && samplerD ? nativeBindingVert.second
2874 : (samplerD ? nativeBindingVert.first : -1);
2875 if (nativeBindingVert.first >= 0 && texD)
2876 res[RBM_VERTEX].textures.append({ nativeBindingVert.first + elem, texD->srv });
2877 if (samplerBinding >= 0)
2878 res[RBM_VERTEX].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2879 }
2880 if (b->stage.testFlag(QRhiShaderResourceBinding::TessellationControlStage)) {
2881 const int samplerBinding = texD && samplerD ? nativeBindingHull.second
2882 : (samplerD ? nativeBindingHull.first : -1);
2883 if (nativeBindingHull.first >= 0 && texD)
2884 res[RBM_HULL].textures.append({ nativeBindingHull.first + elem, texD->srv });
2885 if (samplerBinding >= 0)
2886 res[RBM_HULL].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2887 }
2888 if (b->stage.testFlag(QRhiShaderResourceBinding::TessellationEvaluationStage)) {
2889 const int samplerBinding = texD && samplerD ? nativeBindingDomain.second
2890 : (samplerD ? nativeBindingDomain.first : -1);
2891 if (nativeBindingDomain.first >= 0 && texD)
2892 res[RBM_DOMAIN].textures.append({ nativeBindingDomain.first + elem, texD->srv });
2893 if (samplerBinding >= 0)
2894 res[RBM_DOMAIN].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2895 }
2896 if (b->stage.testFlag(QRhiShaderResourceBinding::GeometryStage)) {
2897 const int samplerBinding = texD && samplerD ? nativeBindingGeom.second
2898 : (samplerD ? nativeBindingGeom.first : -1);
2899 if (nativeBindingGeom.first >= 0 && texD)
2900 res[RBM_GEOMETRY].textures.append({ nativeBindingGeom.first + elem, texD->srv });
2901 if (samplerBinding >= 0)
2902 res[RBM_GEOMETRY].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2903 }
2904 if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
2905 const int samplerBinding = texD && samplerD ? nativeBindingFrag.second
2906 : (samplerD ? nativeBindingFrag.first : -1);
2907 if (nativeBindingFrag.first >= 0 && texD)
2908 res[RBM_FRAGMENT].textures.append({ nativeBindingFrag.first + elem, texD->srv });
2909 if (samplerBinding >= 0)
2910 res[RBM_FRAGMENT].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2911 }
2912 if (b->stage.testFlag(QRhiShaderResourceBinding::ComputeStage)) {
2913 const int samplerBinding = texD && samplerD ? nativeBindingComp.second
2914 : (samplerD ? nativeBindingComp.first : -1);
2915 if (nativeBindingComp.first >= 0 && texD)
2916 res[RBM_COMPUTE].textures.append({ nativeBindingComp.first + elem, texD->srv });
2917 if (samplerBinding >= 0)
2918 res[RBM_COMPUTE].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2919 }
2920 }
2921 }
2922 break;
2923 case QRhiShaderResourceBinding::ImageLoad:
2924 case QRhiShaderResourceBinding::ImageStore:
2925 case QRhiShaderResourceBinding::ImageLoadStore:
2926 {
2927 QD3D11Texture *texD = QRHI_RES(QD3D11Texture, b->simage().tex);
2928 bd.simage.id = texD->m_id;
2929 bd.simage.generation = texD->generation;
2930 bool validStage = false;
2931 if (b->stage.testFlag(QRhiShaderResourceBinding::ComputeStage)) {
2932 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_COMPUTE, nativeResourceBindingMaps, pushConstantStages);
2933 if (nativeBinding.first >= 0) {
2934 ID3D11UnorderedAccessView *uav = texD->unorderedAccessViewForLevel(b->simage().level);
2935 if (uav)
2936 res[RBM_COMPUTE].uavs.append({ nativeBinding.first, uav });
2937 }
2938 validStage = true;
2939 }
2940 if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
2941 QPair<int, int> nativeBinding = mapBinding(b->binding, RBM_FRAGMENT, nativeResourceBindingMaps, pushConstantStages);
2942 if (nativeBinding.first >= 0) {
2943 ID3D11UnorderedAccessView *uav = texD->unorderedAccessViewForLevel(b->simage().level);
2944 if (uav)
2945 res[RBM_FRAGMENT].uavs.append({ nativeBinding.first, uav });
2946 }
2947 validStage = true;
2948 }
2949 if (!validStage)
2950 qWarning("Unordered access only supported at fragment/compute stage");
2951 }
2952 break;
2953 case QRhiShaderResourceBinding::BufferLoad:
2954 case QRhiShaderResourceBinding::BufferStore:
2955 case QRhiShaderResourceBinding::BufferLoadStore:
2956 {
2957 QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, b->sbuf().buf);
2958 bd.sbuf.id = bufD->m_id;
2959 bd.sbuf.generation = bufD->generation;
2960 bool validStage = false;
2961 if (b->stage.testFlag(QRhiShaderResourceBinding::ComputeStage)) {
2962 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_COMPUTE, nativeResourceBindingMaps, pushConstantStages);
2963 if (nativeBinding.first >= 0) {
2964 ID3D11UnorderedAccessView *uav = bufD->unorderedAccessView(b->sbuf().offset);
2965 if (uav)
2966 res[RBM_COMPUTE].uavs.append({ nativeBinding.first, uav });
2967 }
2968 validStage = true;
2969 }
2970 if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
2971 std::pair<int, int> nativeBinding = mapBinding(b->binding, RBM_FRAGMENT, nativeResourceBindingMaps, pushConstantStages);
2972 if (nativeBinding.first >= 0) {
2973 ID3D11UnorderedAccessView *uav = bufD->unorderedAccessView(b->sbuf().offset);
2974 if (uav)
2975 res[RBM_FRAGMENT].uavs.append({ nativeBinding.first, uav });
2976 }
2977 validStage = true;
2978 }
2979 if (!validStage)
2980 qWarning("Unordered access only supported at fragment/compute stage");
2981 }
2982 break;
2983 default:
2984 Q_UNREACHABLE();
2985 break;
2986 }
2987 }
2988
2989 // QRhiBatchedBindings works with the native bindings and expects
2990 // sorted input. The pre-sorted QRhiShaderResourceBinding list (based
2991 // on the QRhi (SPIR-V) binding) is not helpful in this regard, so we
2992 // have to sort here every time.
2993 for (int stage = 0; stage < RBM_SUPPORTED_STAGES; ++stage) {
2994 std::sort(res[stage].buffers.begin(), res[stage].buffers.end(), [](const Stage::Buffer &a, const Stage::Buffer &b) {
2995 return a.breg < b.breg;
2996 });
2997 std::sort(res[stage].textures.begin(), res[stage].textures.end(), [](const Stage::Texture &a, const Stage::Texture &b) {
2998 return a.treg < b.treg;
2999 });
3000 std::sort(res[stage].samplers.begin(), res[stage].samplers.end(), [](const Stage::Sampler &a, const Stage::Sampler &b) {
3001 return a.sreg < b.sreg;
3002 });
3003 std::sort(res[stage].uavs.begin(), res[stage].uavs.end(), [](const Stage::Uav &a, const Stage::Uav &b) {
3004 return a.ureg < b.ureg;
3005 });
3006 }
3007
3008 res[RBM_VERTEX].buildBufferBatches(batches.vsUniformBufferBatches);
3009 res[RBM_HULL].buildBufferBatches(batches.hsUniformBufferBatches);
3010 res[RBM_DOMAIN].buildBufferBatches(batches.dsUniformBufferBatches);
3011 res[RBM_GEOMETRY].buildBufferBatches(batches.gsUniformBufferBatches);
3012 res[RBM_FRAGMENT].buildBufferBatches(batches.fsUniformBufferBatches);
3013 res[RBM_COMPUTE].buildBufferBatches(batches.csUniformBufferBatches);
3014
3015 res[RBM_VERTEX].buildSamplerBatches(batches.vsSamplerBatches);
3016 res[RBM_HULL].buildSamplerBatches(batches.hsSamplerBatches);
3017 res[RBM_DOMAIN].buildSamplerBatches(batches.dsSamplerBatches);
3018 res[RBM_GEOMETRY].buildSamplerBatches(batches.gsSamplerBatches);
3019 res[RBM_FRAGMENT].buildSamplerBatches(batches.fsSamplerBatches);
3020 res[RBM_COMPUTE].buildSamplerBatches(batches.csSamplerBatches);
3021
3022 res[RBM_FRAGMENT].buildUavBatches(batches.fsUavBatches);
3023 res[RBM_COMPUTE].buildUavBatches(batches.csUavBatches);
3024}
3025
3027{
3028 if (!bufD->hasPendingDynamicUpdates || bufD->m_size < 1)
3029 return;
3030
3031 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
3032 bufD->hasPendingDynamicUpdates = false;
3033 D3D11_MAPPED_SUBRESOURCE mp;
3034 HRESULT hr = context->Map(bufD->buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
3035 if (SUCCEEDED(hr)) {
3036 memcpy(mp.pData, bufD->dynBuf, bufD->m_size);
3037 context->Unmap(bufD->buffer, 0);
3038 } else {
3039 qWarning("Failed to map buffer: %s",
3040 qPrintable(QSystemError::windowsComString(hr)));
3041 }
3042}
3043
3044static void applyDynamicOffsets(UINT *offsets,
3045 int batchIndex,
3046 const QRhiBatchedBindings<UINT> *originalBindings,
3047 const QRhiBatchedBindings<UINT> *staticOffsets,
3048 const uint *dynOfsPairs, int dynOfsPairCount)
3049{
3050 const int count = staticOffsets->batches[batchIndex].resources.count();
3051 // Make a copy of the offset list, the entries that have no corresponding
3052 // dynamic offset will continue to use the existing offset value.
3053 for (int b = 0; b < count; ++b) {
3054 offsets[b] = staticOffsets->batches[batchIndex].resources[b];
3055 for (int di = 0; di < dynOfsPairCount; ++di) {
3056 const uint binding = dynOfsPairs[2 * di];
3057 // binding is the SPIR-V style binding point here, nothing to do
3058 // with the native one.
3059 if (binding == originalBindings->batches[batchIndex].resources[b]) {
3060 const uint offsetInConstants = dynOfsPairs[2 * di + 1];
3061 offsets[b] = offsetInConstants;
3062 break;
3063 }
3064 }
3065 }
3066}
3067
3068static inline uint clampedResourceCount(uint startSlot, int countSlots, uint maxSlots, const char *resType)
3069{
3070 if (startSlot + countSlots > maxSlots) {
3071 qWarning("Not enough D3D11 %s slots to bind %d resources starting at slot %d, max slots is %d",
3072 resType, countSlots, startSlot, maxSlots);
3073 countSlots = maxSlots > startSlot ? maxSlots - startSlot : 0;
3074 }
3075 return countSlots;
3076}
3077
3078#define SETUBUFBATCH(stagePrefixL, stagePrefixU)
3079 if (allResourceBatches.stagePrefixL##UniformBufferBatches.present) {
3080 const QD3D11ShaderResourceBindings::StageUniformBufferBatches &batches(allResourceBatches.stagePrefixL##UniformBufferBatches);
3081 for (int i = 0, ie = batches.ubufs.batches.count(); i != ie; ++i) {
3082 const uint count = clampedResourceCount(batches.ubufs.batches[i].startBinding,
3083 batches.ubufs.batches[i].resources.count(),
3084 D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT,
3085 #stagePrefixU " cbuf");
3086 if (count) {
3087 if (!dynOfsPairCount) {
3088 context->stagePrefixU##SetConstantBuffers1(batches.ubufs.batches[i].startBinding,
3089 count,
3090 batches.ubufs.batches[i].resources.constData(),
3091 batches.ubufoffsets.batches[i].resources.constData(),
3092 batches.ubufsizes.batches[i].resources.constData());
3093 } else {
3094 applyDynamicOffsets(offsets, i,
3095 &batches.ubuforigbindings, &batches.ubufoffsets,
3096 dynOfsPairs, dynOfsPairCount);
3097 context->stagePrefixU##SetConstantBuffers1(batches.ubufs.batches[i].startBinding,
3098 count,
3099 batches.ubufs.batches[i].resources.constData(),
3100 offsets,
3101 batches.ubufsizes.batches[i].resources.constData());
3102 }
3103 }
3104 }
3105 }
3106
3107#define SETSAMPLERBATCH(stagePrefixL, stagePrefixU)
3108 if (allResourceBatches.stagePrefixL##SamplerBatches.present) {
3109 for (const auto &batch : allResourceBatches.stagePrefixL##SamplerBatches.samplers.batches) {
3110 const uint count = clampedResourceCount(batch.startBinding, batch.resources.count(),
3111 D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, #stagePrefixU " sampler");
3112 if (count)
3113 context->stagePrefixU##SetSamplers(batch.startBinding, count, batch.resources.constData());
3114 }
3115 for (const auto &batch : allResourceBatches.stagePrefixL##SamplerBatches.shaderresources.batches) {
3116 const uint count = clampedResourceCount(batch.startBinding, batch.resources.count(),
3117 D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, #stagePrefixU " SRV");
3118 if (count) {
3119 context->stagePrefixU##SetShaderResources(batch.startBinding, count, batch.resources.constData());
3120 contextState.stagePrefixL##HighestActiveSrvBinding = qMax(contextState.stagePrefixL##HighestActiveSrvBinding,
3121 int(batch.startBinding + count) - 1);
3122 }
3123 }
3124 }
3125
3126#define SETUAVBATCH(stagePrefixL, stagePrefixU)
3127 if (allResourceBatches.stagePrefixL##UavBatches.present) {
3128 for (const auto &batch : allResourceBatches.stagePrefixL##UavBatches.uavs.batches) {
3129 const uint count = clampedResourceCount(batch.startBinding, batch.resources.count(),
3130 D3D11_1_UAV_SLOT_COUNT, #stagePrefixU " UAV");
3131 if (count) {
3132 context->stagePrefixU##SetUnorderedAccessViews(batch.startBinding,
3133 count,
3134 batch.resources.constData(),
3135 nullptr);
3136 contextState.stagePrefixL##HighestActiveUavBinding = qMax(contextState.stagePrefixL##HighestActiveUavBinding,
3137 int(batch.startBinding + count) - 1);
3138 }
3139 }
3140 }
3141
3143 const QD3D11ShaderResourceBindings::ResourceBatches &allResourceBatches,
3144 const uint *dynOfsPairs, int dynOfsPairCount,
3145 bool offsetOnlyChange,
3147{
3149
3150 SETUBUFBATCH(vs, VS)
3151 SETUBUFBATCH(hs, HS)
3152 SETUBUFBATCH(ds, DS)
3153 SETUBUFBATCH(gs, GS)
3154 SETUBUFBATCH(fs, PS)
3155 SETUBUFBATCH(cs, CS)
3156
3157 if (!offsetOnlyChange) {
3158 SETSAMPLERBATCH(vs, VS)
3159 SETSAMPLERBATCH(hs, HS)
3160 SETSAMPLERBATCH(ds, DS)
3161 SETSAMPLERBATCH(gs, GS)
3162 SETSAMPLERBATCH(fs, PS)
3163 SETSAMPLERBATCH(cs, CS)
3164
3165 SETUAVBATCH(cs, CS)
3166
3167 if (allResourceBatches.fsUavBatches.present) {
3168 for (const auto &batch : allResourceBatches.fsUavBatches.uavs.batches) {
3169 const uint count = qMin(clampedResourceCount(batch.startBinding, batch.resources.count(),
3170 D3D11_1_UAV_SLOT_COUNT, "fs UAV"),
3171 uint(QD3D11RenderTargetData::MAX_COLOR_ATTACHMENTS));
3172 if (count) {
3173 if (rtUavState->update(cbD->currentRenderTargetViews, batch.resources.constData(), count)) {
3174 context->OMSetRenderTargetsAndUnorderedAccessViews(
3175 UINT(rtUavState->rtViews.colorAttCount),
3176 rtUavState->rtViews.colorAttCount ? rtUavState->rtViews.rtv : nullptr,
3177 rtUavState->rtViews.dsv,
3178 UINT(batch.startBinding),
3179 count,
3180 batch.resources.constData(),
3181 nullptr);
3182 }
3183 contextState.fsHighestActiveUavBinding = qMax(contextState.fsHighestActiveUavBinding,
3184 int(batch.startBinding + count) - 1);
3185 }
3186 }
3187 }
3188 }
3189}
3190
3193{
3194 // Output cannot be bound on input etc.
3195
3196 if (contextState.vsHasIndexBufferBound) {
3197 context->IASetIndexBuffer(nullptr, DXGI_FORMAT_R16_UINT, 0);
3198 contextState.vsHasIndexBufferBound = false;
3199 }
3200
3201 if (contextState.vsHighestActiveVertexBufferBinding >= 0) {
3202 const int count = contextState.vsHighestActiveVertexBufferBinding + 1;
3203 QVarLengthArray<ID3D11Buffer *, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> nullbufs(count);
3204 for (int i = 0; i < count; ++i)
3205 nullbufs[i] = nullptr;
3206 QVarLengthArray<UINT, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> nullstrides(count);
3207 for (int i = 0; i < count; ++i)
3208 nullstrides[i] = 0;
3209 QVarLengthArray<UINT, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> nulloffsets(count);
3210 for (int i = 0; i < count; ++i)
3211 nulloffsets[i] = 0;
3212 context->IASetVertexBuffers(0, UINT(count), nullbufs.constData(), nullstrides.constData(), nulloffsets.constData());
3213 contextState.vsHighestActiveVertexBufferBinding = -1;
3214 }
3215
3216 int nullsrvCount = qMax(contextState.vsHighestActiveSrvBinding, contextState.fsHighestActiveSrvBinding);
3217 nullsrvCount = qMax(nullsrvCount, contextState.hsHighestActiveSrvBinding);
3218 nullsrvCount = qMax(nullsrvCount, contextState.dsHighestActiveSrvBinding);
3219 nullsrvCount = qMax(nullsrvCount, contextState.gsHighestActiveSrvBinding);
3220 nullsrvCount = qMax(nullsrvCount, contextState.csHighestActiveSrvBinding);
3221 nullsrvCount += 1;
3222 if (nullsrvCount > 0) {
3223 QVarLengthArray<ID3D11ShaderResourceView *,
3224 D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT> nullsrvs(nullsrvCount);
3225 for (int i = 0; i < nullsrvs.count(); ++i)
3226 nullsrvs[i] = nullptr;
3227 if (contextState.vsHighestActiveSrvBinding >= 0) {
3228 context->VSSetShaderResources(0, UINT(contextState.vsHighestActiveSrvBinding + 1), nullsrvs.constData());
3229 contextState.vsHighestActiveSrvBinding = -1;
3230 }
3231 if (contextState.hsHighestActiveSrvBinding >= 0) {
3232 context->HSSetShaderResources(0, UINT(contextState.hsHighestActiveSrvBinding + 1), nullsrvs.constData());
3233 contextState.hsHighestActiveSrvBinding = -1;
3234 }
3235 if (contextState.dsHighestActiveSrvBinding >= 0) {
3236 context->DSSetShaderResources(0, UINT(contextState.dsHighestActiveSrvBinding + 1), nullsrvs.constData());
3237 contextState.dsHighestActiveSrvBinding = -1;
3238 }
3239 if (contextState.gsHighestActiveSrvBinding >= 0) {
3240 context->GSSetShaderResources(0, UINT(contextState.gsHighestActiveSrvBinding + 1), nullsrvs.constData());
3241 contextState.gsHighestActiveSrvBinding = -1;
3242 }
3243 if (contextState.fsHighestActiveSrvBinding >= 0) {
3244 context->PSSetShaderResources(0, UINT(contextState.fsHighestActiveSrvBinding + 1), nullsrvs.constData());
3245 contextState.fsHighestActiveSrvBinding = -1;
3246 }
3247 if (contextState.csHighestActiveSrvBinding >= 0) {
3248 context->CSSetShaderResources(0, UINT(contextState.csHighestActiveSrvBinding + 1), nullsrvs.constData());
3249 contextState.csHighestActiveSrvBinding = -1;
3250 }
3251 }
3252
3253 if (contextState.fsHighestActiveUavBinding >= 0) {
3254 rtUavState->update(cbD->currentRenderTargetViews);
3255 context->OMSetRenderTargetsAndUnorderedAccessViews(
3256 UINT(cbD->currentRenderTargetViews.colorAttCount),
3257 cbD->currentRenderTargetViews.colorAttCount ? cbD->currentRenderTargetViews.rtv : nullptr,
3258 cbD->currentRenderTargetViews.dsv,
3259 0, 0, nullptr, nullptr);
3260 contextState.fsHighestActiveUavBinding = -1;
3261 }
3262 if (contextState.csHighestActiveUavBinding >= 0) {
3263 const int nulluavCount = contextState.csHighestActiveUavBinding + 1;
3264 QVarLengthArray<ID3D11UnorderedAccessView *,
3265 D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT> nulluavs(nulluavCount);
3266 for (int i = 0; i < nulluavCount; ++i)
3267 nulluavs[i] = nullptr;
3268 context->CSSetUnorderedAccessViews(0, UINT(nulluavCount), nulluavs.constData(), nullptr);
3269 contextState.csHighestActiveUavBinding = -1;
3270 }
3271}
3272
3273#define SETSHADER(StageL, StageU)
3274 if (cmd.args.bindGraphicsPipeline.StageL) {
3275 context->StageU##SetShader(cmd.args.bindGraphicsPipeline.StageL, nullptr, 0);
3276 currentShaderMask |= StageU##MaskBit;
3277 } else if (currentShaderMask & StageU##MaskBit) {
3278 context->StageU##SetShader(nullptr, nullptr, 0);
3279 currentShaderMask &= ~StageU##MaskBit;
3280 }
3281
3283{
3284 float blendConstants[] = { 1, 1, 1, 1 };
3285 enum ActiveShaderMask {
3286 VSMaskBit = 0x01,
3287 HSMaskBit = 0x02,
3288 DSMaskBit = 0x04,
3289 GSMaskBit = 0x08,
3290 PSMaskBit = 0x10
3291 };
3292 int currentShaderMask = 0xFF;
3293
3294 // Track render target and uav updates during executeCommandBuffer.
3295 // Prevents multiple identical OMSetRenderTargetsAndUnorderedAccessViews calls.
3297
3298 for (auto it = cbD->commands.cbegin(), end = cbD->commands.cend(); it != end; ++it) {
3299 const QD3D11CommandBuffer::Command &cmd(*it);
3300 switch (cmd.cmd) {
3301 case QD3D11CommandBuffer::Command::BeginFrame:
3302 if (cmd.args.beginFrame.tsDisjointQuery)
3303 context->Begin(cmd.args.beginFrame.tsDisjointQuery);
3304 if (cmd.args.beginFrame.tsQuery) {
3305 if (cmd.args.beginFrame.swapchainRtv) {
3306 // The timestamps seem to include vsync time with Present(1), except
3307 // when running on a non-primary gpu. This is not ideal. So try working
3308 // it around by issuing a semi-fake OMSetRenderTargets early and
3309 // writing the first timestamp only afterwards.
3310 cbD->currentRenderTargetViews.setFrom(1, &cmd.args.beginFrame.swapchainRtv, cmd.args.beginFrame.swapchainDsv);
3311 rtUavState.update(cbD->currentRenderTargetViews);
3312 context->OMSetRenderTargets(1, &cmd.args.beginFrame.swapchainRtv, cmd.args.beginFrame.swapchainDsv);
3313 }
3314 context->End(cmd.args.beginFrame.tsQuery); // no Begin() for D3D11_QUERY_TIMESTAMP
3315 }
3316 break;
3317 case QD3D11CommandBuffer::Command::EndFrame:
3318 if (cmd.args.endFrame.tsQuery)
3319 context->End(cmd.args.endFrame.tsQuery);
3320 if (cmd.args.endFrame.tsDisjointQuery)
3321 context->End(cmd.args.endFrame.tsDisjointQuery);
3322 break;
3324 resetShaderResources(cbD, &rtUavState);
3325 break;
3327 {
3328 cbD->currentRenderTargetViews = cmd.args.setRenderTarget.rtViews;
3329 if (rtUavState.update(cbD->currentRenderTargetViews)) {
3330 const UINT colorAttCount = UINT(cmd.args.setRenderTarget.rtViews.colorAttCount);
3331 context->OMSetRenderTargets(colorAttCount,
3332 colorAttCount ? cmd.args.setRenderTarget.rtViews.rtv : nullptr,
3333 cmd.args.setRenderTarget.rtViews.dsv);
3334 }
3335 }
3336 break;
3338 {
3339 if (cmd.args.clear.mask & QD3D11CommandBuffer::Command::Color) {
3340 for (int i = 0; i < cmd.args.clear.rtViews.colorAttCount; ++i)
3341 context->ClearRenderTargetView(cmd.args.clear.rtViews.rtv[i], cmd.args.clear.c);
3342 }
3343 uint ds = 0;
3344 if (cmd.args.clear.mask & QD3D11CommandBuffer::Command::Depth)
3345 ds |= D3D11_CLEAR_DEPTH;
3346 if (cmd.args.clear.mask & QD3D11CommandBuffer::Command::Stencil)
3347 ds |= D3D11_CLEAR_STENCIL;
3348 if (ds && cmd.args.clear.rtViews.dsv)
3349 context->ClearDepthStencilView(cmd.args.clear.rtViews.dsv, ds, cmd.args.clear.d, UINT8(cmd.args.clear.s));
3350 }
3351 break;
3353 {
3354 D3D11_VIEWPORT v;
3355 v.TopLeftX = cmd.args.viewport.x;
3356 v.TopLeftY = cmd.args.viewport.y;
3357 v.Width = cmd.args.viewport.w;
3358 v.Height = cmd.args.viewport.h;
3359 v.MinDepth = cmd.args.viewport.d0;
3360 v.MaxDepth = cmd.args.viewport.d1;
3361 context->RSSetViewports(1, &v);
3362 }
3363 break;
3365 {
3366 D3D11_RECT r;
3367 r.left = cmd.args.scissor.x;
3368 r.top = cmd.args.scissor.y;
3369 // right and bottom are exclusive
3370 r.right = cmd.args.scissor.x + cmd.args.scissor.w;
3371 r.bottom = cmd.args.scissor.y + cmd.args.scissor.h;
3372 context->RSSetScissorRects(1, &r);
3373 }
3374 break;
3376 contextState.vsHighestActiveVertexBufferBinding = qMax<int>(
3377 contextState.vsHighestActiveVertexBufferBinding,
3378 cmd.args.bindVertexBuffers.startSlot + cmd.args.bindVertexBuffers.slotCount - 1);
3379 context->IASetVertexBuffers(UINT(cmd.args.bindVertexBuffers.startSlot),
3380 UINT(cmd.args.bindVertexBuffers.slotCount),
3381 cmd.args.bindVertexBuffers.buffers,
3382 cmd.args.bindVertexBuffers.strides,
3383 cmd.args.bindVertexBuffers.offsets);
3384 break;
3386 contextState.vsHasIndexBufferBound = true;
3387 context->IASetIndexBuffer(cmd.args.bindIndexBuffer.buffer,
3388 cmd.args.bindIndexBuffer.format,
3389 cmd.args.bindIndexBuffer.offset);
3390 break;
3392 {
3393 SETSHADER(vs, VS)
3394 SETSHADER(hs, HS)
3395 SETSHADER(ds, DS)
3396 SETSHADER(gs, GS)
3397 SETSHADER(fs, PS)
3398 context->IASetPrimitiveTopology(cmd.args.bindGraphicsPipeline.topology);
3399 context->IASetInputLayout(cmd.args.bindGraphicsPipeline.inputLayout);
3400 context->OMSetDepthStencilState(cmd.args.bindGraphicsPipeline.dsState, cmd.args.bindGraphicsPipeline.stencilRef);
3401 context->OMSetBlendState(cmd.args.bindGraphicsPipeline.blendState, blendConstants, 0xffffffff);
3402 context->RSSetState(cmd.args.bindGraphicsPipeline.rastState);
3403 }
3404 break;
3407 *cbD->resourceBatchRetainPool[cmd.args.bindShaderResources.resourceBatchesIndex],
3408 cmd.args.bindShaderResources.dynamicOffsetPairs,
3409 cmd.args.bindShaderResources.dynamicOffsetCount,
3410 cmd.args.bindShaderResources.offsetOnlyChange,
3411 &rtUavState);
3412 break;
3414 {
3415 // With WRITE_DISCARD the draw calls already recorded keep seeing
3416 // the data they were given, which is what allows varying the values
3417 // between the draw calls.
3418 ID3D11Buffer *buf = cmd.args.setPushConstants.buffer;
3419 D3D11_MAPPED_SUBRESOURCE mp;
3420 HRESULT hr = context->Map(buf, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
3421 if (SUCCEEDED(hr)) {
3422 memcpy(mp.pData, cbD->pushConstantPool.constData() + cmd.args.setPushConstants.dataOffset,
3423 cmd.args.setPushConstants.size);
3424 context->Unmap(buf, 0);
3425 } else {
3426 qWarning("Failed to map push constant buffer: %s",
3427 qPrintable(QSystemError::windowsComString(hr)));
3428 break;
3429 }
3430 const UINT startSlot = cmd.args.setPushConstants.startSlot;
3431 const uint stages = cmd.args.setPushConstants.stages;
3432 // The uniform buffers of a stage that has a push constant block
3433 // start at the next register, so binding one buffer on its own
3434 // here never disturbs what bindShaderResources() sets.
3435 if (stages & (1u << uint(RBM_VERTEX)))
3436 context->VSSetConstantBuffers(startSlot, 1, &buf);
3437 if (stages & (1u << uint(RBM_HULL)))
3438 context->HSSetConstantBuffers(startSlot, 1, &buf);
3439 if (stages & (1u << uint(RBM_DOMAIN)))
3440 context->DSSetConstantBuffers(startSlot, 1, &buf);
3441 if (stages & (1u << uint(RBM_GEOMETRY)))
3442 context->GSSetConstantBuffers(startSlot, 1, &buf);
3443 if (stages & (1u << uint(RBM_FRAGMENT)))
3444 context->PSSetConstantBuffers(startSlot, 1, &buf);
3445 if (stages & (1u << uint(RBM_COMPUTE)))
3446 context->CSSetConstantBuffers(startSlot, 1, &buf);
3447 }
3448 break;
3449 case QD3D11CommandBuffer::Command::StencilRef:
3450 context->OMSetDepthStencilState(cmd.args.stencilRef.dsState, cmd.args.stencilRef.ref);
3451 break;
3453 memcpy(blendConstants, cmd.args.blendConstants.c, 4 * sizeof(float));
3454 context->OMSetBlendState(cmd.args.blendConstants.blendState, blendConstants, 0xffffffff);
3455 break;
3456 case QD3D11CommandBuffer::Command::Draw:
3457 if (cmd.args.draw.instanceCount == 1 && cmd.args.draw.firstInstance == 0)
3458 context->Draw(cmd.args.draw.vertexCount, cmd.args.draw.firstVertex);
3459 else
3460 context->DrawInstanced(cmd.args.draw.vertexCount, cmd.args.draw.instanceCount,
3461 cmd.args.draw.firstVertex, cmd.args.draw.firstInstance);
3462 break;
3463 case QD3D11CommandBuffer::Command::DrawIndexed:
3464 if (cmd.args.drawIndexed.instanceCount == 1 && cmd.args.drawIndexed.firstInstance == 0)
3465 context->DrawIndexed(cmd.args.drawIndexed.indexCount, cmd.args.drawIndexed.firstIndex,
3466 cmd.args.drawIndexed.vertexOffset);
3467 else
3468 context->DrawIndexedInstanced(cmd.args.drawIndexed.indexCount, cmd.args.drawIndexed.instanceCount,
3469 cmd.args.drawIndexed.firstIndex, cmd.args.drawIndexed.vertexOffset,
3470 cmd.args.drawIndexed.firstInstance);
3471 break;
3473 {
3474 UINT alignedByteOffsetForArgs = cmd.args.drawIndirect.indirectBufferOffset;
3475 const UINT stride = cmd.args.drawIndirect.stride;
3476 for (quint32 i = 0; i < cmd.args.drawIndirect.drawCount; ++i) {
3477 context->DrawInstancedIndirect(cmd.args.drawIndirect.indirectBuffer, alignedByteOffsetForArgs);
3478 alignedByteOffsetForArgs += stride;
3479 }
3480 }
3481 break;
3483 {
3484 UINT alignedByteOffsetForArgs = cmd.args.drawIndexedIndirect.indirectBufferOffset;
3485 const UINT stride = cmd.args.drawIndexedIndirect.stride;
3486 for (quint32 i = 0; i < cmd.args.drawIndexedIndirect.drawCount; ++i) {
3487 context->DrawIndexedInstancedIndirect(cmd.args.drawIndexedIndirect.indirectBuffer, alignedByteOffsetForArgs);
3488 alignedByteOffsetForArgs += stride;
3489 }
3490 }
3491 break;
3493 // dst can be null (e.g. device lost), but d3d11 dereferences it unconditionally
3494 if (cmd.args.updateSubRes.dst) {
3495 context->UpdateSubresource(cmd.args.updateSubRes.dst, cmd.args.updateSubRes.dstSubRes,
3496 cmd.args.updateSubRes.hasDstBox ? &cmd.args.updateSubRes.dstBox : nullptr,
3497 cmd.args.updateSubRes.src, cmd.args.updateSubRes.srcRowPitch, 0);
3498 }
3499 break;
3500 case QD3D11CommandBuffer::Command::CopySubRes:
3501 context->CopySubresourceRegion(cmd.args.copySubRes.dst, cmd.args.copySubRes.dstSubRes,
3502 cmd.args.copySubRes.dstX, cmd.args.copySubRes.dstY, cmd.args.copySubRes.dstZ,
3503 cmd.args.copySubRes.src, cmd.args.copySubRes.srcSubRes,
3504 cmd.args.copySubRes.hasSrcBox ? &cmd.args.copySubRes.srcBox : nullptr);
3505 break;
3506 case QD3D11CommandBuffer::Command::ClearUav:
3507 context->ClearUnorderedAccessViewUint(cmd.args.clearUav.uav, cmd.args.clearUav.values);
3508 break;
3509 case QD3D11CommandBuffer::Command::ResolveSubRes:
3510 context->ResolveSubresource(cmd.args.resolveSubRes.dst, cmd.args.resolveSubRes.dstSubRes,
3511 cmd.args.resolveSubRes.src, cmd.args.resolveSubRes.srcSubRes,
3512 cmd.args.resolveSubRes.format);
3513 break;
3514 case QD3D11CommandBuffer::Command::GenMip:
3515 context->GenerateMips(cmd.args.genMip.srv);
3516 break;
3517 case QD3D11CommandBuffer::Command::DebugMarkBegin:
3518 annotations->BeginEvent(reinterpret_cast<LPCWSTR>(QString::fromLatin1(cmd.args.debugMark.s).utf16()));
3519 break;
3520 case QD3D11CommandBuffer::Command::DebugMarkEnd:
3521 annotations->EndEvent();
3522 break;
3523 case QD3D11CommandBuffer::Command::DebugMarkMsg:
3524 annotations->SetMarker(reinterpret_cast<LPCWSTR>(QString::fromLatin1(cmd.args.debugMark.s).utf16()));
3525 break;
3526 case QD3D11CommandBuffer::Command::BindComputePipeline:
3527 context->CSSetShader(cmd.args.bindComputePipeline.cs, nullptr, 0);
3528 break;
3529 case QD3D11CommandBuffer::Command::Dispatch:
3530 context->Dispatch(cmd.args.dispatch.x, cmd.args.dispatch.y, cmd.args.dispatch.z);
3531 break;
3532 case QD3D11CommandBuffer::Command::DispatchIndirect:
3533 context->DispatchIndirect(cmd.args.dispatchIndirect.indirectBuffer,
3534 cmd.args.dispatchIndirect.indirectBufferOffset);
3535 break;
3536 default:
3537 break;
3538 }
3539 }
3540}
3541
3542QD3D11Buffer::QD3D11Buffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
3544{
3545}
3546
3551
3553{
3554 if (!buffer)
3555 return;
3556
3557 buffer->Release();
3558 buffer = nullptr;
3559
3560 delete[] dynBuf;
3561 dynBuf = nullptr;
3562
3563 for (auto it = uavs.begin(), end = uavs.end(); it != end; ++it)
3564 it.value()->Release();
3565 uavs.clear();
3566
3567 QRHI_RES_RHI(QRhiD3D11);
3568 if (rhiD)
3569 rhiD->unregisterResource(this);
3570}
3571
3572static inline uint toD3DBufferUsage(QRhiBuffer::UsageFlags usage)
3573{
3574 int u = 0;
3575 if (usage.testFlag(QRhiBuffer::VertexBuffer))
3576 u |= D3D11_BIND_VERTEX_BUFFER;
3577 if (usage.testFlag(QRhiBuffer::IndexBuffer))
3578 u |= D3D11_BIND_INDEX_BUFFER;
3579 if (usage.testFlag(QRhiBuffer::UniformBuffer))
3580 u |= D3D11_BIND_CONSTANT_BUFFER;
3581 if (usage.testFlag(QRhiBuffer::StorageBuffer))
3582 u |= D3D11_BIND_UNORDERED_ACCESS;
3583 return uint(u);
3584}
3585
3587{
3588 if (buffer)
3589 destroy();
3590
3591 if (m_usage.testFlag(QRhiBuffer::UniformBuffer) && m_type != Dynamic) {
3592 qWarning("UniformBuffer must always be combined with Dynamic on D3D11");
3593 return false;
3594 }
3595
3596 if (m_usage.testFlag(QRhiBuffer::StorageBuffer) && m_type == Dynamic) {
3597 qWarning("StorageBuffer cannot be combined with Dynamic");
3598 return false;
3599 }
3600
3601 if (m_usage.testFlag(QRhiBuffer::IndirectBuffer) && m_type == Dynamic) {
3602 qWarning("IndirectBuffer cannot be combined with Dynamic on D3D11");
3603 return false;
3604 }
3605
3606 const quint32 nonZeroSize = m_size <= 0 ? 256 : m_size;
3607 // D3D11 refuses to create a DRAWINDIRECT_ARGS buffer that could not hold
3608 // even the smallest indirect argument struct, the 3 uints of
3609 // DispatchIndirect. A count buffer for drawIndirectCount() is a single
3610 // quint32 and would hit this, so pad instead of failing.
3611 const quint32 minSize = m_usage.testFlag(QRhiBuffer::IndirectBuffer) ? 12u : 1u;
3612 const quint32 roundedSize = aligned(qMax(nonZeroSize, minSize),
3613 m_usage.testFlag(QRhiBuffer::UniformBuffer) ? 256u : 4u);
3614
3615 D3D11_BUFFER_DESC desc = {};
3616 desc.ByteWidth = roundedSize;
3617 desc.Usage = m_type == Dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
3618 desc.BindFlags = toD3DBufferUsage(m_usage);
3619 desc.CPUAccessFlags = m_type == Dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
3620 desc.MiscFlags = m_usage.testFlag(QRhiBuffer::StorageBuffer) ? D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS : 0;
3621 if (m_usage.testFlag(QRhiBuffer::IndirectBuffer))
3622 desc.MiscFlags |= D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS;
3623
3624 QRHI_RES_RHI(QRhiD3D11);
3625 HRESULT hr = rhiD->dev->CreateBuffer(&desc, nullptr, &buffer);
3626 if (FAILED(hr)) {
3627 qWarning("Failed to create buffer: %s",
3628 qPrintable(QSystemError::windowsComString(hr)));
3629 return false;
3630 }
3631
3632 if (m_type == Dynamic) {
3633 dynBuf = new char[nonZeroSize];
3635 }
3636
3637 if (!m_objectName.isEmpty())
3638 buffer->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData());
3639
3640 generation += 1;
3641 rhiD->registerResource(this);
3642 return true;
3643}
3644
3646{
3647 if (m_type == Dynamic) {
3648 QRHI_RES_RHI(QRhiD3D11);
3650 }
3651 return { { &buffer }, 1 };
3652}
3653
3655{
3656 // Shortcut the entire buffer update mechanism and allow the client to do
3657 // the host writes directly to the buffer. This will lead to unexpected
3658 // results when combined with QRhiResourceUpdateBatch-based updates for the
3659 // buffer, since dynBuf is left untouched and out of sync, but provides a
3660 // fast path for dynamic buffers that have all their content changed in
3661 // every frame.
3662 Q_ASSERT(m_type == Dynamic);
3663 D3D11_MAPPED_SUBRESOURCE mp;
3664 QRHI_RES_RHI(QRhiD3D11);
3665 HRESULT hr = rhiD->context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
3666 if (FAILED(hr)) {
3667 qWarning("Failed to map buffer: %s",
3668 qPrintable(QSystemError::windowsComString(hr)));
3669 return nullptr;
3670 }
3671 return static_cast<char *>(mp.pData);
3672}
3673
3675{
3676 QRHI_RES_RHI(QRhiD3D11);
3677 rhiD->context->Unmap(buffer, 0);
3678}
3679
3681{
3682 auto it = uavs.find(offset);
3683 if (it != uavs.end())
3684 return it.value();
3685
3686 // SPIRV-Cross generated HLSL uses RWByteAddressBuffer
3687 D3D11_UNORDERED_ACCESS_VIEW_DESC desc = {};
3688 desc.Format = DXGI_FORMAT_R32_TYPELESS;
3689 desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
3690 desc.Buffer.FirstElement = offset / 4u;
3691 desc.Buffer.NumElements = aligned(m_size - offset, 4u) / 4u;
3692 desc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW;
3693
3694 QRHI_RES_RHI(QRhiD3D11);
3695 ID3D11UnorderedAccessView *uav = nullptr;
3696 HRESULT hr = rhiD->dev->CreateUnorderedAccessView(buffer, &desc, &uav);
3697 if (FAILED(hr)) {
3698 qWarning("Failed to create UAV: %s",
3699 qPrintable(QSystemError::windowsComString(hr)));
3700 return nullptr;
3701 }
3702
3703 uavs[offset] = uav;
3704 return uav;
3705}
3706
3707// Not cached, because arbitrary ranges could make a cache grow without bounds.
3709{
3710 // A typed view, unlike a raw one, can start at any multiple of 4 bytes.
3711 // Typed UAVs need feature level 11_0, which Compute requires.
3712 D3D11_UNORDERED_ACCESS_VIEW_DESC desc = {};
3713 desc.Format = DXGI_FORMAT_R32_UINT;
3714 desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
3715 desc.Buffer.FirstElement = offset / 4u;
3716 desc.Buffer.NumElements = size / 4u;
3717
3718 QRHI_RES_RHI(QRhiD3D11);
3719 ID3D11UnorderedAccessView *uav = nullptr;
3720 HRESULT hr = rhiD->dev->CreateUnorderedAccessView(buffer, &desc, &uav);
3721 if (FAILED(hr)) {
3722 qWarning("Failed to create UAV: %s",
3723 qPrintable(QSystemError::windowsComString(hr)));
3724 return nullptr;
3725 }
3726
3727 return uav;
3728}
3729
3730QD3D11RenderBuffer::QD3D11RenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize,
3731 int sampleCount, QRhiRenderBuffer::Flags flags,
3732 QRhiTexture::Format backingFormatHint)
3734{
3735}
3736
3741
3743{
3744 if (!tex)
3745 return;
3746
3747 if (dsv) {
3748 dsv->Release();
3749 dsv = nullptr;
3750 }
3751
3752 if (rtv) {
3753 rtv->Release();
3754 rtv = nullptr;
3755 }
3756
3757 tex->Release();
3758 tex = nullptr;
3759
3760 QRHI_RES_RHI(QRhiD3D11);
3761 if (rhiD)
3762 rhiD->unregisterResource(this);
3763}
3764
3766{
3767 if (tex)
3768 destroy();
3769
3770 if (m_pixelSize.isEmpty())
3771 return false;
3772
3773 QRHI_RES_RHI(QRhiD3D11);
3774 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount);
3775
3776 D3D11_TEXTURE2D_DESC desc = {};
3777 desc.Width = UINT(m_pixelSize.width());
3778 desc.Height = UINT(m_pixelSize.height());
3779 desc.MipLevels = 1;
3780 desc.ArraySize = 1;
3781 desc.SampleDesc = sampleDesc;
3782 desc.Usage = D3D11_USAGE_DEFAULT;
3783
3784 if (m_type == Color) {
3785 dxgiFormat = m_backingFormatHint == QRhiTexture::UnknownFormat ? DXGI_FORMAT_R8G8B8A8_UNORM
3786 : toD3DTextureFormat(m_backingFormatHint, {});
3787 desc.Format = dxgiFormat;
3788 desc.BindFlags = D3D11_BIND_RENDER_TARGET;
3789 HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, &tex);
3790 if (FAILED(hr)) {
3791 qWarning("Failed to create color renderbuffer: %s",
3792 qPrintable(QSystemError::windowsComString(hr)));
3793 return false;
3794 }
3795 D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
3796 rtvDesc.Format = dxgiFormat;
3797 rtvDesc.ViewDimension = desc.SampleDesc.Count > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS
3798 : D3D11_RTV_DIMENSION_TEXTURE2D;
3799 hr = rhiD->dev->CreateRenderTargetView(tex, &rtvDesc, &rtv);
3800 if (FAILED(hr)) {
3801 qWarning("Failed to create rtv: %s",
3802 qPrintable(QSystemError::windowsComString(hr)));
3803 return false;
3804 }
3805 } else if (m_type == DepthStencil) {
3806 dxgiFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
3807 desc.Format = dxgiFormat;
3808 desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
3809 HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, &tex);
3810 if (FAILED(hr)) {
3811 qWarning("Failed to create depth-stencil buffer: %s",
3812 qPrintable(QSystemError::windowsComString(hr)));
3813 return false;
3814 }
3815 D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
3816 dsvDesc.Format = dxgiFormat;
3817 dsvDesc.ViewDimension = desc.SampleDesc.Count > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS
3818 : D3D11_DSV_DIMENSION_TEXTURE2D;
3819 hr = rhiD->dev->CreateDepthStencilView(tex, &dsvDesc, &dsv);
3820 if (FAILED(hr)) {
3821 qWarning("Failed to create dsv: %s",
3822 qPrintable(QSystemError::windowsComString(hr)));
3823 return false;
3824 }
3825 } else {
3826 return false;
3827 }
3828
3829 if (!m_objectName.isEmpty())
3830 tex->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData());
3831
3832 generation += 1;
3833 rhiD->registerResource(this);
3834 return true;
3835}
3836
3838{
3839 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
3840 return m_backingFormatHint;
3841 else
3842 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
3843}
3844
3845QD3D11Texture::QD3D11Texture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth,
3846 int arraySize, int sampleCount, Flags flags)
3848{
3849 for (int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i)
3850 perLevelViews[i] = nullptr;
3851}
3852
3857
3859{
3860 if (!tex && !tex3D && !tex1D)
3861 return;
3862
3863 if (srv) {
3864 srv->Release();
3865 srv = nullptr;
3866 }
3867
3868 for (int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i) {
3869 if (perLevelViews[i]) {
3870 perLevelViews[i]->Release();
3871 perLevelViews[i] = nullptr;
3872 }
3873 }
3874
3875 if (owns) {
3876 if (tex)
3877 tex->Release();
3878 if (tex3D)
3879 tex3D->Release();
3880 if (tex1D)
3881 tex1D->Release();
3882 }
3883
3884 tex = nullptr;
3885 tex3D = nullptr;
3886 tex1D = nullptr;
3887
3888 QRHI_RES_RHI(QRhiD3D11);
3889 if (rhiD)
3890 rhiD->unregisterResource(this);
3891}
3892
3893static inline DXGI_FORMAT toD3DDepthTextureSRVFormat(QRhiTexture::Format format)
3894{
3895 switch (format) {
3896 case QRhiTexture::Format::D16:
3897 return DXGI_FORMAT_R16_UNORM;
3898 case QRhiTexture::Format::D24:
3899 return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
3900 case QRhiTexture::Format::D24S8:
3901 return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
3902 case QRhiTexture::Format::D32F:
3903 return DXGI_FORMAT_R32_FLOAT;
3904 case QRhiTexture::Format::D32FS8:
3905 return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
3906 default:
3907 Q_UNREACHABLE();
3908 return DXGI_FORMAT_R32_FLOAT;
3909 }
3910}
3911
3912static inline DXGI_FORMAT toD3DDepthTextureDSVFormat(QRhiTexture::Format format)
3913{
3914 switch (format) {
3915 case QRhiTexture::Format::D16:
3916 return DXGI_FORMAT_D16_UNORM;
3917 case QRhiTexture::Format::D24:
3918 return DXGI_FORMAT_D24_UNORM_S8_UINT;
3919 case QRhiTexture::Format::D24S8:
3920 return DXGI_FORMAT_D24_UNORM_S8_UINT;
3921 case QRhiTexture::Format::D32F:
3922 return DXGI_FORMAT_D32_FLOAT;
3923 case QRhiTexture::Format::D32FS8:
3924 return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
3925 default:
3926 Q_UNREACHABLE();
3927 return DXGI_FORMAT_D32_FLOAT;
3928 }
3929}
3930
3931bool QD3D11Texture::prepareCreate(QSize *adjustedSize)
3932{
3933 if (tex || tex3D || tex1D)
3934 destroy();
3935
3936 QRHI_RES_RHI(QRhiD3D11);
3937 if (!rhiD->isTextureFormatSupported(m_format, m_flags))
3938 return false;
3939
3940 const bool isDepth = isDepthTextureFormat(m_format);
3941 const bool isCube = m_flags.testFlag(CubeMap);
3942 const bool is3D = m_flags.testFlag(ThreeDimensional);
3943 const bool isArray = m_flags.testFlag(TextureArray);
3944 const bool hasMipMaps = m_flags.testFlag(MipMapped);
3945 const bool is1D = m_flags.testFlag(OneDimensional);
3946
3947 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
3948 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
3949
3950 dxgiFormat = toD3DTextureFormat(m_format, m_flags);
3951 mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1);
3952 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount);
3953 if (sampleDesc.Count > 1) {
3954 if (isCube) {
3955 qWarning("Cubemap texture cannot be multisample");
3956 return false;
3957 }
3958 if (is3D) {
3959 qWarning("3D texture cannot be multisample");
3960 return false;
3961 }
3962 if (hasMipMaps) {
3963 qWarning("Multisample texture cannot have mipmaps");
3964 return false;
3965 }
3966 }
3967 if (isDepth && hasMipMaps) {
3968 qWarning("Depth texture cannot have mipmaps");
3969 return false;
3970 }
3971 if (isCube && is3D) {
3972 qWarning("Texture cannot be both cube and 3D");
3973 return false;
3974 }
3975 if (isArray && is3D) {
3976 qWarning("Texture cannot be both array and 3D");
3977 return false;
3978 }
3979 if (isCube && is1D) {
3980 qWarning("Texture cannot be both cube and 1D");
3981 return false;
3982 }
3983 if (is1D && is3D) {
3984 qWarning("Texture cannot be both 1D and 3D");
3985 return false;
3986 }
3987 if (m_depth > 1 && !is3D) {
3988 qWarning("Texture cannot have a depth of %d when it is not 3D", m_depth);
3989 return false;
3990 }
3991 if (m_arraySize > 0 && !isArray) {
3992 qWarning("Texture cannot have an array size of %d when it is not an array", m_arraySize);
3993 return false;
3994 }
3995 if (m_arraySize < 1 && isArray) {
3996 qWarning("Texture is an array but array size is %d", m_arraySize);
3997 return false;
3998 }
3999
4000 if (!rhiD->textureFormatInfo(m_format, size, nullptr, nullptr, nullptr))
4001 return false;
4002
4003 if (adjustedSize)
4004 *adjustedSize = size;
4005
4006 return true;
4007}
4008
4010{
4011 QRHI_RES_RHI(QRhiD3D11);
4012 const bool isDepth = isDepthTextureFormat(m_format);
4013 const bool isCube = m_flags.testFlag(CubeMap);
4014 const bool is3D = m_flags.testFlag(ThreeDimensional);
4015 const bool isArray = m_flags.testFlag(TextureArray);
4016 const bool is1D = m_flags.testFlag(OneDimensional);
4017
4018 D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
4019 srvDesc.Format = isDepth ? toD3DDepthTextureSRVFormat(m_format) : dxgiFormat;
4020 if (isCube) {
4021 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
4022 srvDesc.TextureCube.MipLevels = mipLevelCount;
4023 } else {
4024 if (is1D) {
4025 if (isArray) {
4026 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY;
4027 srvDesc.Texture1DArray.MipLevels = mipLevelCount;
4028 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
4029 srvDesc.Texture1DArray.FirstArraySlice = UINT(m_arrayRangeStart);
4030 srvDesc.Texture1DArray.ArraySize = UINT(m_arrayRangeLength);
4031 } else {
4032 srvDesc.Texture1DArray.FirstArraySlice = 0;
4033 srvDesc.Texture1DArray.ArraySize = UINT(qMax(0, m_arraySize));
4034 }
4035 } else {
4036 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D;
4037 srvDesc.Texture1D.MipLevels = mipLevelCount;
4038 }
4039 } else if (isArray) {
4040 if (sampleDesc.Count > 1) {
4041 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY;
4042 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
4043 srvDesc.Texture2DMSArray.FirstArraySlice = UINT(m_arrayRangeStart);
4044 srvDesc.Texture2DMSArray.ArraySize = UINT(m_arrayRangeLength);
4045 } else {
4046 srvDesc.Texture2DMSArray.FirstArraySlice = 0;
4047 srvDesc.Texture2DMSArray.ArraySize = UINT(qMax(0, m_arraySize));
4048 }
4049 } else {
4050 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
4051 srvDesc.Texture2DArray.MipLevels = mipLevelCount;
4052 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
4053 srvDesc.Texture2DArray.FirstArraySlice = UINT(m_arrayRangeStart);
4054 srvDesc.Texture2DArray.ArraySize = UINT(m_arrayRangeLength);
4055 } else {
4056 srvDesc.Texture2DArray.FirstArraySlice = 0;
4057 srvDesc.Texture2DArray.ArraySize = UINT(qMax(0, m_arraySize));
4058 }
4059 }
4060 } else {
4061 if (sampleDesc.Count > 1) {
4062 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS;
4063 } else if (is3D) {
4064 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
4065 srvDesc.Texture3D.MipLevels = mipLevelCount;
4066 } else {
4067 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
4068 srvDesc.Texture2D.MipLevels = mipLevelCount;
4069 }
4070 }
4071 }
4072
4073 HRESULT hr = rhiD->dev->CreateShaderResourceView(textureResource(), &srvDesc, &srv);
4074 if (FAILED(hr)) {
4075 qWarning("Failed to create srv: %s",
4076 qPrintable(QSystemError::windowsComString(hr)));
4077 return false;
4078 }
4079
4080 generation += 1;
4081 return true;
4082}
4083
4085{
4086 QSize size;
4087 if (!prepareCreate(&size))
4088 return false;
4089
4090 const bool isDepth = isDepthTextureFormat(m_format);
4091 const bool isCube = m_flags.testFlag(CubeMap);
4092 const bool is3D = m_flags.testFlag(ThreeDimensional);
4093 const bool isArray = m_flags.testFlag(TextureArray);
4094 const bool is1D = m_flags.testFlag(OneDimensional);
4095
4096 uint bindFlags = D3D11_BIND_SHADER_RESOURCE;
4097 uint miscFlags = isCube ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
4098 if (m_flags.testFlag(RenderTarget)) {
4099 if (isDepth)
4100 bindFlags |= D3D11_BIND_DEPTH_STENCIL;
4101 else
4102 bindFlags |= D3D11_BIND_RENDER_TARGET;
4103 }
4104 if (m_flags.testFlag(UsedWithGenerateMips)) {
4105 if (isDepth) {
4106 qWarning("Depth texture cannot have mipmaps generated");
4107 return false;
4108 }
4109 bindFlags |= D3D11_BIND_RENDER_TARGET;
4110 miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
4111 }
4112 if (m_flags.testFlag(UsedWithLoadStore))
4113 bindFlags |= D3D11_BIND_UNORDERED_ACCESS;
4114
4115 QRHI_RES_RHI(QRhiD3D11);
4116 if (is1D) {
4117 D3D11_TEXTURE1D_DESC desc = {};
4118 desc.Width = UINT(size.width());
4119 desc.MipLevels = mipLevelCount;
4120 desc.ArraySize = isArray ? UINT(qMax(0, m_arraySize)) : 1;
4121 desc.Format = dxgiFormat;
4122 desc.Usage = D3D11_USAGE_DEFAULT;
4123 desc.BindFlags = bindFlags;
4124 desc.MiscFlags = miscFlags;
4125
4126 HRESULT hr = rhiD->dev->CreateTexture1D(&desc, nullptr, &tex1D);
4127 if (FAILED(hr)) {
4128 qWarning("Failed to create 1D texture: %s",
4129 qPrintable(QSystemError::windowsComString(hr)));
4130 return false;
4131 }
4132 if (!m_objectName.isEmpty())
4133 tex1D->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()),
4134 m_objectName.constData());
4135 } else if (!is3D) {
4136 D3D11_TEXTURE2D_DESC desc = {};
4137 desc.Width = UINT(size.width());
4138 desc.Height = UINT(size.height());
4139 desc.MipLevels = mipLevelCount;
4140 desc.ArraySize = isCube ? 6 : (isArray ? UINT(qMax(0, m_arraySize)) : 1);
4141 desc.Format = dxgiFormat;
4142 desc.SampleDesc = sampleDesc;
4143 desc.Usage = D3D11_USAGE_DEFAULT;
4144 desc.BindFlags = bindFlags;
4145 desc.MiscFlags = miscFlags;
4146
4147 HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, &tex);
4148 if (FAILED(hr)) {
4149 qWarning("Failed to create 2D texture: %s",
4150 qPrintable(QSystemError::windowsComString(hr)));
4151 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
4152 rhiD->deviceLost = true;
4153 return false;
4154 }
4155 if (!m_objectName.isEmpty())
4156 tex->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData());
4157 } else {
4158 D3D11_TEXTURE3D_DESC desc = {};
4159 desc.Width = UINT(size.width());
4160 desc.Height = UINT(size.height());
4161 desc.Depth = UINT(qMax(1, m_depth));
4162 desc.MipLevels = mipLevelCount;
4163 desc.Format = dxgiFormat;
4164 desc.Usage = D3D11_USAGE_DEFAULT;
4165 desc.BindFlags = bindFlags;
4166 desc.MiscFlags = miscFlags;
4167
4168 HRESULT hr = rhiD->dev->CreateTexture3D(&desc, nullptr, &tex3D);
4169 if (FAILED(hr)) {
4170 qWarning("Failed to create 3D texture: %s",
4171 qPrintable(QSystemError::windowsComString(hr)));
4172 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
4173 rhiD->deviceLost = true;
4174 return false;
4175 }
4176 if (!m_objectName.isEmpty())
4177 tex3D->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData());
4178 }
4179
4180 if (!finishCreate())
4181 return false;
4182
4183 owns = true;
4184 rhiD->registerResource(this);
4185 return true;
4186}
4187
4188bool QD3D11Texture::createFrom(QRhiTexture::NativeTexture src)
4189{
4190 if (!src.object)
4191 return false;
4192
4193 if (!prepareCreate())
4194 return false;
4195
4196 if (m_flags.testFlag(ThreeDimensional))
4197 tex3D = reinterpret_cast<ID3D11Texture3D *>(src.object);
4198 else if (m_flags.testFlags(OneDimensional))
4199 tex1D = reinterpret_cast<ID3D11Texture1D *>(src.object);
4200 else
4201 tex = reinterpret_cast<ID3D11Texture2D *>(src.object);
4202
4203 if (!finishCreate())
4204 return false;
4205
4206 owns = false;
4207 QRHI_RES_RHI(QRhiD3D11);
4208 rhiD->registerResource(this);
4209 return true;
4210}
4211
4213{
4214 return { quint64(textureResource()), 0 };
4215}
4216
4218{
4219 if (perLevelViews[level])
4220 return perLevelViews[level];
4221
4222 const bool isCube = m_flags.testFlag(CubeMap);
4223 const bool isArray = m_flags.testFlag(TextureArray);
4224 const bool is3D = m_flags.testFlag(ThreeDimensional);
4225 const bool is1D = m_flags.testFlag(OneDimensional);
4226 D3D11_UNORDERED_ACCESS_VIEW_DESC desc = {};
4227 desc.Format = dxgiFormat;
4228 if (isCube) {
4229 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY;
4230 desc.Texture2DArray.MipSlice = UINT(level);
4231 desc.Texture2DArray.FirstArraySlice = 0;
4232 desc.Texture2DArray.ArraySize = 6;
4233 } else if (is1D && isArray) {
4234 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE1DARRAY;
4235 desc.Texture1DArray.MipSlice = UINT(level);
4236 desc.Texture1DArray.FirstArraySlice = 0;
4237 desc.Texture1DArray.ArraySize = UINT(qMax(0, m_arraySize));
4238 } else if (is1D) {
4239 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE1D;
4240 desc.Texture1D.MipSlice = UINT(level);
4241 } else if (isArray) {
4242 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY;
4243 desc.Texture2DArray.MipSlice = UINT(level);
4244 desc.Texture2DArray.FirstArraySlice = 0;
4245 desc.Texture2DArray.ArraySize = UINT(qMax(0, m_arraySize));
4246 } else if (is3D) {
4247 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE3D;
4248 desc.Texture3D.MipSlice = UINT(level);
4249 desc.Texture3D.WSize = UINT(m_depth);
4250 } else {
4251 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
4252 desc.Texture2D.MipSlice = UINT(level);
4253 }
4254
4255 QRHI_RES_RHI(QRhiD3D11);
4256 ID3D11UnorderedAccessView *uav = nullptr;
4257 HRESULT hr = rhiD->dev->CreateUnorderedAccessView(textureResource(), &desc, &uav);
4258 if (FAILED(hr)) {
4259 qWarning("Failed to create UAV: %s",
4260 qPrintable(QSystemError::windowsComString(hr)));
4261 return nullptr;
4262 }
4263
4264 perLevelViews[level] = uav;
4265 return uav;
4266}
4267
4268QD3D11Sampler::QD3D11Sampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode,
4269 AddressMode u, AddressMode v, AddressMode w)
4271{
4272}
4273
4278
4280{
4281 if (!samplerState)
4282 return;
4283
4284 samplerState->Release();
4285 samplerState = nullptr;
4286
4287 QRHI_RES_RHI(QRhiD3D11);
4288 if (rhiD)
4289 rhiD->unregisterResource(this);
4290}
4291
4292static inline D3D11_FILTER toD3DFilter(QRhiSampler::Filter minFilter, QRhiSampler::Filter magFilter, QRhiSampler::Filter mipFilter)
4293{
4294 if (minFilter == QRhiSampler::Nearest) {
4295 if (magFilter == QRhiSampler::Nearest) {
4296 if (mipFilter == QRhiSampler::Linear)
4297 return D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR;
4298 else
4299 return D3D11_FILTER_MIN_MAG_MIP_POINT;
4300 } else {
4301 if (mipFilter == QRhiSampler::Linear)
4302 return D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR;
4303 else
4304 return D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
4305 }
4306 } else {
4307 if (magFilter == QRhiSampler::Nearest) {
4308 if (mipFilter == QRhiSampler::Linear)
4309 return D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
4310 else
4311 return D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT;
4312 } else {
4313 if (mipFilter == QRhiSampler::Linear)
4314 return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
4315 else
4316 return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
4317 }
4318 }
4319
4320 Q_UNREACHABLE();
4321 return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
4322}
4323
4324static inline D3D11_TEXTURE_ADDRESS_MODE toD3DAddressMode(QRhiSampler::AddressMode m)
4325{
4326 switch (m) {
4327 case QRhiSampler::Repeat:
4328 return D3D11_TEXTURE_ADDRESS_WRAP;
4329 case QRhiSampler::ClampToEdge:
4330 return D3D11_TEXTURE_ADDRESS_CLAMP;
4331 case QRhiSampler::Mirror:
4332 return D3D11_TEXTURE_ADDRESS_MIRROR;
4333 default:
4334 Q_UNREACHABLE();
4335 return D3D11_TEXTURE_ADDRESS_CLAMP;
4336 }
4337}
4338
4339static inline D3D11_COMPARISON_FUNC toD3DTextureComparisonFunc(QRhiSampler::CompareOp op)
4340{
4341 switch (op) {
4342 case QRhiSampler::Never:
4343 return D3D11_COMPARISON_NEVER;
4344 case QRhiSampler::Less:
4345 return D3D11_COMPARISON_LESS;
4346 case QRhiSampler::Equal:
4347 return D3D11_COMPARISON_EQUAL;
4348 case QRhiSampler::LessOrEqual:
4349 return D3D11_COMPARISON_LESS_EQUAL;
4350 case QRhiSampler::Greater:
4351 return D3D11_COMPARISON_GREATER;
4352 case QRhiSampler::NotEqual:
4353 return D3D11_COMPARISON_NOT_EQUAL;
4354 case QRhiSampler::GreaterOrEqual:
4355 return D3D11_COMPARISON_GREATER_EQUAL;
4356 case QRhiSampler::Always:
4357 return D3D11_COMPARISON_ALWAYS;
4358 default:
4359 Q_UNREACHABLE();
4360 return D3D11_COMPARISON_NEVER;
4361 }
4362}
4363
4365{
4366 if (samplerState)
4367 destroy();
4368
4369 D3D11_SAMPLER_DESC desc = {};
4370 desc.Filter = toD3DFilter(m_minFilter, m_magFilter, m_mipmapMode);
4371 if (m_compareOp != Never)
4372 desc.Filter = D3D11_FILTER(desc.Filter | 0x80);
4373 desc.AddressU = toD3DAddressMode(m_addressU);
4374 desc.AddressV = toD3DAddressMode(m_addressV);
4375 desc.AddressW = toD3DAddressMode(m_addressW);
4376 desc.MaxAnisotropy = 1.0f;
4377 desc.ComparisonFunc = toD3DTextureComparisonFunc(m_compareOp);
4378 desc.MaxLOD = m_mipmapMode == None ? 0.0f : 1000.0f;
4379
4380 QRHI_RES_RHI(QRhiD3D11);
4381 HRESULT hr = rhiD->dev->CreateSamplerState(&desc, &samplerState);
4382 if (FAILED(hr)) {
4383 qWarning("Failed to create sampler state: %s",
4384 qPrintable(QSystemError::windowsComString(hr)));
4385 return false;
4386 }
4387
4388 generation += 1;
4389 rhiD->registerResource(this);
4390 return true;
4391}
4392
4393// dummy, no Vulkan-style RenderPass+Framebuffer concept here
4398
4403
4405{
4406 QRHI_RES_RHI(QRhiD3D11);
4407 if (rhiD)
4408 rhiD->unregisterResource(this);
4409}
4410
4411bool QD3D11RenderPassDescriptor::isCompatible(const QRhiRenderPassDescriptor *other) const
4412{
4413 Q_UNUSED(other);
4414 return true;
4415}
4416
4418{
4419 QD3D11RenderPassDescriptor *rpD = new QD3D11RenderPassDescriptor(m_rhi);
4420 QRHI_RES_RHI(QRhiD3D11);
4421 rhiD->registerResource(rpD, false);
4422 return rpD;
4423}
4424
4426{
4427 return {};
4428}
4429
4430QD3D11SwapChainRenderTarget::QD3D11SwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
4432 d(rhi)
4433{
4434}
4435
4440
4442{
4443 // nothing to do here
4444}
4445
4447{
4448 return d.pixelSize;
4449}
4450
4452{
4453 return d.dpr;
4454}
4455
4457{
4458 return d.sampleCount;
4459}
4460
4462 const QRhiTextureRenderTargetDescription &desc,
4463 Flags flags)
4465 d(rhi)
4466{
4467 for (int i = 0; i < QD3D11RenderTargetData::MAX_COLOR_ATTACHMENTS; ++i) {
4468 ownsRtv[i] = false;
4469 rtv[i] = nullptr;
4470 }
4471}
4472
4477
4479{
4480 if (!rtv[0] && !dsv)
4481 return;
4482
4483 if (dsv) {
4484 if (ownsDsv)
4485 dsv->Release();
4486 dsv = nullptr;
4487 }
4488
4489 for (int i = 0; i < QD3D11RenderTargetData::MAX_COLOR_ATTACHMENTS; ++i) {
4490 if (rtv[i]) {
4491 if (ownsRtv[i])
4492 rtv[i]->Release();
4493 rtv[i] = nullptr;
4494 }
4495 }
4496
4497 QRHI_RES_RHI(QRhiD3D11);
4498 if (rhiD)
4499 rhiD->unregisterResource(this);
4500}
4501
4503{
4504 QD3D11RenderPassDescriptor *rpD = new QD3D11RenderPassDescriptor(m_rhi);
4505 QRHI_RES_RHI(QRhiD3D11);
4506 rhiD->registerResource(rpD, false);
4507 return rpD;
4508}
4509
4511{
4512 if (rtv[0] || dsv)
4513 destroy();
4514
4515 Q_ASSERT(m_desc.colorAttachmentCount() > 0 || m_desc.depthTexture());
4516 Q_ASSERT(!m_desc.depthStencilBuffer() || !m_desc.depthTexture());
4517 const bool hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
4518
4519 QRHI_RES_RHI(QRhiD3D11);
4520
4521 int colorAttCount = 0;
4522 int attIndex = 0;
4523 for (auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
4524 colorAttCount += 1;
4525 const QRhiColorAttachment &colorAtt(*it);
4526 QRhiTexture *texture = colorAtt.texture();
4527 QRhiRenderBuffer *rb = colorAtt.renderBuffer();
4528 Q_ASSERT(texture || rb);
4529 if (texture) {
4530 QD3D11Texture *texD = QRHI_RES(QD3D11Texture, texture);
4531 D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
4532 rtvDesc.Format = toD3DTextureFormat(texD->format(), texD->flags());
4533 if (texD->flags().testFlag(QRhiTexture::CubeMap)) {
4534 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
4535 rtvDesc.Texture2DArray.MipSlice = UINT(colorAtt.level());
4536 rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAtt.layer());
4537 rtvDesc.Texture2DArray.ArraySize = 1;
4538 } else if (texD->flags().testFlag(QRhiTexture::OneDimensional)) {
4539 if (texD->flags().testFlag(QRhiTexture::TextureArray)) {
4540 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1DARRAY;
4541 rtvDesc.Texture1DArray.MipSlice = UINT(colorAtt.level());
4542 rtvDesc.Texture1DArray.FirstArraySlice = UINT(colorAtt.layer());
4543 rtvDesc.Texture1DArray.ArraySize = 1;
4544 } else {
4545 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D;
4546 rtvDesc.Texture1D.MipSlice = UINT(colorAtt.level());
4547 }
4548 } else if (texD->flags().testFlag(QRhiTexture::TextureArray)) {
4549 if (texD->sampleDesc.Count > 1) {
4550 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
4551 rtvDesc.Texture2DMSArray.FirstArraySlice = UINT(colorAtt.layer());
4552 rtvDesc.Texture2DMSArray.ArraySize = 1;
4553 } else {
4554 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
4555 rtvDesc.Texture2DArray.MipSlice = UINT(colorAtt.level());
4556 rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAtt.layer());
4557 rtvDesc.Texture2DArray.ArraySize = 1;
4558 }
4559 } else if (texD->flags().testFlag(QRhiTexture::ThreeDimensional)) {
4560 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
4561 rtvDesc.Texture3D.MipSlice = UINT(colorAtt.level());
4562 rtvDesc.Texture3D.FirstWSlice = UINT(colorAtt.layer());
4563 rtvDesc.Texture3D.WSize = 1;
4564 } else {
4565 if (texD->sampleDesc.Count > 1) {
4566 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
4567 } else {
4568 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
4569 rtvDesc.Texture2D.MipSlice = UINT(colorAtt.level());
4570 }
4571 }
4572 HRESULT hr = rhiD->dev->CreateRenderTargetView(texD->textureResource(), &rtvDesc, &rtv[attIndex]);
4573 if (FAILED(hr)) {
4574 qWarning("Failed to create rtv: %s",
4575 qPrintable(QSystemError::windowsComString(hr)));
4576 return false;
4577 }
4578 ownsRtv[attIndex] = true;
4579 if (attIndex == 0) {
4580 d.pixelSize = rhiD->q->sizeForMipLevel(colorAtt.level(), texD->pixelSize());
4581 d.sampleCount = int(texD->sampleDesc.Count);
4582 }
4583 } else if (rb) {
4584 QD3D11RenderBuffer *rbD = QRHI_RES(QD3D11RenderBuffer, rb);
4585 ownsRtv[attIndex] = false;
4586 rtv[attIndex] = rbD->rtv;
4587 if (attIndex == 0) {
4588 d.pixelSize = rbD->pixelSize();
4589 d.sampleCount = int(rbD->sampleDesc.Count);
4590 }
4591 }
4592 }
4593 d.dpr = 1;
4594
4595 if (hasDepthStencil) {
4596 if (m_desc.depthTexture()) {
4597 ownsDsv = true;
4598 QD3D11Texture *depthTexD = QRHI_RES(QD3D11Texture, m_desc.depthTexture());
4599 D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
4600 dsvDesc.Format = toD3DDepthTextureDSVFormat(depthTexD->format());
4601 const bool isMultisample = depthTexD->sampleDesc.Count > 1;
4602 if (depthTexD->flags().testFlag(QRhiTexture::TextureArray)) {
4603 if (isMultisample) {
4604 dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY;
4605 if (m_desc.depthLayer() >= 0) {
4606 dsvDesc.Texture2DMSArray.FirstArraySlice = UINT(m_desc.depthLayer());
4607 dsvDesc.Texture2DMSArray.ArraySize = 1;
4608 } else if (depthTexD->arrayRangeStart() >= 0 && depthTexD->arrayRangeLength() >= 0) {
4609 dsvDesc.Texture2DMSArray.FirstArraySlice = UINT(depthTexD->arrayRangeStart());
4610 dsvDesc.Texture2DMSArray.ArraySize = UINT(depthTexD->arrayRangeLength());
4611 } else {
4612 dsvDesc.Texture2DMSArray.FirstArraySlice = 0;
4613 dsvDesc.Texture2DMSArray.ArraySize = UINT(qMax(0, depthTexD->arraySize()));
4614 }
4615 } else {
4616 dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
4617 if (m_desc.depthLayer() >= 0) {
4618 dsvDesc.Texture2DArray.FirstArraySlice = UINT(m_desc.depthLayer());
4619 dsvDesc.Texture2DArray.ArraySize = 1;
4620 } else if (depthTexD->arrayRangeStart() >= 0 && depthTexD->arrayRangeLength() >= 0) {
4621 dsvDesc.Texture2DArray.FirstArraySlice = UINT(depthTexD->arrayRangeStart());
4622 dsvDesc.Texture2DArray.ArraySize = UINT(depthTexD->arrayRangeLength());
4623 } else {
4624 dsvDesc.Texture2DArray.FirstArraySlice = 0;
4625 dsvDesc.Texture2DArray.ArraySize = UINT(qMax(0, depthTexD->arraySize()));
4626 }
4627 }
4628 }
4629 else {
4630 dsvDesc.ViewDimension = isMultisample ? D3D11_DSV_DIMENSION_TEXTURE2DMS
4631 : D3D11_DSV_DIMENSION_TEXTURE2D;
4632 }
4633 HRESULT hr = rhiD->dev->CreateDepthStencilView(depthTexD->tex, &dsvDesc, &dsv);
4634 if (FAILED(hr)) {
4635 qWarning("Failed to create dsv: %s",
4636 qPrintable(QSystemError::windowsComString(hr)));
4637 return false;
4638 }
4639 if (colorAttCount == 0) {
4640 d.pixelSize = depthTexD->pixelSize();
4641 d.sampleCount = int(depthTexD->sampleDesc.Count);
4642 }
4643 } else {
4644 ownsDsv = false;
4645 QD3D11RenderBuffer *depthRbD = QRHI_RES(QD3D11RenderBuffer, m_desc.depthStencilBuffer());
4646 dsv = depthRbD->dsv;
4647 if (colorAttCount == 0) {
4648 d.pixelSize = m_desc.depthStencilBuffer()->pixelSize();
4649 d.sampleCount = int(depthRbD->sampleDesc.Count);
4650 }
4651 }
4652 } else {
4653 dsv = nullptr;
4654 }
4655
4656 d.views.setFrom(colorAttCount, rtv, dsv);
4657
4658 d.rp = QRHI_RES(QD3D11RenderPassDescriptor, m_renderPassDesc);
4659
4660 QRhiRenderTargetAttachmentTracker::updateResIdList<QD3D11Texture, QD3D11RenderBuffer>(m_desc, &d.currentResIdList);
4661
4662 rhiD->registerResource(this);
4663 return true;
4664}
4665
4667{
4668 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QD3D11Texture, QD3D11RenderBuffer>(m_desc, d.currentResIdList))
4669 const_cast<QD3D11TextureRenderTarget *>(this)->create();
4670
4671 return d.pixelSize;
4672}
4673
4675{
4676 return d.dpr;
4677}
4678
4680{
4681 return d.sampleCount;
4682}
4683
4688
4693
4695{
4696 sortedBindings.clear();
4697 boundResourceData.clear();
4698
4699 QRHI_RES_RHI(QRhiD3D11);
4700 if (rhiD)
4701 rhiD->unregisterResource(this);
4702}
4703
4705{
4706 if (!sortedBindings.isEmpty())
4707 destroy();
4708
4709 QRHI_RES_RHI(QRhiD3D11);
4710 if (!rhiD->sanityCheckShaderResourceBindings(this))
4711 return false;
4712
4713 rhiD->updateLayoutDesc(this);
4714
4715 std::copy(m_bindings.cbegin(), m_bindings.cend(), std::back_inserter(sortedBindings));
4716 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
4717
4718 boundResourceData.resize(sortedBindings.count());
4719
4720 for (BoundResourceData &bd : boundResourceData)
4721 bd = {};
4722
4723 hasDynamicOffset = false;
4724 for (const QRhiShaderResourceBinding &b : sortedBindings) {
4725 const QRhiShaderResourceBinding::Data *bd = QRhiImplementation::shaderResourceBindingData(b);
4726 if (bd->type() == QRhiShaderResourceBinding::UniformBuffer && bd->ubuf().hasDynamicOffset) {
4727 hasDynamicOffset = true;
4728 break;
4729 }
4730 }
4731
4732 generation += 1;
4733 rhiD->registerResource(this, false);
4734 return true;
4735}
4736
4738{
4739 sortedBindings.clear();
4740 std::copy(m_bindings.cbegin(), m_bindings.cend(), std::back_inserter(sortedBindings));
4741 if (!flags.testFlag(BindingsAreSorted))
4742 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
4743
4744 Q_ASSERT(boundResourceData.count() == sortedBindings.count());
4745 for (BoundResourceData &bd : boundResourceData)
4746 bd = {};
4747
4748 generation += 1;
4749}
4750
4753{
4754}
4755
4760
4761template<typename T>
4762inline void releasePipelineShader(T &s)
4763{
4764 if (s.shader) {
4765 s.shader->Release();
4766 s.shader = nullptr;
4767 }
4768 s.nativeResourceBindingMap.clear();
4769}
4770
4772{
4773 if (!dsState)
4774 return;
4775
4776 dsState->Release();
4777 dsState = nullptr;
4778
4779 if (blendState) {
4780 blendState->Release();
4781 blendState = nullptr;
4782 }
4783
4784 if (inputLayout) {
4785 inputLayout->Release();
4786 inputLayout = nullptr;
4787 }
4788
4789 if (rastState) {
4790 rastState->Release();
4791 rastState = nullptr;
4792 }
4793
4794 releasePipelineShader(vs);
4795 releasePipelineShader(hs);
4796 releasePipelineShader(ds);
4797 releasePipelineShader(gs);
4798 releasePipelineShader(fs);
4799
4800 pushConstants = {};
4801
4802 QRHI_RES_RHI(QRhiD3D11);
4803 if (rhiD)
4804 rhiD->unregisterResource(this);
4805}
4806
4807static inline D3D11_CULL_MODE toD3DCullMode(QRhiGraphicsPipeline::CullMode c)
4808{
4809 switch (c) {
4810 case QRhiGraphicsPipeline::None:
4811 return D3D11_CULL_NONE;
4812 case QRhiGraphicsPipeline::Front:
4813 return D3D11_CULL_FRONT;
4814 case QRhiGraphicsPipeline::Back:
4815 return D3D11_CULL_BACK;
4816 default:
4817 Q_UNREACHABLE();
4818 return D3D11_CULL_NONE;
4819 }
4820}
4821
4822static inline D3D11_FILL_MODE toD3DFillMode(QRhiGraphicsPipeline::PolygonMode mode)
4823{
4824 switch (mode) {
4825 case QRhiGraphicsPipeline::Fill:
4826 return D3D11_FILL_SOLID;
4827 case QRhiGraphicsPipeline::Line:
4828 return D3D11_FILL_WIREFRAME;
4829 default:
4830 Q_UNREACHABLE();
4831 return D3D11_FILL_SOLID;
4832 }
4833}
4834
4835static inline D3D11_COMPARISON_FUNC toD3DCompareOp(QRhiGraphicsPipeline::CompareOp op)
4836{
4837 switch (op) {
4838 case QRhiGraphicsPipeline::Never:
4839 return D3D11_COMPARISON_NEVER;
4840 case QRhiGraphicsPipeline::Less:
4841 return D3D11_COMPARISON_LESS;
4842 case QRhiGraphicsPipeline::Equal:
4843 return D3D11_COMPARISON_EQUAL;
4844 case QRhiGraphicsPipeline::LessOrEqual:
4845 return D3D11_COMPARISON_LESS_EQUAL;
4846 case QRhiGraphicsPipeline::Greater:
4847 return D3D11_COMPARISON_GREATER;
4848 case QRhiGraphicsPipeline::NotEqual:
4849 return D3D11_COMPARISON_NOT_EQUAL;
4850 case QRhiGraphicsPipeline::GreaterOrEqual:
4851 return D3D11_COMPARISON_GREATER_EQUAL;
4852 case QRhiGraphicsPipeline::Always:
4853 return D3D11_COMPARISON_ALWAYS;
4854 default:
4855 Q_UNREACHABLE();
4856 return D3D11_COMPARISON_ALWAYS;
4857 }
4858}
4859
4860static inline D3D11_STENCIL_OP toD3DStencilOp(QRhiGraphicsPipeline::StencilOp op)
4861{
4862 switch (op) {
4863 case QRhiGraphicsPipeline::StencilZero:
4864 return D3D11_STENCIL_OP_ZERO;
4865 case QRhiGraphicsPipeline::Keep:
4866 return D3D11_STENCIL_OP_KEEP;
4867 case QRhiGraphicsPipeline::Replace:
4868 return D3D11_STENCIL_OP_REPLACE;
4869 case QRhiGraphicsPipeline::IncrementAndClamp:
4870 return D3D11_STENCIL_OP_INCR_SAT;
4871 case QRhiGraphicsPipeline::DecrementAndClamp:
4872 return D3D11_STENCIL_OP_DECR_SAT;
4873 case QRhiGraphicsPipeline::Invert:
4874 return D3D11_STENCIL_OP_INVERT;
4875 case QRhiGraphicsPipeline::IncrementAndWrap:
4876 return D3D11_STENCIL_OP_INCR;
4877 case QRhiGraphicsPipeline::DecrementAndWrap:
4878 return D3D11_STENCIL_OP_DECR;
4879 default:
4880 Q_UNREACHABLE();
4881 return D3D11_STENCIL_OP_KEEP;
4882 }
4883}
4884
4885static inline DXGI_FORMAT toD3DAttributeFormat(QRhiVertexInputAttribute::Format format)
4886{
4887 switch (format) {
4888 case QRhiVertexInputAttribute::Float4:
4889 return DXGI_FORMAT_R32G32B32A32_FLOAT;
4890 case QRhiVertexInputAttribute::Float3:
4891 return DXGI_FORMAT_R32G32B32_FLOAT;
4892 case QRhiVertexInputAttribute::Float2:
4893 return DXGI_FORMAT_R32G32_FLOAT;
4894 case QRhiVertexInputAttribute::Float:
4895 return DXGI_FORMAT_R32_FLOAT;
4896 case QRhiVertexInputAttribute::UNormByte4:
4897 return DXGI_FORMAT_R8G8B8A8_UNORM;
4898 case QRhiVertexInputAttribute::UNormByte2:
4899 return DXGI_FORMAT_R8G8_UNORM;
4900 case QRhiVertexInputAttribute::UNormByte:
4901 return DXGI_FORMAT_R8_UNORM;
4902 case QRhiVertexInputAttribute::UInt4:
4903 return DXGI_FORMAT_R32G32B32A32_UINT;
4904 case QRhiVertexInputAttribute::UInt3:
4905 return DXGI_FORMAT_R32G32B32_UINT;
4906 case QRhiVertexInputAttribute::UInt2:
4907 return DXGI_FORMAT_R32G32_UINT;
4908 case QRhiVertexInputAttribute::UInt:
4909 return DXGI_FORMAT_R32_UINT;
4910 case QRhiVertexInputAttribute::SInt4:
4911 return DXGI_FORMAT_R32G32B32A32_SINT;
4912 case QRhiVertexInputAttribute::SInt3:
4913 return DXGI_FORMAT_R32G32B32_SINT;
4914 case QRhiVertexInputAttribute::SInt2:
4915 return DXGI_FORMAT_R32G32_SINT;
4916 case QRhiVertexInputAttribute::SInt:
4917 return DXGI_FORMAT_R32_SINT;
4918 case QRhiVertexInputAttribute::Half4:
4919 // Note: D3D does not support half3. Pass through half3 as half4.
4920 case QRhiVertexInputAttribute::Half3:
4921 return DXGI_FORMAT_R16G16B16A16_FLOAT;
4922 case QRhiVertexInputAttribute::Half2:
4923 return DXGI_FORMAT_R16G16_FLOAT;
4924 case QRhiVertexInputAttribute::Half:
4925 return DXGI_FORMAT_R16_FLOAT;
4926 case QRhiVertexInputAttribute::UShort4:
4927 // Note: D3D does not support UShort3. Pass through UShort3 as UShort4.
4928 case QRhiVertexInputAttribute::UShort3:
4929 return DXGI_FORMAT_R16G16B16A16_UINT;
4930 case QRhiVertexInputAttribute::UShort2:
4931 return DXGI_FORMAT_R16G16_UINT;
4932 case QRhiVertexInputAttribute::UShort:
4933 return DXGI_FORMAT_R16_UINT;
4934 case QRhiVertexInputAttribute::SShort4:
4935 // Note: D3D does not support SShort3. Pass through SShort3 as SShort4.
4936 case QRhiVertexInputAttribute::SShort3:
4937 return DXGI_FORMAT_R16G16B16A16_SINT;
4938 case QRhiVertexInputAttribute::SShort2:
4939 return DXGI_FORMAT_R16G16_SINT;
4940 case QRhiVertexInputAttribute::SShort:
4941 return DXGI_FORMAT_R16_SINT;
4942 default:
4943 Q_UNREACHABLE();
4944 return DXGI_FORMAT_R32G32B32A32_FLOAT;
4945 }
4946}
4947
4948static inline D3D11_PRIMITIVE_TOPOLOGY toD3DTopology(QRhiGraphicsPipeline::Topology t, int patchControlPointCount)
4949{
4950 switch (t) {
4951 case QRhiGraphicsPipeline::Triangles:
4952 return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
4953 case QRhiGraphicsPipeline::TriangleStrip:
4954 return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
4955 case QRhiGraphicsPipeline::Lines:
4956 return D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
4957 case QRhiGraphicsPipeline::LineStrip:
4958 return D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
4959 case QRhiGraphicsPipeline::Points:
4960 return D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
4961 case QRhiGraphicsPipeline::Patches:
4962 Q_ASSERT(patchControlPointCount >= 1 && patchControlPointCount <= 32);
4963 return D3D11_PRIMITIVE_TOPOLOGY(D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST + (patchControlPointCount - 1));
4964 default:
4965 Q_UNREACHABLE();
4966 return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
4967 }
4968}
4969
4970static inline UINT8 toD3DColorWriteMask(QRhiGraphicsPipeline::ColorMask c)
4971{
4972 UINT8 f = 0;
4973 if (c.testFlag(QRhiGraphicsPipeline::R))
4974 f |= D3D11_COLOR_WRITE_ENABLE_RED;
4975 if (c.testFlag(QRhiGraphicsPipeline::G))
4976 f |= D3D11_COLOR_WRITE_ENABLE_GREEN;
4977 if (c.testFlag(QRhiGraphicsPipeline::B))
4978 f |= D3D11_COLOR_WRITE_ENABLE_BLUE;
4979 if (c.testFlag(QRhiGraphicsPipeline::A))
4980 f |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
4981 return f;
4982}
4983
4984static inline D3D11_BLEND toD3DBlendFactor(QRhiGraphicsPipeline::BlendFactor f, bool rgb)
4985{
4986 // SrcBlendAlpha and DstBlendAlpha do not accept *_COLOR. With other APIs
4987 // this is handled internally (so that e.g. VK_BLEND_FACTOR_SRC_COLOR is
4988 // accepted and is in effect equivalent to VK_BLEND_FACTOR_SRC_ALPHA when
4989 // set as an alpha src/dest factor), but for D3D we have to take care of it
4990 // ourselves. Hence the rgb argument.
4991
4992 switch (f) {
4993 case QRhiGraphicsPipeline::Zero:
4994 return D3D11_BLEND_ZERO;
4995 case QRhiGraphicsPipeline::One:
4996 return D3D11_BLEND_ONE;
4997 case QRhiGraphicsPipeline::SrcColor:
4998 return rgb ? D3D11_BLEND_SRC_COLOR : D3D11_BLEND_SRC_ALPHA;
4999 case QRhiGraphicsPipeline::OneMinusSrcColor:
5000 return rgb ? D3D11_BLEND_INV_SRC_COLOR : D3D11_BLEND_INV_SRC_ALPHA;
5001 case QRhiGraphicsPipeline::DstColor:
5002 return rgb ? D3D11_BLEND_DEST_COLOR : D3D11_BLEND_DEST_ALPHA;
5003 case QRhiGraphicsPipeline::OneMinusDstColor:
5004 return rgb ? D3D11_BLEND_INV_DEST_COLOR : D3D11_BLEND_INV_DEST_ALPHA;
5005 case QRhiGraphicsPipeline::SrcAlpha:
5006 return D3D11_BLEND_SRC_ALPHA;
5007 case QRhiGraphicsPipeline::OneMinusSrcAlpha:
5008 return D3D11_BLEND_INV_SRC_ALPHA;
5009 case QRhiGraphicsPipeline::DstAlpha:
5010 return D3D11_BLEND_DEST_ALPHA;
5011 case QRhiGraphicsPipeline::OneMinusDstAlpha:
5012 return D3D11_BLEND_INV_DEST_ALPHA;
5013 case QRhiGraphicsPipeline::ConstantColor:
5014 case QRhiGraphicsPipeline::ConstantAlpha:
5015 return D3D11_BLEND_BLEND_FACTOR;
5016 case QRhiGraphicsPipeline::OneMinusConstantColor:
5017 case QRhiGraphicsPipeline::OneMinusConstantAlpha:
5018 return D3D11_BLEND_INV_BLEND_FACTOR;
5019 case QRhiGraphicsPipeline::SrcAlphaSaturate:
5020 return D3D11_BLEND_SRC_ALPHA_SAT;
5021 case QRhiGraphicsPipeline::Src1Color:
5022 return rgb ? D3D11_BLEND_SRC1_COLOR : D3D11_BLEND_SRC1_ALPHA;
5023 case QRhiGraphicsPipeline::OneMinusSrc1Color:
5024 return rgb ? D3D11_BLEND_INV_SRC1_COLOR : D3D11_BLEND_INV_SRC1_ALPHA;
5025 case QRhiGraphicsPipeline::Src1Alpha:
5026 return D3D11_BLEND_SRC1_ALPHA;
5027 case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
5028 return D3D11_BLEND_INV_SRC1_ALPHA;
5029 default:
5030 Q_UNREACHABLE();
5031 return D3D11_BLEND_ZERO;
5032 }
5033}
5034
5035static inline D3D11_BLEND_OP toD3DBlendOp(QRhiGraphicsPipeline::BlendOp op)
5036{
5037 switch (op) {
5038 case QRhiGraphicsPipeline::Add:
5039 return D3D11_BLEND_OP_ADD;
5040 case QRhiGraphicsPipeline::Subtract:
5041 return D3D11_BLEND_OP_SUBTRACT;
5042 case QRhiGraphicsPipeline::ReverseSubtract:
5043 return D3D11_BLEND_OP_REV_SUBTRACT;
5044 case QRhiGraphicsPipeline::Min:
5045 return D3D11_BLEND_OP_MIN;
5046 case QRhiGraphicsPipeline::Max:
5047 return D3D11_BLEND_OP_MAX;
5048 default:
5049 Q_UNREACHABLE();
5050 return D3D11_BLEND_OP_ADD;
5051 }
5052}
5053
5054static inline QByteArray sourceHash(const QByteArray &source)
5055{
5056 // taken from the GL backend, use the same mechanism to get a key
5057 QCryptographicHash keyBuilder(QCryptographicHash::Sha1);
5058 keyBuilder.addData(source);
5059 return keyBuilder.result().toHex();
5060}
5061
5062QByteArray QRhiD3D11::compileHlslShaderSource(const QShader &shader, QShader::Variant shaderVariant, uint flags,
5063 QString *error, QShaderKey *usedShaderKey)
5064{
5065 QShaderKey key = { QShader::DxbcShader, 50, shaderVariant };
5066 QShaderCode dxbc = shader.shader(key);
5067 if (!dxbc.shader().isEmpty()) {
5068 if (usedShaderKey)
5069 *usedShaderKey = key;
5070 return dxbc.shader();
5071 }
5072
5073 key = { QShader::HlslShader, 50, shaderVariant };
5074 QShaderCode hlslSource = shader.shader(key);
5075 if (hlslSource.shader().isEmpty()) {
5076 qWarning() << "No HLSL (shader model 5.0) code found in baked shader" << shader;
5077 return QByteArray();
5078 }
5079
5080 if (usedShaderKey)
5081 *usedShaderKey = key;
5082
5083 const char *target;
5084 switch (shader.stage()) {
5085 case QShader::VertexStage:
5086 target = "vs_5_0";
5087 break;
5088 case QShader::TessellationControlStage:
5089 target = "hs_5_0";
5090 break;
5091 case QShader::TessellationEvaluationStage:
5092 target = "ds_5_0";
5093 break;
5094 case QShader::GeometryStage:
5095 target = "gs_5_0";
5096 break;
5097 case QShader::FragmentStage:
5098 target = "ps_5_0";
5099 break;
5100 case QShader::ComputeStage:
5101 target = "cs_5_0";
5102 break;
5103 default:
5104 qWarning("compileHlslShaderSource: Unknown SM 5.0 stage (%d)", int(shader.stage()));
5105 return QByteArray();
5106 }
5107
5108 BytecodeCacheKey cacheKey;
5109 if (rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave)) {
5110 cacheKey.sourceHash = sourceHash(hlslSource.shader());
5111 cacheKey.target = target;
5112 cacheKey.entryPoint = hlslSource.entryPoint();
5113 cacheKey.compileFlags = flags;
5114 auto cacheIt = m_bytecodeCache.data.constFind(cacheKey);
5115 if (cacheIt != m_bytecodeCache.data.constEnd())
5116 return cacheIt.value();
5117 }
5118
5119 static const pD3DCompile d3dCompile = QRhiD3D::resolveD3DCompile();
5120 if (d3dCompile == nullptr) {
5121 qWarning("Unable to resolve function D3DCompile()");
5122 return QByteArray();
5123 }
5124
5125 ID3DBlob *bytecode = nullptr;
5126 ID3DBlob *errors = nullptr;
5127 HRESULT hr = d3dCompile(hlslSource.shader().constData(), SIZE_T(hlslSource.shader().size()),
5128 nullptr, nullptr, nullptr,
5129 hlslSource.entryPoint().constData(), target, flags, 0, &bytecode, &errors);
5130 if (FAILED(hr) || !bytecode) {
5131 qWarning("HLSL shader compilation failed: 0x%x", uint(hr));
5132 if (errors) {
5133 *error = QString::fromUtf8(static_cast<const char *>(errors->GetBufferPointer()),
5134 int(errors->GetBufferSize()));
5135 errors->Release();
5136 }
5137 return QByteArray();
5138 }
5139
5140 QByteArray result;
5141 result.resize(int(bytecode->GetBufferSize()));
5142 memcpy(result.data(), bytecode->GetBufferPointer(), size_t(result.size()));
5143 bytecode->Release();
5144
5145 if (rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
5146 m_bytecodeCache.insertWithCapacityLimit(cacheKey, result);
5147
5148 return result;
5149}
5150
5152{
5153 if (dsState)
5154 destroy();
5155
5156 QRHI_RES_RHI(QRhiD3D11);
5157 rhiD->pipelineCreationStart();
5158 if (!rhiD->sanityCheckGraphicsPipeline(this))
5159 return false;
5160
5161 D3D11_RASTERIZER_DESC rastDesc = {};
5162 rastDesc.FillMode = toD3DFillMode(m_polygonMode);
5163 rastDesc.CullMode = toD3DCullMode(m_cullMode);
5164 rastDesc.FrontCounterClockwise = m_frontFace == CCW;
5165 rastDesc.DepthBias = m_depthBias;
5166 rastDesc.SlopeScaledDepthBias = m_slopeScaledDepthBias;
5167 rastDesc.DepthClipEnable = m_depthClamp ? FALSE : TRUE;
5168 rastDesc.ScissorEnable = m_flags.testFlag(UsesScissor);
5169 rastDesc.MultisampleEnable = rhiD->effectiveSampleDesc(m_sampleCount).Count > 1;
5170 HRESULT hr = rhiD->dev->CreateRasterizerState(&rastDesc, &rastState);
5171 if (FAILED(hr)) {
5172 qWarning("Failed to create rasterizer state: %s",
5173 qPrintable(QSystemError::windowsComString(hr)));
5174 return false;
5175 }
5176
5177 D3D11_DEPTH_STENCIL_DESC dsDesc = {};
5178 dsDesc.DepthEnable = m_depthTest;
5179 dsDesc.DepthWriteMask = m_depthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
5180 dsDesc.DepthFunc = toD3DCompareOp(m_depthOp);
5181 dsDesc.StencilEnable = m_stencilTest;
5182 if (m_stencilTest) {
5183 dsDesc.StencilReadMask = UINT8(m_stencilReadMask);
5184 dsDesc.StencilWriteMask = UINT8(m_stencilWriteMask);
5185 dsDesc.FrontFace.StencilFailOp = toD3DStencilOp(m_stencilFront.failOp);
5186 dsDesc.FrontFace.StencilDepthFailOp = toD3DStencilOp(m_stencilFront.depthFailOp);
5187 dsDesc.FrontFace.StencilPassOp = toD3DStencilOp(m_stencilFront.passOp);
5188 dsDesc.FrontFace.StencilFunc = toD3DCompareOp(m_stencilFront.compareOp);
5189 dsDesc.BackFace.StencilFailOp = toD3DStencilOp(m_stencilBack.failOp);
5190 dsDesc.BackFace.StencilDepthFailOp = toD3DStencilOp(m_stencilBack.depthFailOp);
5191 dsDesc.BackFace.StencilPassOp = toD3DStencilOp(m_stencilBack.passOp);
5192 dsDesc.BackFace.StencilFunc = toD3DCompareOp(m_stencilBack.compareOp);
5193 }
5194 hr = rhiD->dev->CreateDepthStencilState(&dsDesc, &dsState);
5195 if (FAILED(hr)) {
5196 qWarning("Failed to create depth-stencil state: %s",
5197 qPrintable(QSystemError::windowsComString(hr)));
5198 return false;
5199 }
5200
5201 D3D11_BLEND_DESC blendDesc = {};
5202 blendDesc.IndependentBlendEnable = m_targetBlends.count() > 1;
5203 for (int i = 0, ie = m_targetBlends.count(); i != ie; ++i) {
5204 const QRhiGraphicsPipeline::TargetBlend &b(m_targetBlends[i]);
5205 D3D11_RENDER_TARGET_BLEND_DESC blend = {};
5206 blend.BlendEnable = b.enable;
5207 blend.SrcBlend = toD3DBlendFactor(b.srcColor, true);
5208 blend.DestBlend = toD3DBlendFactor(b.dstColor, true);
5209 blend.BlendOp = toD3DBlendOp(b.opColor);
5210 blend.SrcBlendAlpha = toD3DBlendFactor(b.srcAlpha, false);
5211 blend.DestBlendAlpha = toD3DBlendFactor(b.dstAlpha, false);
5212 blend.BlendOpAlpha = toD3DBlendOp(b.opAlpha);
5213 blend.RenderTargetWriteMask = toD3DColorWriteMask(b.colorWrite);
5214 blendDesc.RenderTarget[i] = blend;
5215 }
5216 if (m_targetBlends.isEmpty()) {
5217 D3D11_RENDER_TARGET_BLEND_DESC blend = {};
5218 blend.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
5219 blendDesc.RenderTarget[0] = blend;
5220 }
5221 hr = rhiD->dev->CreateBlendState(&blendDesc, &blendState);
5222 if (FAILED(hr)) {
5223 qWarning("Failed to create blend state: %s",
5224 qPrintable(QSystemError::windowsComString(hr)));
5225 return false;
5226 }
5227
5228 QByteArray vsByteCode;
5229 for (const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
5230 int stagePushConstantRegister = -1;
5231 quint32 stagePushConstantSize = 0;
5232 auto cacheIt = rhiD->m_shaderCache.constFind(shaderStage);
5233 if (cacheIt != rhiD->m_shaderCache.constEnd()) {
5234 stagePushConstantRegister = cacheIt->pushConstantRegister;
5235 stagePushConstantSize = cacheIt->pushConstantSize;
5236 switch (shaderStage.type()) {
5237 case QRhiShaderStage::Vertex:
5238 vs.shader = static_cast<ID3D11VertexShader *>(cacheIt->s);
5239 vs.shader->AddRef();
5240 vsByteCode = cacheIt->bytecode;
5241 vs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5242 break;
5243 case QRhiShaderStage::TessellationControl:
5244 hs.shader = static_cast<ID3D11HullShader *>(cacheIt->s);
5245 hs.shader->AddRef();
5246 hs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5247 break;
5248 case QRhiShaderStage::TessellationEvaluation:
5249 ds.shader = static_cast<ID3D11DomainShader *>(cacheIt->s);
5250 ds.shader->AddRef();
5251 ds.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5252 break;
5253 case QRhiShaderStage::Geometry:
5254 gs.shader = static_cast<ID3D11GeometryShader *>(cacheIt->s);
5255 gs.shader->AddRef();
5256 gs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5257 break;
5258 case QRhiShaderStage::Fragment:
5259 fs.shader = static_cast<ID3D11PixelShader *>(cacheIt->s);
5260 fs.shader->AddRef();
5261 fs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5262 break;
5263 default:
5264 break;
5265 }
5266 } else {
5267 QString error;
5268 QShaderKey shaderKey;
5269 UINT compileFlags = 0;
5270 if (m_flags.testFlag(CompileShadersWithDebugInfo))
5271 compileFlags |= D3DCOMPILE_DEBUG;
5272
5273 const QByteArray bytecode = rhiD->compileHlslShaderSource(shaderStage.shader(), shaderStage.shaderVariant(), compileFlags,
5274 &error, &shaderKey);
5275 if (bytecode.isEmpty()) {
5276 qWarning("HLSL shader compilation failed: %s", qPrintable(error));
5277 return false;
5278 }
5279
5280 if (rhiD->m_shaderCache.count() >= QRhiD3D11::MAX_SHADER_CACHE_ENTRIES) {
5281 // Use the simplest strategy: too many cached shaders -> drop them all.
5282 rhiD->clearShaderCache();
5283 }
5284
5285 getPushConstantInfo(shaderStage.shader(), shaderKey, &stagePushConstantRegister, &stagePushConstantSize);
5286
5287 switch (shaderStage.type()) {
5288 case QRhiShaderStage::Vertex:
5289 hr = rhiD->dev->CreateVertexShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &vs.shader);
5290 if (FAILED(hr)) {
5291 qWarning("Failed to create vertex shader: %s",
5292 qPrintable(QSystemError::windowsComString(hr)));
5293 return false;
5294 }
5295 vsByteCode = bytecode;
5296 vs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5297 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(vs.shader, bytecode, vs.nativeResourceBindingMap,
5298 stagePushConstantRegister, stagePushConstantSize));
5299 vs.shader->AddRef();
5300 break;
5301 case QRhiShaderStage::TessellationControl:
5302 hr = rhiD->dev->CreateHullShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &hs.shader);
5303 if (FAILED(hr)) {
5304 qWarning("Failed to create hull shader: %s",
5305 qPrintable(QSystemError::windowsComString(hr)));
5306 return false;
5307 }
5308 hs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5309 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(hs.shader, bytecode, hs.nativeResourceBindingMap,
5310 stagePushConstantRegister, stagePushConstantSize));
5311 hs.shader->AddRef();
5312 break;
5313 case QRhiShaderStage::TessellationEvaluation:
5314 hr = rhiD->dev->CreateDomainShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &ds.shader);
5315 if (FAILED(hr)) {
5316 qWarning("Failed to create domain shader: %s",
5317 qPrintable(QSystemError::windowsComString(hr)));
5318 return false;
5319 }
5320 ds.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5321 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(ds.shader, bytecode, ds.nativeResourceBindingMap,
5322 stagePushConstantRegister, stagePushConstantSize));
5323 ds.shader->AddRef();
5324 break;
5325 case QRhiShaderStage::Geometry:
5326 hr = rhiD->dev->CreateGeometryShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &gs.shader);
5327 if (FAILED(hr)) {
5328 qWarning("Failed to create geometry shader: %s",
5329 qPrintable(QSystemError::windowsComString(hr)));
5330 return false;
5331 }
5332 gs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5333 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(gs.shader, bytecode, gs.nativeResourceBindingMap,
5334 stagePushConstantRegister, stagePushConstantSize));
5335 gs.shader->AddRef();
5336 break;
5337 case QRhiShaderStage::Fragment:
5338 hr = rhiD->dev->CreatePixelShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &fs.shader);
5339 if (FAILED(hr)) {
5340 qWarning("Failed to create pixel shader: %s",
5341 qPrintable(QSystemError::windowsComString(hr)));
5342 return false;
5343 }
5344 fs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5345 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(fs.shader, bytecode, fs.nativeResourceBindingMap,
5346 stagePushConstantRegister, stagePushConstantSize));
5347 fs.shader->AddRef();
5348 break;
5349 default:
5350 break;
5351 }
5352 }
5353
5354 if (stagePushConstantRegister >= 0 && stagePushConstantSize) {
5355 const int stageIndex = rbmStageIndex(shaderStage.type());
5356 if (stageIndex >= 0) {
5357 pushConstants.reg = stagePushConstantRegister;
5358 pushConstants.size = qMax(pushConstants.size, stagePushConstantSize);
5359 pushConstants.stages |= 1u << uint(stageIndex);
5360 }
5361 }
5362 }
5363
5364 d3dTopology = toD3DTopology(m_topology, m_patchControlPointCount);
5365
5366 if (!vsByteCode.isEmpty()) {
5367 QByteArrayList matrixSliceSemantics;
5368 QVarLengthArray<D3D11_INPUT_ELEMENT_DESC, 4> inputDescs;
5369 for (auto it = m_vertexInputLayout.cbeginAttributes(), itEnd = m_vertexInputLayout.cendAttributes();
5370 it != itEnd; ++it)
5371 {
5372 D3D11_INPUT_ELEMENT_DESC desc = {};
5373 // The output from SPIRV-Cross uses TEXCOORD<location> as the
5374 // semantic, except for matrices that are unrolled into consecutive
5375 // vec2/3/4s attributes and need TEXCOORD<location>_ as
5376 // SemanticName and row/column index as SemanticIndex.
5377 const int matrixSlice = it->matrixSlice();
5378 if (matrixSlice < 0) {
5379 desc.SemanticName = "TEXCOORD";
5380 desc.SemanticIndex = UINT(it->location());
5381 } else {
5382 QByteArray sem;
5383 sem.resize(16);
5384 std::snprintf(sem.data(), sem.size(), "TEXCOORD%d_", it->location() - matrixSlice);
5385 matrixSliceSemantics.append(sem);
5386 desc.SemanticName = matrixSliceSemantics.last().constData();
5387 desc.SemanticIndex = UINT(matrixSlice);
5388 }
5389 desc.Format = toD3DAttributeFormat(it->format());
5390 desc.InputSlot = UINT(it->binding());
5391 desc.AlignedByteOffset = it->offset();
5392 const QRhiVertexInputBinding *inputBinding = m_vertexInputLayout.bindingAt(it->binding());
5393 if (inputBinding->classification() == QRhiVertexInputBinding::PerInstance) {
5394 desc.InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
5395 desc.InstanceDataStepRate = inputBinding->instanceStepRate();
5396 } else {
5397 desc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
5398 }
5399 inputDescs.append(desc);
5400 }
5401 if (!inputDescs.isEmpty()) {
5402 hr = rhiD->dev->CreateInputLayout(inputDescs.constData(), UINT(inputDescs.count()),
5403 vsByteCode, SIZE_T(vsByteCode.size()), &inputLayout);
5404 if (FAILED(hr)) {
5405 qWarning("Failed to create input layout: %s",
5406 qPrintable(QSystemError::windowsComString(hr)));
5407 return false;
5408 }
5409 } // else leave inputLayout set to nullptr; that's valid and it avoids a debug layer warning about an input layout with 0 elements
5410 }
5411
5412 rhiD->pipelineCreationEnd();
5413 generation += 1;
5414 rhiD->registerResource(this);
5415 return true;
5416}
5417
5420{
5421}
5422
5427
5429{
5430 if (!cs.shader)
5431 return;
5432
5433 cs.shader->Release();
5434 cs.shader = nullptr;
5435 cs.nativeResourceBindingMap.clear();
5436 pushConstants = {};
5437
5438 QRHI_RES_RHI(QRhiD3D11);
5439 if (rhiD)
5440 rhiD->unregisterResource(this);
5441}
5442
5444{
5445 if (cs.shader)
5446 destroy();
5447
5448 QRHI_RES_RHI(QRhiD3D11);
5449 rhiD->pipelineCreationStart();
5450
5451 auto cacheIt = rhiD->m_shaderCache.constFind(m_shaderStage);
5452 if (cacheIt != rhiD->m_shaderCache.constEnd()) {
5453 cs.shader = static_cast<ID3D11ComputeShader *>(cacheIt->s);
5454 cs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5455 pushConstants.reg = cacheIt->pushConstantRegister;
5456 pushConstants.size = cacheIt->pushConstantSize;
5457 } else {
5458 QString error;
5459 QShaderKey shaderKey;
5460 UINT compileFlags = 0;
5461 if (m_flags.testFlag(CompileShadersWithDebugInfo))
5462 compileFlags |= D3DCOMPILE_DEBUG;
5463
5464 const QByteArray bytecode = rhiD->compileHlslShaderSource(m_shaderStage.shader(), m_shaderStage.shaderVariant(), compileFlags,
5465 &error, &shaderKey);
5466 if (bytecode.isEmpty()) {
5467 qWarning("HLSL compute shader compilation failed: %s", qPrintable(error));
5468 return false;
5469 }
5470
5471 HRESULT hr = rhiD->dev->CreateComputeShader(bytecode.constData(), SIZE_T(bytecode.size()), nullptr, &cs.shader);
5472 if (FAILED(hr)) {
5473 qWarning("Failed to create compute shader: %s",
5474 qPrintable(QSystemError::windowsComString(hr)));
5475 return false;
5476 }
5477
5478 cs.nativeResourceBindingMap = m_shaderStage.shader().nativeResourceBindingMap(shaderKey);
5479 getPushConstantInfo(m_shaderStage.shader(), shaderKey, &pushConstants.reg, &pushConstants.size);
5480
5481 if (rhiD->m_shaderCache.count() >= QRhiD3D11::MAX_SHADER_CACHE_ENTRIES)
5483
5484 rhiD->m_shaderCache.insert(m_shaderStage, QRhiD3D11::Shader(cs.shader, bytecode, cs.nativeResourceBindingMap,
5485 pushConstants.reg, pushConstants.size));
5486 }
5487
5488 cs.shader->AddRef();
5489
5490 rhiD->pipelineCreationEnd();
5491 generation += 1;
5492 rhiD->registerResource(this);
5493 return true;
5494}
5495
5498{
5500}
5501
5506
5511
5513{
5514 // Creates the query objects if not yet done, but otherwise calling this
5515 // function is expected to be a no-op.
5516
5517 D3D11_QUERY_DESC queryDesc = {};
5518 for (int i = 0; i < TIMESTAMP_PAIRS; ++i) {
5519 if (!disjointQuery[i]) {
5520 queryDesc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
5521 HRESULT hr = rhiD->dev->CreateQuery(&queryDesc, &disjointQuery[i]);
5522 if (FAILED(hr)) {
5523 qWarning("Failed to create timestamp disjoint query: %s",
5524 qPrintable(QSystemError::windowsComString(hr)));
5525 return false;
5526 }
5527 }
5528 queryDesc.Query = D3D11_QUERY_TIMESTAMP;
5529 for (int j = 0; j < 2; ++j) {
5530 const int idx = 2 * i + j;
5531 if (!query[idx]) {
5532 HRESULT hr = rhiD->dev->CreateQuery(&queryDesc, &query[idx]);
5533 if (FAILED(hr)) {
5534 qWarning("Failed to create timestamp query: %s",
5535 qPrintable(QSystemError::windowsComString(hr)));
5536 return false;
5537 }
5538 }
5539 }
5540 }
5541 return true;
5542}
5543
5545{
5546 for (int i = 0; i < TIMESTAMP_PAIRS; ++i) {
5547 active[i] = false;
5548 if (disjointQuery[i]) {
5549 disjointQuery[i]->Release();
5550 disjointQuery[i] = nullptr;
5551 }
5552 for (int j = 0; j < 2; ++j) {
5553 const int idx = TIMESTAMP_PAIRS * i + j;
5554 if (query[idx]) {
5555 query[idx]->Release();
5556 query[idx] = nullptr;
5557 }
5558 }
5559 }
5560}
5561
5562bool QD3D11SwapChainTimestamps::tryQueryTimestamps(int pairIndex, ID3D11DeviceContext *context, double *elapsedSec)
5563{
5564 bool result = false;
5565 if (!active[pairIndex])
5566 return result;
5567
5568 ID3D11Query *tsDisjoint = disjointQuery[pairIndex];
5569 ID3D11Query *tsStart = query[pairIndex * 2];
5570 ID3D11Query *tsEnd = query[pairIndex * 2 + 1];
5571 quint64 timestamps[2];
5572 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT dj;
5573
5574 bool ok = true;
5575 ok &= context->GetData(tsDisjoint, &dj, sizeof(dj), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
5576 ok &= context->GetData(tsEnd, &timestamps[1], sizeof(quint64), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
5577 ok &= context->GetData(tsStart, &timestamps[0], sizeof(quint64), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
5578
5579 if (ok) {
5580 if (!dj.Disjoint && dj.Frequency) {
5581 const float elapsedMs = (timestamps[1] - timestamps[0]) / float(dj.Frequency) * 1000.0f;
5582 *elapsedSec = elapsedMs / 1000.0;
5583 result = true;
5584 }
5585 active[pairIndex] = false;
5586 } // else leave active set, will retry in a subsequent beginFrame
5587
5588 return result;
5589}
5590
5591QD3D11SwapChain::QD3D11SwapChain(QRhiImplementation *rhi)
5592 : QRhiSwapChain(rhi), rt(rhi, this), rtRight(rhi, this), cb(rhi)
5593{
5594 backBufferTex = nullptr;
5595 backBufferRtv = nullptr;
5596 for (int i = 0; i < BUFFER_COUNT; ++i) {
5597 msaaTex[i] = nullptr;
5598 msaaRtv[i] = nullptr;
5599 }
5600}
5601
5606
5608{
5609 if (backBufferRtv) {
5610 backBufferRtv->Release();
5611 backBufferRtv = nullptr;
5612 }
5613 if (backBufferRtvRight) {
5614 backBufferRtvRight->Release();
5615 backBufferRtvRight = nullptr;
5616 }
5617 if (backBufferTex) {
5618 backBufferTex->Release();
5619 backBufferTex = nullptr;
5620 }
5621 for (int i = 0; i < BUFFER_COUNT; ++i) {
5622 if (msaaRtv[i]) {
5623 msaaRtv[i]->Release();
5624 msaaRtv[i] = nullptr;
5625 }
5626 if (msaaTex[i]) {
5627 msaaTex[i]->Release();
5628 msaaTex[i] = nullptr;
5629 }
5630 }
5631}
5632
5634{
5635 if (dcompVisual) {
5636 dcompVisual->Release();
5637 dcompVisual = nullptr;
5638 }
5639
5640 if (dcompTarget) {
5641 dcompTarget->Release();
5642 dcompTarget = nullptr;
5643 }
5644
5645 if (!swapChain)
5646 return;
5647
5649
5650 timestamps.destroy();
5651
5652 swapChain->Release();
5653 swapChain = nullptr;
5654
5655 if (frameLatencyWaitableObject) {
5656 CloseHandle(frameLatencyWaitableObject);
5657 frameLatencyWaitableObject = nullptr;
5658 }
5659
5660 QDxgiVSyncService::instance()->unregisterWindow(window);
5661
5662 QRHI_RES_RHI(QRhiD3D11);
5663 if (rhiD) {
5664 rhiD->unregisterResource(this);
5665 // See Deferred Destruction Issues with Flip Presentation Swap Chains in
5666 // https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-flush
5667 rhiD->context->Flush();
5668 }
5669}
5670
5672{
5673 return &cb;
5674}
5675
5680
5682{
5683 return targetBuffer == StereoTargetBuffer::LeftBuffer? &rt: &rtRight;
5684}
5685
5687{
5688 Q_ASSERT(m_window);
5689 return m_window->size() * m_window->devicePixelRatio();
5690}
5691
5693{
5694 if (f == SDR)
5695 return true;
5696
5697 if (!m_window) {
5698 qWarning("Attempted to call isFormatSupported() without a window set");
5699 return false;
5700 }
5701
5702 QRHI_RES_RHI(QRhiD3D11);
5703 if (QDxgiHdrInfo(rhiD->activeAdapter).isHdrCapable(m_window))
5704 return f == QRhiSwapChain::HDRExtendedSrgbLinear || f == QRhiSwapChain::HDR10;
5705
5706 return false;
5707}
5708
5710{
5711 QRhiSwapChainHdrInfo info = QRhiSwapChain::hdrInfo();
5712 // Must use m_window, not window, given this may be called before createOrResize().
5713 if (m_window) {
5714 QRHI_RES_RHI(QRhiD3D11);
5715 info = QDxgiHdrInfo(rhiD->activeAdapter).queryHdrInfo(m_window);
5716 }
5717 return info;
5718}
5719
5721{
5722 QD3D11RenderPassDescriptor *rpD = new QD3D11RenderPassDescriptor(m_rhi);
5723 QRHI_RES_RHI(QRhiD3D11);
5724 rhiD->registerResource(rpD, false);
5725 return rpD;
5726}
5727
5728bool QD3D11SwapChain::newColorBuffer(const QSize &size, DXGI_FORMAT format, DXGI_SAMPLE_DESC sampleDesc,
5729 ID3D11Texture2D **tex, ID3D11RenderTargetView **rtv) const
5730{
5731 D3D11_TEXTURE2D_DESC desc = {};
5732 desc.Width = UINT(size.width());
5733 desc.Height = UINT(size.height());
5734 desc.MipLevels = 1;
5735 desc.ArraySize = 1;
5736 desc.Format = format;
5737 desc.SampleDesc = sampleDesc;
5738 desc.Usage = D3D11_USAGE_DEFAULT;
5739 desc.BindFlags = D3D11_BIND_RENDER_TARGET;
5740
5741 QRHI_RES_RHI(QRhiD3D11);
5742 HRESULT hr = rhiD->dev->CreateTexture2D(&desc, nullptr, tex);
5743 if (FAILED(hr)) {
5744 qWarning("Failed to create color buffer texture: %s",
5745 qPrintable(QSystemError::windowsComString(hr)));
5746 return false;
5747 }
5748
5749 D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
5750 rtvDesc.Format = format;
5751 rtvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
5752 hr = rhiD->dev->CreateRenderTargetView(*tex, &rtvDesc, rtv);
5753 if (FAILED(hr)) {
5754 qWarning("Failed to create color buffer rtv: %s",
5755 qPrintable(QSystemError::windowsComString(hr)));
5756 (*tex)->Release();
5757 *tex = nullptr;
5758 return false;
5759 }
5760
5761 return true;
5762}
5763
5765{
5766 if (dcompDevice)
5767 return true;
5768
5769 qCDebug(QRHI_LOG_INFO, "Creating Direct Composition device (needed for semi-transparent windows)");
5770 dcompDevice = QRhiD3D::createDirectCompositionDevice();
5771 return dcompDevice ? true : false;
5772}
5773
5774static const DXGI_FORMAT DEFAULT_FORMAT = DXGI_FORMAT_R8G8B8A8_UNORM;
5775static const DXGI_FORMAT DEFAULT_SRGB_FORMAT = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
5776
5778{
5779 // Can be called multiple times due to window resizes - that is not the
5780 // same as a simple destroy+create (as with other resources). Just need to
5781 // resize the buffers then.
5782
5783 const bool needsRegistration = !window || window != m_window;
5784 const bool stereo = m_window->format().stereo();
5785
5786 // except if the window actually changes
5787 if (window && window != m_window)
5788 destroy();
5789
5790 window = m_window;
5791 pixelSize = surfacePixelSize();
5792
5793 if (pixelSize.isEmpty())
5794 return false;
5795
5796 HWND hwnd = reinterpret_cast<HWND>(window->winId());
5797 HRESULT hr;
5798
5799 QRHI_RES_RHI(QRhiD3D11);
5800
5801 if (m_flags.testFlag(SurfaceHasPreMulAlpha) || m_flags.testFlag(SurfaceHasNonPreMulAlpha)) {
5803 if (!dcompTarget) {
5804 hr = rhiD->dcompDevice->CreateTargetForHwnd(hwnd, false, &dcompTarget);
5805 if (FAILED(hr)) {
5806 qWarning("Failed to create Direct Compsition target for the window: %s",
5807 qPrintable(QSystemError::windowsComString(hr)));
5808 }
5809 }
5810 if (dcompTarget && !dcompVisual) {
5811 hr = rhiD->dcompDevice->CreateVisual(&dcompVisual);
5812 if (FAILED(hr)) {
5813 qWarning("Failed to create DirectComposition visual: %s",
5814 qPrintable(QSystemError::windowsComString(hr)));
5815 }
5816 }
5817 }
5818 // simple consistency check
5819 if (window->requestedFormat().alphaBufferSize() <= 0)
5820 qWarning("Swapchain says surface has alpha but the window has no alphaBufferSize set. "
5821 "This may lead to problems.");
5822 }
5823
5824 swapInterval = m_flags.testFlag(QRhiSwapChain::NoVSync) ? 0 : 1;
5825 swapChainFlags = 0;
5826
5827 // A non-flip swapchain can do Present(0) as expected without
5828 // ALLOW_TEARING, and ALLOW_TEARING is not compatible with it at all so the
5829 // flag must not be set then. Whereas for flip we should use it, if
5830 // supported, to get better results for 'unthrottled' presentation.
5831 if (swapInterval == 0 && rhiD->supportsAllowTearing)
5832 swapChainFlags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
5833
5834 // maxFrameLatency 0 means no waitable object usage.
5835 // Ignore it also when NoVSync is on, and when using WARP.
5836 const bool useFrameLatencyWaitableObject = rhiD->maxFrameLatency != 0
5837 && swapInterval != 0
5838 && rhiD->driverInfoStruct.deviceType != QRhiDriverInfo::CpuDevice;
5839
5840 if (useFrameLatencyWaitableObject) {
5841 // the flag is not supported in real fullscreen on D3D11, but perhaps that's fine since we only do borderless
5842 swapChainFlags |= DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
5843 }
5844
5845 if (!swapChain) {
5846 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount);
5847 colorFormat = DEFAULT_FORMAT;
5848 srgbAdjustedColorFormat = m_flags.testFlag(sRGB) ? DEFAULT_SRGB_FORMAT : DEFAULT_FORMAT;
5849
5850 DXGI_COLOR_SPACE_TYPE hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; // SDR
5851 if (m_format != SDR) {
5852 if (QDxgiHdrInfo(rhiD->activeAdapter).isHdrCapable(m_window)) {
5853 // https://docs.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range
5854 switch (m_format) {
5855 case HDRExtendedSrgbLinear:
5856 colorFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;
5857 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
5858 srgbAdjustedColorFormat = colorFormat;
5859 break;
5860 case HDR10:
5861 colorFormat = DXGI_FORMAT_R10G10B10A2_UNORM;
5862 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
5863 srgbAdjustedColorFormat = colorFormat;
5864 break;
5865 default:
5866 break;
5867 }
5868 } else {
5869 // This happens also when Use HDR is set to Off in the Windows
5870 // Display settings. Show a helpful warning, but continue with the
5871 // default non-HDR format.
5872 qWarning("The output associated with the window is not HDR capable "
5873 "(or Use HDR is Off in the Display Settings), ignoring HDR format request");
5874 }
5875 }
5876
5877 // We use a FLIP model swapchain which implies a buffer count of 2
5878 // (as opposed to the old DISCARD with back buffer count == 1).
5879 // This makes no difference for the rest of the stuff except that
5880 // automatic MSAA is unsupported and needs to be implemented via a
5881 // custom multisample render target and an explicit resolve.
5882
5883 DXGI_SWAP_CHAIN_DESC1 desc = {};
5884 desc.Width = UINT(pixelSize.width());
5885 desc.Height = UINT(pixelSize.height());
5886 desc.Format = colorFormat;
5887 desc.SampleDesc.Count = 1;
5888 desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
5889 desc.BufferCount = BUFFER_COUNT;
5890 desc.Flags = swapChainFlags;
5891 desc.Scaling = rhiD->useLegacySwapchainModel ? DXGI_SCALING_STRETCH : DXGI_SCALING_NONE;
5892 desc.SwapEffect = rhiD->useLegacySwapchainModel ? DXGI_SWAP_EFFECT_DISCARD : DXGI_SWAP_EFFECT_FLIP_DISCARD;
5893 desc.Stereo = stereo;
5894
5895 if (dcompVisual) {
5896 // With DirectComposition setting AlphaMode to STRAIGHT fails the
5897 // swapchain creation, whereas the result seems to be identical
5898 // with any of the other values, including IGNORE. (?)
5899 desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
5900
5901 // DirectComposition has its own limitations, cannot use
5902 // SCALING_NONE. So with semi-transparency requested we are forced
5903 // to SCALING_STRETCH.
5904 desc.Scaling = DXGI_SCALING_STRETCH;
5905 }
5906
5907 IDXGIFactory2 *fac = static_cast<IDXGIFactory2 *>(rhiD->dxgiFactory);
5908 IDXGISwapChain1 *sc1;
5909
5910 if (dcompVisual)
5911 hr = fac->CreateSwapChainForComposition(rhiD->dev, &desc, nullptr, &sc1);
5912 else
5913 hr = fac->CreateSwapChainForHwnd(rhiD->dev, hwnd, &desc, nullptr, nullptr, &sc1);
5914
5915 // If failed and we tried a HDR format, then try with SDR. This
5916 // matches other backends, such as Vulkan where if the format is
5917 // not supported, the default one is used instead.
5918 if (FAILED(hr) && m_format != SDR) {
5919 colorFormat = DEFAULT_FORMAT;
5920 desc.Format = DEFAULT_FORMAT;
5921 if (dcompVisual)
5922 hr = fac->CreateSwapChainForComposition(rhiD->dev, &desc, nullptr, &sc1);
5923 else
5924 hr = fac->CreateSwapChainForHwnd(rhiD->dev, hwnd, &desc, nullptr, nullptr, &sc1);
5925 }
5926
5927 if (SUCCEEDED(hr)) {
5928 swapChain = sc1;
5929 IDXGISwapChain3 *sc3 = nullptr;
5930 if (SUCCEEDED(sc1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void **>(&sc3)))) {
5931 if (m_format != SDR) {
5932 hr = sc3->SetColorSpace1(hdrColorSpace);
5933 if (FAILED(hr))
5934 qWarning("Failed to set color space on swapchain: %s",
5935 qPrintable(QSystemError::windowsComString(hr)));
5936 }
5937 if (useFrameLatencyWaitableObject) {
5938 sc3->SetMaximumFrameLatency(rhiD->maxFrameLatency);
5939 frameLatencyWaitableObject = sc3->GetFrameLatencyWaitableObject();
5940 }
5941 sc3->Release();
5942 } else {
5943 if (m_format != SDR)
5944 qWarning("IDXGISwapChain3 not available, HDR swapchain will not work as expected");
5945 if (useFrameLatencyWaitableObject) {
5946 IDXGISwapChain2 *sc2 = nullptr;
5947 if (SUCCEEDED(sc1->QueryInterface(__uuidof(IDXGISwapChain2), reinterpret_cast<void **>(&sc2)))) {
5948 sc2->SetMaximumFrameLatency(rhiD->maxFrameLatency);
5949 frameLatencyWaitableObject = sc2->GetFrameLatencyWaitableObject();
5950 sc2->Release();
5951 } else { // this cannot really happen since we require DXGIFactory2
5952 qWarning("IDXGISwapChain2 not available, FrameLatencyWaitableObject cannot be used");
5953 }
5954 }
5955 }
5956 if (dcompVisual) {
5957 hr = dcompVisual->SetContent(sc1);
5958 if (SUCCEEDED(hr)) {
5959 hr = dcompTarget->SetRoot(dcompVisual);
5960 if (FAILED(hr)) {
5961 qWarning("Failed to associate Direct Composition visual with the target: %s",
5962 qPrintable(QSystemError::windowsComString(hr)));
5963 }
5964 } else {
5965 qWarning("Failed to set content for Direct Composition visual: %s",
5966 qPrintable(QSystemError::windowsComString(hr)));
5967 }
5968 } else {
5969 // disable Alt+Enter; not relevant when using DirectComposition
5970 rhiD->dxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES);
5971 }
5972 }
5973 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
5974 qWarning("Device loss detected during swapchain creation");
5975 rhiD->deviceLost = true;
5976 return false;
5977 } else if (FAILED(hr)) {
5978 qWarning("Failed to create D3D11 swapchain: %s"
5979 " (Width=%u Height=%u Format=%u SampleCount=%u BufferCount=%u Scaling=%u SwapEffect=%u Stereo=%u)",
5980 qPrintable(QSystemError::windowsComString(hr)),
5981 desc.Width, desc.Height, UINT(desc.Format), desc.SampleDesc.Count,
5982 desc.BufferCount, UINT(desc.Scaling), UINT(desc.SwapEffect), UINT(desc.Stereo));
5983 return false;
5984 }
5985 } else {
5987 // flip model -> buffer count is the real buffer count, not 1 like with the legacy modes
5988 hr = swapChain->ResizeBuffers(UINT(BUFFER_COUNT), UINT(pixelSize.width()), UINT(pixelSize.height()),
5989 colorFormat, swapChainFlags);
5990 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
5991 qWarning("Device loss detected in ResizeBuffers()");
5992 rhiD->deviceLost = true;
5993 return false;
5994 } else if (FAILED(hr)) {
5995 qWarning("Failed to resize D3D11 swapchain: %s",
5996 qPrintable(QSystemError::windowsComString(hr)));
5997 return false;
5998 }
5999 }
6000
6001 // This looks odd (for FLIP_*, esp. compared with backends for Vulkan
6002 // & co.) but the backbuffer is always at index 0, with magic underneath.
6003 // Some explanation from
6004 // https://docs.microsoft.com/en-us/windows/win32/direct3ddxgi/dxgi-1-4-improvements
6005 //
6006 // "In Direct3D 11, applications could call GetBuffer( 0, … ) only once.
6007 // Every call to Present implicitly changed the resource identity of the
6008 // returned interface. Direct3D 12 no longer supports that implicit
6009 // resource identity change, due to the CPU overhead required and the
6010 // flexible resource descriptor design. As a result, the application must
6011 // manually call GetBuffer for every each buffer created with the
6012 // swapchain."
6013
6014 // So just query index 0 once (per resize) and be done with it.
6015 hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&backBufferTex));
6016 if (FAILED(hr)) {
6017 qWarning("Failed to query swapchain backbuffer: %s",
6018 qPrintable(QSystemError::windowsComString(hr)));
6019 return false;
6020 }
6021 D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
6022 rtvDesc.Format = srgbAdjustedColorFormat;
6023 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
6024 hr = rhiD->dev->CreateRenderTargetView(backBufferTex, &rtvDesc, &backBufferRtv);
6025 if (FAILED(hr)) {
6026 qWarning("Failed to create rtv for swapchain backbuffer: %s",
6027 qPrintable(QSystemError::windowsComString(hr)));
6028 return false;
6029 }
6030
6031 if (stereo) {
6032 // Create a second render target view for the right eye
6033 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
6034 rtvDesc.Texture2DArray.FirstArraySlice = 1;
6035 rtvDesc.Texture2DArray.ArraySize = 1;
6036 hr = rhiD->dev->CreateRenderTargetView(backBufferTex, &rtvDesc, &backBufferRtvRight);
6037 if (FAILED(hr)) {
6038 qWarning("Failed to create rtv for swapchain backbuffer (right eye): %s",
6039 qPrintable(QSystemError::windowsComString(hr)));
6040 return false;
6041 }
6042 }
6043
6044 // Try to reduce stalls by having a dedicated MSAA texture per swapchain buffer.
6045 for (int i = 0; i < BUFFER_COUNT; ++i) {
6046 if (sampleDesc.Count > 1) {
6047 if (!newColorBuffer(pixelSize, srgbAdjustedColorFormat, sampleDesc, &msaaTex[i], &msaaRtv[i]))
6048 return false;
6049 }
6050 }
6051
6052 if (m_depthStencil && m_depthStencil->sampleCount() != m_sampleCount) {
6053 qWarning("Depth-stencil buffer's sampleCount (%d) does not match color buffers' sample count (%d). Expect problems.",
6054 m_depthStencil->sampleCount(), m_sampleCount);
6055 }
6056 if (m_depthStencil && m_depthStencil->pixelSize() != pixelSize) {
6057 if (m_depthStencil->flags().testFlag(QRhiRenderBuffer::UsedWithSwapChainOnly)) {
6058 m_depthStencil->setPixelSize(pixelSize);
6059 if (!m_depthStencil->create())
6060 qWarning("Failed to rebuild swapchain's associated depth-stencil buffer for size %dx%d",
6061 pixelSize.width(), pixelSize.height());
6062 } else {
6063 qWarning("Depth-stencil buffer's size (%dx%d) does not match the surface size (%dx%d). Expect problems.",
6064 m_depthStencil->pixelSize().width(), m_depthStencil->pixelSize().height(),
6065 pixelSize.width(), pixelSize.height());
6066 }
6067 }
6068
6069 currentFrameSlot = 0;
6070 lastFrameLatencyWaitSlot = -1; // wait already in the first frame, as instructed in the dxgi docs
6071 frameCount = 0;
6072 ds = m_depthStencil ? QRHI_RES(QD3D11RenderBuffer, m_depthStencil) : nullptr;
6073
6074 rt.setRenderPassDescriptor(m_renderPassDesc); // for the public getter in QRhiRenderTarget
6075 QD3D11SwapChainRenderTarget *rtD = QRHI_RES(QD3D11SwapChainRenderTarget, &rt);
6076 rtD->d.rp = QRHI_RES(QD3D11RenderPassDescriptor, m_renderPassDesc);
6077 rtD->d.pixelSize = pixelSize;
6078 rtD->d.dpr = float(window->devicePixelRatio());
6079 rtD->d.sampleCount = int(sampleDesc.Count);
6080 rtD->d.views.setFrom(1, &backBufferRtv, ds ? ds->dsv : nullptr);
6081
6082 if (stereo) {
6083 rtD = QRHI_RES(QD3D11SwapChainRenderTarget, &rtRight);
6084 rtD->d.rp = QRHI_RES(QD3D11RenderPassDescriptor, m_renderPassDesc);
6085 rtD->d.pixelSize = pixelSize;
6086 rtD->d.dpr = float(window->devicePixelRatio());
6087 rtD->d.sampleCount = int(sampleDesc.Count);
6088 rtD->d.views.setFrom(1, &backBufferRtvRight, ds ? ds->dsv : nullptr);
6089 }
6090
6091 if (rhiD->rhiFlags.testFlag(QRhi::EnableTimestamps)) {
6092 timestamps.prepare(rhiD);
6093 // timestamp queries are optional so we can go on even if they failed
6094 }
6095
6096 QDxgiVSyncService::instance()->registerWindow(window);
6097
6098 if (needsRegistration)
6099 rhiD->registerResource(this);
6100
6101 m_currentPixelSize = pixelSize;
6102 return true;
6103}
6104
6105bool QD3D11RenderTargetUavUpdateState::update(const QD3D11RenderTargetData::Views &currentRtViews, ID3D11UnorderedAccessView *const *uavs, int count)
6106{
6107 bool ret = false;
6108 if (rtViews.dsv != currentRtViews.dsv) {
6109 rtViews.dsv = currentRtViews.dsv;
6110 ret = true;
6111 }
6112 for (int i = 0; i < currentRtViews.colorAttCount; i++) {
6113 ret |= rtViews.rtv[i] != currentRtViews.rtv[i];
6114 rtViews.rtv[i] = currentRtViews.rtv[i];
6115 }
6116 rtViews.colorAttCount = currentRtViews.colorAttCount;
6117 for (int i = currentRtViews.colorAttCount; i < QD3D11RenderTargetData::MAX_COLOR_ATTACHMENTS; i++) {
6118 ret |= rtViews.rtv[i] != nullptr;
6119 rtViews.rtv[i] = nullptr;
6120 }
6121 for (int i = 0; i < count; i++) {
6122 ret |= uav[i] != uavs[i];
6123 uav[i] = uavs[i];
6124 }
6125 for (int i = count; i < QD3D11RenderTargetData::MAX_COLOR_ATTACHMENTS; i++) {
6126 ret |= uav[i] != nullptr;
6127 uav[i] = nullptr;
6128 }
6129 return ret;
6130}
6131
6132
6133QT_END_NAMESPACE
QRhiDriverInfo info() const override
void updateShaderResourceBindings(QD3D11ShaderResourceBindings *srbD, const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[], uint pushConstantStages)
void setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor) override
bool deviceLost
void debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg) override
bool isYUpInNDC() const override
void drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
QRhiSwapChain * createSwapChain() override
void enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
bool isFeatureSupported(QRhi::Feature feature) const override
QRhi::FrameOpResult endOffscreenFrame(QRhi::EndFrameFlags flags) override
bool isDeviceLost() const override
void executeBufferHostWrites(QD3D11Buffer *bufD)
QRhiStats statistics() override
QList< QSize > supportedShadingRates(int sampleCount) const override
QRhiComputePipeline * createComputePipeline() override
void debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name) override
bool debugLayer
QRhi::FrameOpResult finish() override
void setVertexInput(QRhiCommandBuffer *cb, int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings, QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat) override
void dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset) override
QRhiGraphicsPipeline * createGraphicsPipeline() override
void drawIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
QRhiShaderResourceBindings * createShaderResourceBindings() override
QRhi::FrameOpResult beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags) override
QList< int > supportedSampleCounts() const override
QRhiTextureRenderTarget * createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc, QRhiTextureRenderTarget::Flags flags) override
QByteArray compileHlslShaderSource(const QShader &shader, QShader::Variant shaderVariant, uint flags, QString *error, QShaderKey *usedShaderKey)
void setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) override
bool isClipDepthZeroToOne() const override
void resetShaderResources(QD3D11CommandBuffer *cbD, QD3D11RenderTargetUavUpdateState *rtUavState)
bool ensureDirectCompositionDevice()
const QRhiNativeHandles * nativeHandles(QRhiCommandBuffer *cb) override
void beginComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
void draw(QRhiCommandBuffer *cb, quint32 vertexCount, quint32 instanceCount, quint32 firstVertex, quint32 firstInstance) override
void enqueueSubresUpload(QD3D11Texture *texD, QD3D11CommandBuffer *cbD, int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc)
void reportLiveObjects(ID3D11Device *device)
void resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
void destroy() override
QMatrix4x4 clipSpaceCorrMatrix() const override
void setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data) override
bool isYUpInFramebuffer() const override
int resourceLimit(QRhi::ResourceLimit limit) const override
void beginExternal(QRhiCommandBuffer *cb) override
QRhiTexture * createTexture(QRhiTexture::Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, QRhiTexture::Flags flags) override
void setPipelineCacheData(const QByteArray &data) override
void executeCommandBuffer(QD3D11CommandBuffer *cbD)
void debugMarkEnd(QRhiCommandBuffer *cb) override
void releaseCachedResources() override
double lastCompletedGpuTime(QRhiCommandBuffer *cb) override
bool importedDeviceAndContext
QRhi::FrameOpResult beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags) override
bool supportsAllowTearing
void dispatch(QRhiCommandBuffer *cb, int x, int y, int z) override
void endExternal(QRhiCommandBuffer *cb) override
void setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport) override
bool ensurePushConstantBuffer()
void drawIndexedIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
void setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps) override
QRhi::FrameOpResult endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags) override
QRhiShadingRateMap * createShadingRateMap() override
bool isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const override
void setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb, int dynamicOffsetCount, const QRhiCommandBuffer::DynamicOffset *dynamicOffsets) override
void clearShaderCache()
bool useLegacySwapchainModel
void endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
bool makeThreadLocalNativeContextCurrent() override
bool create(QRhi::Flags flags) override
void finishActiveReadbacks()
void setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize) override
QByteArray pipelineCacheData() override
const QRhiNativeHandles * nativeHandles() override
QRhiDriverInfo driverInfo() const override
void endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
int ubufAlignment() const override
void beginPass(QRhiCommandBuffer *cb, QRhiRenderTarget *rt, const QColor &colorClearValue, const QRhiDepthStencilClearValue &depthStencilClearValue, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
void bindShaderResources(QD3D11CommandBuffer *cbD, const QD3D11ShaderResourceBindings::ResourceBatches &allResourceBatches, const uint *dynOfsPairs, int dynOfsPairCount, bool offsetOnlyChange, QD3D11RenderTargetUavUpdateState *rtUavState)
void drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount, quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance) override
QRhiSampler * createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter, QRhiSampler::Filter mipmapMode, QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w) override
void setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps) override
QRhiD3D11(QRhiD3D11InitParams *params, QRhiD3D11NativeHandles *importDevice=nullptr)
DXGI_SAMPLE_DESC effectiveSampleDesc(int sampleCount) const
void setStencilRef(QRhiCommandBuffer *cb, quint32 refValue) override
void drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
static QRhiResourceUpdateBatchPrivate * get(QRhiResourceUpdateBatch *b)
Definition qrhi_p.h:756
void fillDriverInfo(QRhiDriverInfo *info, const DXGI_ADAPTER_DESC1 &desc)
@ 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 const DXGI_FORMAT DEFAULT_SRGB_FORMAT
static void applyDynamicOffsets(UINT *offsets, int batchIndex, const QRhiBatchedBindings< UINT > *originalBindings, const QRhiBatchedBindings< UINT > *staticOffsets, const uint *dynOfsPairs, int dynOfsPairCount)
static D3D11_TEXTURE_ADDRESS_MODE toD3DAddressMode(QRhiSampler::AddressMode m)
#define SETUAVBATCH(stagePrefixL, stagePrefixU)
static QByteArray sourceHash(const QByteArray &source)
#define SETSAMPLERBATCH(stagePrefixL, stagePrefixU)
static const int RBM_HULL
static uint toD3DBufferUsage(QRhiBuffer::UsageFlags usage)
static const int RBM_FRAGMENT
#define SETUBUFBATCH(stagePrefixL, stagePrefixU)
Int aligned(Int v, Int byteAlign)
\variable QRhiVulkanQueueSubmitParams::waitSemaphoreCount
static DXGI_FORMAT toD3DDepthTextureDSVFormat(QRhiTexture::Format format)
static D3D11_BLEND toD3DBlendFactor(QRhiGraphicsPipeline::BlendFactor f, bool rgb)
static const int RBM_VERTEX
static D3D11_BLEND_OP toD3DBlendOp(QRhiGraphicsPipeline::BlendOp op)
#define D3D11_1_UAV_SLOT_COUNT
static const int RBM_DOMAIN
static D3D11_FILTER toD3DFilter(QRhiSampler::Filter minFilter, QRhiSampler::Filter magFilter, QRhiSampler::Filter mipFilter)
static std::pair< int, int > mapBinding(int binding, int stageIndex, const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[], uint pushConstantStages)
static QD3D11RenderTargetData * rtData(QRhiRenderTarget *rt)
static UINT8 toD3DColorWriteMask(QRhiGraphicsPipeline::ColorMask c)
static D3D11_STENCIL_OP toD3DStencilOp(QRhiGraphicsPipeline::StencilOp op)
void releasePipelineShader(T &s)
static D3D11_COMPARISON_FUNC toD3DTextureComparisonFunc(QRhiSampler::CompareOp op)
static int rbmStageIndex(QRhiShaderStage::Type type)
static DXGI_FORMAT toD3DAttributeFormat(QRhiVertexInputAttribute::Format format)
static void getPushConstantInfo(const QShader &shader, const QShaderKey &key, int *reg, quint32 *size)
static const int RBM_GEOMETRY
static D3D11_PRIMITIVE_TOPOLOGY toD3DTopology(QRhiGraphicsPipeline::Topology t, int patchControlPointCount)
static IDXGIFactory1 * createDXGIFactory2()
static D3D11_FILL_MODE toD3DFillMode(QRhiGraphicsPipeline::PolygonMode mode)
static bool isDepthTextureFormat(QRhiTexture::Format format)
static const int RBM_COMPUTE
static D3D11_CULL_MODE toD3DCullMode(QRhiGraphicsPipeline::CullMode c)
#define SETSHADER(StageL, StageU)
static DXGI_FORMAT toD3DTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
static const DXGI_FORMAT DEFAULT_FORMAT
static uint clampedResourceCount(uint startSlot, int countSlots, uint maxSlots, const char *resType)
#define D3D11_VS_INPUT_REGISTER_COUNT
#define DXGI_ADAPTER_FLAG_SOFTWARE
\variable QRhiD3D11NativeHandles::dev
static QRhiTexture::Format swapchainReadbackTextureFormat(DXGI_FORMAT format, QRhiTexture::Flags *flags)
static D3D11_COMPARISON_FUNC toD3DCompareOp(QRhiGraphicsPipeline::CompareOp op)
static DXGI_FORMAT toD3DDepthTextureSRVFormat(QRhiTexture::Format format)
static const int RBM_SUPPORTED_STAGES
bool hasPendingDynamicUpdates
Definition qrhid3d11_p.h:48
void endFullDynamicBufferUpdateForCurrentFrame() override
To be called when the entire contents of the buffer data has been updated in the memory block returne...
char * dynBuf
Definition qrhid3d11_p.h:47
QD3D11Buffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
char * beginFullDynamicBufferUpdateForCurrentFrame() override
bool create() override
Creates the corresponding native graphics resources.
ID3D11UnorderedAccessView * createClearUnorderedAccessView(quint32 offset, quint32 size)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QRhiBuffer::NativeBuffer nativeBuffer() override
ID3D11UnorderedAccessView * unorderedAccessView(quint32 offset)
static const int MAX_DYNAMIC_OFFSET_COUNT
static const int MAX_VERTEX_BUFFER_BINDING_COUNT
int retainResourceBatches(const std::shared_ptr< QD3D11ShaderResourceBindings::ResourceBatches > &resourceBatches)
QD3D11CommandBuffer(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QD3D11ComputePipeline(QRhiImplementation *rhi)
bool create() override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QD3D11GraphicsPipeline(QRhiImplementation *rhi)
bool create() override
Creates the corresponding native graphics resources.
QD3D11RenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize, int sampleCount, QRhiRenderBuffer::Flags flags, QRhiTexture::Format backingFormatHint)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool create() override
Creates the corresponding native graphics resources.
QRhiTexture::Format backingFormat() const override
QD3D11RenderPassDescriptor(QRhiImplementation *rhi)
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool isCompatible(const QRhiRenderPassDescriptor *other) const override
QVector< quint32 > serializedFormat() const override
static const int MAX_COLOR_ATTACHMENTS
bool update(const QD3D11RenderTargetData::Views &currentRtViews, ID3D11UnorderedAccessView *const *uavs=nullptr, int count=0)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QD3D11Sampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode, AddressMode u, AddressMode v, AddressMode w)
bool create() override
QD3D11GraphicsPipeline * lastUsedGraphicsPipeline
bool create() override
Creates the corresponding resource binding set.
void updateResources(UpdateFlags flags) override
QD3D11ComputePipeline * lastUsedComputePipeline
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QD3D11ShaderResourceBindings(QRhiImplementation *rhi)
int sampleCount() const override
QD3D11SwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
float devicePixelRatio() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QSize pixelSize() const override
bool prepare(QRhiD3D11 *rhiD)
bool tryQueryTimestamps(int idx, ID3D11DeviceContext *context, double *elapsedSec)
bool active[TIMESTAMP_PAIRS]
static const int TIMESTAMP_PAIRS
QRhiSwapChainHdrInfo hdrInfo() override
\variable QRhiSwapChainHdrInfo::limitsType
int lastFrameLatencyWaitSlot
QWindow * window
QD3D11RenderBuffer * ds
QRhiRenderTarget * currentFrameRenderTarget() override
QD3D11SwapChain(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QRhiRenderTarget * currentFrameRenderTarget(StereoTargetBuffer targetBuffer) override
bool createOrResize() override
Creates the swapchain if not already done and resizes the swapchain buffers to match the current size...
QSize surfacePixelSize() override
bool newColorBuffer(const QSize &size, DXGI_FORMAT format, DXGI_SAMPLE_DESC sampleDesc, ID3D11Texture2D **tex, ID3D11RenderTargetView **rtv) const
static const int BUFFER_COUNT
bool isFormatSupported(Format f) override
QRhiCommandBuffer * currentFrameCommandBuffer() override
int currentTimestampPairIndex
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() override
QSize pixelSize() const override
QD3D11TextureRenderTarget(QRhiImplementation *rhi, const QRhiTextureRenderTargetDescription &desc, Flags flags)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
float devicePixelRatio() const override
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() override
int sampleCount() const override
bool ownsRtv[QD3D11RenderTargetData::MAX_COLOR_ATTACHMENTS]
bool create() override
Creates the corresponding 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.
bool createFrom(NativeTexture src) override
Similar to create(), except that no new native textures are created.
NativeTexture nativeTexture() override
bool prepareCreate(QSize *adjustedSize=nullptr)
QD3D11Texture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, Flags flags)
ID3D11UnorderedAccessView * unorderedAccessViewForLevel(int level)
bool finishCreate()
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:2016
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:1616