8#include <QtCore/private/qsystemerror_p.h>
9#include <QtCore/qcryptographichash.h>
10#include <QtCore/qendian.h>
20#define QRHI_D3D12_HAS_OLD_PIX
23#ifdef __ID3D12Device2_INTERFACE_DEFINED__
28
29
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
73
74
75
76
77
78
79
80
81
84
85
86
87
88
89
90
91
92
93
94
95
96
99
100
101
102
103
104
105
106
107
108
109
110
113
114
115
116
117
118
121
122
123
124
125
126
127
128
129
130
131
134
135
136
137
138
139
142
143
144
145
146
147
150
151
152
153
154
155
156
159
160
161
162
163
164
165
166
167
168
169
170
171
172
175
176
179static const D3D_FEATURE_LEVEL MIN_FEATURE_LEVEL = D3D_FEATURE_LEVEL_11_0;
181QRhiD3D12::QRhiD3D12(QRhiD3D12InitParams *params, QRhiD3D12NativeHandles *importParams)
183 debugLayer = params->enableDebugLayer;
184 gpuBasedValidation = params->enableGpuBasedValidation;
186 if (importParams->dev) {
187 ID3D12Device *d3d12Device =
reinterpret_cast<ID3D12Device *>(importParams->dev);
188 if (SUCCEEDED(d3d12Device->QueryInterface(__uuidof(ID3D12Device2),
reinterpret_cast<
void **>(&dev)))) {
190 d3d12Device->Release();
191 importedDevice =
true;
193 qWarning(
"ID3D12Device2 not supported, cannot import device");
196 if (importParams->commandQueue) {
197 cmdQueue =
reinterpret_cast<ID3D12CommandQueue *>(importParams->commandQueue);
198 importedCommandQueue =
true;
200 minimumFeatureLevel = D3D_FEATURE_LEVEL(importParams->minimumFeatureLevel);
201 adapterLuid.LowPart = importParams->adapterLuidLow;
202 adapterLuid.HighPart = importParams->adapterLuidHigh;
207inline Int aligned(Int v, Int byteAlign)
209 return (v + byteAlign - 1) & ~(byteAlign - 1);
212static inline UINT calcSubresource(UINT mipSlice, UINT arraySlice, UINT mipLevels)
214 return mipSlice + arraySlice * mipLevels;
217static inline QD3D12RenderTargetData *rtData(QRhiRenderTarget *rt)
219 switch (rt->resourceType()) {
220 case QRhiResource::SwapChainRenderTarget:
221 return &QRHI_RES(QD3D12SwapChainRenderTarget, rt)->d;
222 case QRhiResource::TextureRenderTarget:
223 return &QRHI_RES(QD3D12TextureRenderTarget, rt)->d;
228 Q_UNREACHABLE_RETURN(
nullptr);
231static D3D12_MESSAGE_ID qd3d12_suppressed_messages[] = {
233 D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE,
235 D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE,
237 D3D12_MESSAGE_ID_DRAW_EMPTY_SCISSOR_RECTANGLE,
240 D3D12_MESSAGE_ID_LOADPIPELINE_NAMENOTFOUND
243#ifdef QRHI_D3D12_INFOQUEUE1_AVAILABLE
244static void __stdcall qd3d12_message_callback(D3D12_MESSAGE_CATEGORY category,
245 D3D12_MESSAGE_SEVERITY severity,
255 if (severity == D3D12_MESSAGE_SEVERITY_INFO)
257 for (D3D12_MESSAGE_ID suppressedId : qd3d12_suppressed_messages) {
258 if (id == suppressedId)
264 qDebug(
"D3D12: %s", description);
268bool QRhiD3D12::create(QRhi::Flags flags)
272 UINT factoryFlags = 0;
274 factoryFlags |= DXGI_CREATE_FACTORY_DEBUG;
275 HRESULT hr = CreateDXGIFactory2(factoryFlags, __uuidof(IDXGIFactory2),
reinterpret_cast<
void **>(&dxgiFactory));
279 qCDebug(QRHI_LOG_INFO,
"Debug layer was requested but is not available. "
280 "Attempting to create DXGIFactory2 without it.");
281 factoryFlags &= ~DXGI_CREATE_FACTORY_DEBUG;
282 hr = CreateDXGIFactory2(factoryFlags, __uuidof(IDXGIFactory2),
reinterpret_cast<
void **>(&dxgiFactory));
287 qWarning(
"CreateDXGIFactory2() failed to create DXGI factory: %s",
288 qPrintable(QSystemError::windowsComString(hr)));
293 if (qEnvironmentVariableIsSet(
"QT_D3D_MAX_FRAME_LATENCY"))
294 maxFrameLatency = UINT(qMax(0, qEnvironmentVariableIntValue(
"QT_D3D_MAX_FRAME_LATENCY")));
295 if (maxFrameLatency != 0)
296 qCDebug(QRHI_LOG_INFO,
"Using frame latency waitable object with max frame latency %u", maxFrameLatency);
298 supportsAllowTearing =
false;
299 IDXGIFactory5 *factory5 =
nullptr;
300 if (SUCCEEDED(dxgiFactory->QueryInterface(__uuidof(IDXGIFactory5),
reinterpret_cast<
void **>(&factory5)))) {
301 BOOL allowTearing =
false;
302 if (SUCCEEDED(factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing,
sizeof(allowTearing))))
303 supportsAllowTearing = allowTearing;
308 ID3D12Debug1 *debug =
nullptr;
309 if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(ID3D12Debug1),
reinterpret_cast<
void **>(&debug)))) {
310 qCDebug(QRHI_LOG_INFO,
"Enabling D3D12 debug layer");
311 debug->EnableDebugLayer();
312 if (gpuBasedValidation) {
313 qCDebug(QRHI_LOG_INFO,
"Enabling D3D12 GPU-based validation");
314 debug->SetEnableGPUBasedValidation(TRUE);
320 activeAdapter =
nullptr;
322 if (!importedDevice) {
323 IDXGIAdapter1 *adapter;
324 int requestedAdapterIndex = -1;
325 if (qEnvironmentVariableIsSet(
"QT_D3D_ADAPTER_INDEX"))
326 requestedAdapterIndex = qEnvironmentVariableIntValue(
"QT_D3D_ADAPTER_INDEX");
328 if (requestedRhiAdapter)
329 adapterLuid =
static_cast<QD3D12Adapter *>(requestedRhiAdapter)->luid;
332 if (requestedAdapterIndex < 0 && (adapterLuid.LowPart || adapterLuid.HighPart)) {
333 for (
int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
334 DXGI_ADAPTER_DESC1 desc;
335 adapter->GetDesc1(&desc);
337 if (desc.AdapterLuid.LowPart == adapterLuid.LowPart
338 && desc.AdapterLuid.HighPart == adapterLuid.HighPart)
340 requestedAdapterIndex = adapterIndex;
346 if (requestedAdapterIndex < 0 && flags.testFlag(QRhi::PreferSoftwareRenderer)) {
347 for (
int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
348 DXGI_ADAPTER_DESC1 desc;
349 adapter->GetDesc1(&desc);
351 if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) {
352 requestedAdapterIndex = adapterIndex;
358 for (
int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
359 DXGI_ADAPTER_DESC1 desc;
360 adapter->GetDesc1(&desc);
361 const QString name = QString::fromUtf16(
reinterpret_cast<
char16_t *>(desc.Description));
362 qCDebug(QRHI_LOG_INFO,
"Adapter %d: '%s' (vendor 0x%X device 0x%X flags 0x%X)",
368 if (!activeAdapter && (requestedAdapterIndex < 0 || requestedAdapterIndex == adapterIndex)) {
369 activeAdapter = adapter;
370 adapterLuid = desc.AdapterLuid;
371 QRhiD3D::fillDriverInfo(&driverInfoStruct, desc);
372 qCDebug(QRHI_LOG_INFO,
" using this adapter");
377 if (!activeAdapter) {
378 qWarning(
"No adapter");
382 if (minimumFeatureLevel == 0)
383 minimumFeatureLevel = MIN_FEATURE_LEVEL;
385 hr = D3D12CreateDevice(activeAdapter,
387 __uuidof(ID3D12Device2),
388 reinterpret_cast<
void **>(&dev));
390 qWarning(
"Failed to create D3D12 device: %s", qPrintable(QSystemError::windowsComString(hr)));
396 adapterLuid = dev->GetAdapterLuid();
397 IDXGIAdapter1 *adapter;
398 for (
int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
399 DXGI_ADAPTER_DESC1 desc;
400 adapter->GetDesc1(&desc);
401 if (desc.AdapterLuid.LowPart == adapterLuid.LowPart
402 && desc.AdapterLuid.HighPart == adapterLuid.HighPart)
404 activeAdapter = adapter;
405 QRhiD3D::fillDriverInfo(&driverInfoStruct, desc);
411 if (!activeAdapter) {
412 qWarning(
"No adapter");
415 qCDebug(QRHI_LOG_INFO,
"Using imported device %p", dev);
418 QDxgiVSyncService::instance()->refAdapter(adapterLuid);
421 ID3D12InfoQueue *infoQueue;
422 if (SUCCEEDED(dev->QueryInterface(__uuidof(ID3D12InfoQueue),
reinterpret_cast<
void **>(&infoQueue)))) {
423 if (qEnvironmentVariableIntValue(
"QT_D3D_DEBUG_BREAK")) {
424 infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION,
true);
425 infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR,
true);
426 infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING,
true);
428 D3D12_INFO_QUEUE_FILTER filter = {};
429 filter.DenyList.NumIDs = UINT(std::size(qd3d12_suppressed_messages));
430 filter.DenyList.pIDList = qd3d12_suppressed_messages;
433 D3D12_MESSAGE_SEVERITY infoSev = D3D12_MESSAGE_SEVERITY_INFO;
434 filter.DenyList.NumSeverities = 1;
435 filter.DenyList.pSeverityList = &infoSev;
436 infoQueue->PushStorageFilter(&filter);
437#ifdef QRHI_D3D12_INFOQUEUE1_AVAILABLE
442 if (SUCCEEDED(infoQueue->QueryInterface(__uuidof(ID3D12InfoQueue1),
reinterpret_cast<
void **>(&infoQueue1)))) {
447 if (SUCCEEDED(infoQueue1->RegisterMessageCallback(qd3d12_message_callback,
448 D3D12_MESSAGE_CALLBACK_IGNORE_FILTERS,
450 &infoQueueCallbackCookie)))
454 infoQueue1->SetMuteDebugOutput(
true);
456 infoQueue1->Release();
457 infoQueue1 =
nullptr;
461 infoQueue->Release();
465 if (!importedCommandQueue) {
466 D3D12_COMMAND_QUEUE_DESC queueDesc = {};
467 queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
468 queueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
469 hr = dev->CreateCommandQueue(&queueDesc, __uuidof(ID3D12CommandQueue),
reinterpret_cast<
void **>(&cmdQueue));
471 qWarning(
"Failed to create command queue: %s", qPrintable(QSystemError::windowsComString(hr)));
476 hr = dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence),
reinterpret_cast<
void **>(&fullFence));
478 qWarning(
"Failed to create fence: %s", qPrintable(QSystemError::windowsComString(hr)));
481 fullFenceEvent = CreateEvent(
nullptr, FALSE, FALSE,
nullptr);
482 fullFenceCounter = 0;
484 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
485 hr = dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
486 __uuidof(ID3D12CommandAllocator),
487 reinterpret_cast<
void **>(&cmdAllocators[i]));
489 qWarning(
"Failed to create command allocator: %s", qPrintable(QSystemError::windowsComString(hr)));
494 if (!vma.create(dev, activeAdapter)) {
495 qWarning(
"Failed to initialize graphics memory suballocator");
499 if (!rtvPool.create(dev, D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
"main RTV pool")) {
500 qWarning(
"Could not create RTV pool");
504 if (!dsvPool.create(dev, D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
"main DSV pool")) {
505 qWarning(
"Could not create DSV pool");
509 if (!cbvSrvUavPool.create(dev, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
"main CBV-SRV-UAV pool")) {
510 qWarning(
"Could not create CBV-SRV-UAV pool");
514 resourcePool.create(
"main resource pool");
515 pipelinePool.create(
"main pipeline pool");
516 rootSignaturePool.create(
"main root signature pool");
517 releaseQueue.create(&resourcePool, &pipelinePool, &rootSignaturePool);
518 barrierGen.create(&resourcePool);
520 if (!samplerMgr.create(dev)) {
521 qWarning(
"Could not create sampler pool and shader-visible sampler heap");
525 mipmapGen.create(
this);
526 mipmapGen3D.create(
this);
528 const qint32 smallStagingSize = aligned(SMALL_STAGING_AREA_BYTES_PER_FRAME_START, QD3D12StagingArea::ALIGNMENT);
529 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
530 if (!smallStagingAreas[i].create(
this, smallStagingSize, D3D12_HEAP_TYPE_UPLOAD)) {
531 qWarning(
"Could not create host-visible staging area");
534 QString decoratedName = QLatin1String(
"Small staging area buffer/");
535 decoratedName += QString::number(i);
536 smallStagingAreas[i].mem.buffer->SetName(
reinterpret_cast<LPCWSTR>(decoratedName.utf16()));
539 if (!shaderVisibleCbvSrvUavHeap.create(dev,
540 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
541 SHADER_VISIBLE_CBV_SRV_UAV_HEAP_PER_FRAME_START_SIZE))
543 qWarning(
"Could not create first shader-visible CBV/SRV/UAV heap");
547 if (flags.testFlag(QRhi::EnableTimestamps)) {
548 static bool wantsStablePowerState = qEnvironmentVariableIntValue(
"QT_D3D_STABLE_POWER_STATE");
564 if (wantsStablePowerState)
565 dev->SetStablePowerState(TRUE);
567 hr = cmdQueue->GetTimestampFrequency(×tampTicksPerSecond);
569 qWarning(
"Failed to query timestamp frequency: %s",
570 qPrintable(QSystemError::windowsComString(hr)));
573 if (!timestampQueryHeap.create(dev, QD3D12_FRAMES_IN_FLIGHT * 2, D3D12_QUERY_HEAP_TYPE_TIMESTAMP)) {
574 qWarning(
"Failed to create timestamp query pool");
577 const quint32 readbackBufSize = QD3D12_FRAMES_IN_FLIGHT * 2 *
sizeof(quint64);
578 if (!timestampReadbackArea.create(
this, readbackBufSize, D3D12_HEAP_TYPE_READBACK)) {
579 qWarning(
"Failed to create timestamp readback buffer");
582 timestampReadbackArea.mem.buffer->SetName(L"Timestamp readback buffer");
583 memset(timestampReadbackArea.mem.p, 0, readbackBufSize);
587 D3D12_FEATURE_DATA_D3D12_OPTIONS3 options3 = {};
588 if (SUCCEEDED(dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &options3,
sizeof(options3)))) {
589 caps.multiView = options3.ViewInstancingTier != D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED;
591 caps.textureViewFormat = options3.CastingFullyTypedFormatSupported;
594#ifdef QRHI_D3D12_CL5_AVAILABLE
595 D3D12_FEATURE_DATA_D3D12_OPTIONS6 options6 = {};
596 if (SUCCEEDED(dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS6, &options6,
sizeof(options6)))) {
597 caps.vrs = options6.VariableShadingRateTier != D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED;
598 caps.vrsMap = options6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2;
599 caps.vrsAdditionalRates = options6.AdditionalShadingRatesSupported;
600 shadingRateImageTileSize = options6.ShadingRateImageTileSize;
605 caps.vrsAdditionalRates =
false;
609 D3D12_INDIRECT_ARGUMENT_DESC arg = {};
610 arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
612 D3D12_COMMAND_SIGNATURE_DESC sigDesc = {};
613 sigDesc.ByteStride =
sizeof(D3D12_DRAW_ARGUMENTS);
614 sigDesc.NumArgumentDescs = 1;
615 sigDesc.pArgumentDescs = &arg;
617 hr = dev->CreateCommandSignature(&sigDesc,
nullptr, IID_PPV_ARGS(&drawCommandSignature));
619 qWarning(
"Failed to create draw command signature: %s", qPrintable(QSystemError::windowsComString(hr)));
625 D3D12_INDIRECT_ARGUMENT_DESC arg = {};
626 arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED;
628 D3D12_COMMAND_SIGNATURE_DESC sigDesc = {};
629 sigDesc.ByteStride =
sizeof(D3D12_DRAW_INDEXED_ARGUMENTS);
630 sigDesc.NumArgumentDescs = 1;
631 sigDesc.pArgumentDescs = &arg;
633 hr = dev->CreateCommandSignature(&sigDesc,
nullptr, IID_PPV_ARGS(&drawIndexedCommandSignature));
635 qWarning(
"Failed to create draw indexed command signature: %s", qPrintable(QSystemError::windowsComString(hr)));
641 D3D12_INDIRECT_ARGUMENT_DESC arg = {};
642 arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
644 D3D12_COMMAND_SIGNATURE_DESC sigDesc = {};
645 sigDesc.ByteStride =
sizeof(D3D12_DISPATCH_ARGUMENTS);
646 sigDesc.NumArgumentDescs = 1;
647 sigDesc.pArgumentDescs = &arg;
649 hr = dev->CreateCommandSignature(&sigDesc,
nullptr, IID_PPV_ARGS(&dispatchCommandSignature));
651 qWarning(
"Failed to create dispatch command signature: %s", qPrintable(QSystemError::windowsComString(hr)));
657 offscreenActive =
false;
659 nativeHandlesStruct.dev = dev;
660 nativeHandlesStruct.minimumFeatureLevel = minimumFeatureLevel;
661 nativeHandlesStruct.adapterLuidLow = adapterLuid.LowPart;
662 nativeHandlesStruct.adapterLuidHigh = adapterLuid.HighPart;
663 nativeHandlesStruct.commandQueue = cmdQueue;
668void QRhiD3D12::destroy()
670 if (!deviceLost && fullFence && fullFenceEvent)
673 releaseQueue.releaseAll();
675 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
676 if (offscreenCb[i]) {
677 if (offscreenCb[i]->cmdList)
678 offscreenCb[i]->cmdList->Release();
679 delete offscreenCb[i];
680 offscreenCb[i] =
nullptr;
684 timestampQueryHeap.destroy();
685 timestampReadbackArea.destroy();
687 shaderVisibleCbvSrvUavHeap.destroy();
689 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i)
690 smallStagingAreas[i].destroy();
693 mipmapGen3D.destroy();
694 samplerMgr.destroy();
695 resourcePool.destroy();
696 pipelinePool.destroy();
697 rootSignaturePool.destroy();
700 cbvSrvUavPool.destroy();
702 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
703 if (cmdAllocators[i]) {
704 cmdAllocators[i]->Release();
705 cmdAllocators[i] =
nullptr;
709 if (fullFenceEvent) {
710 CloseHandle(fullFenceEvent);
711 fullFenceEvent =
nullptr;
715 fullFence->Release();
719 if (!importedCommandQueue) {
728#ifdef QRHI_D3D12_INFOQUEUE1_AVAILABLE
730 infoQueue1->UnregisterMessageCallback(infoQueueCallbackCookie);
731 infoQueue1->Release();
732 infoQueue1 =
nullptr;
733 infoQueueCallbackCookie = 0;
737 if (!importedDevice) {
745 dcompDevice->Release();
746 dcompDevice =
nullptr;
750 activeAdapter->Release();
751 activeAdapter =
nullptr;
755 dxgiFactory->Release();
756 dxgiFactory =
nullptr;
759 QDxgiVSyncService::instance()->derefAdapter(adapterLuid);
762 importedDevice =
false;
763 importedCommandQueue =
false;
765 if (drawCommandSignature) {
766 drawCommandSignature->Release();
767 drawCommandSignature =
nullptr;
770 if (drawIndexedCommandSignature) {
771 drawIndexedCommandSignature->Release();
772 drawIndexedCommandSignature =
nullptr;
775 if (dispatchCommandSignature) {
776 dispatchCommandSignature->Release();
777 dispatchCommandSignature =
nullptr;
780 for (ID3D12CommandSignature *sig : std::as_const(drawCommandSignaturesByStride))
782 drawCommandSignaturesByStride.clear();
784 for (ID3D12CommandSignature *sig : std::as_const(drawIndexedCommandSignaturesByStride))
786 drawIndexedCommandSignaturesByStride.clear();
788 destroyPipelineLibrary();
791QRhi::AdapterList QRhiD3D12::enumerateAdaptersBeforeCreate(QRhiNativeHandles *nativeHandles)
const
793 LUID requestedLuid = {};
795 QRhiD3D12NativeHandles *h =
static_cast<QRhiD3D12NativeHandles *>(nativeHandles);
796 const LUID adapterLuid = { h->adapterLuidLow, h->adapterLuidHigh };
797 if (adapterLuid.LowPart || adapterLuid.HighPart)
798 requestedLuid = adapterLuid;
801 IDXGIFactory2 *dxgi =
nullptr;
802 if (FAILED(CreateDXGIFactory2(0, __uuidof(IDXGIFactory2),
reinterpret_cast<
void **>(&dxgi))))
805 QRhi::AdapterList list;
806 IDXGIAdapter1 *adapter;
807 for (
int adapterIndex = 0; dxgi->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
808 DXGI_ADAPTER_DESC1 desc;
809 adapter->GetDesc1(&desc);
811 if (requestedLuid.LowPart || requestedLuid.HighPart) {
812 if (desc.AdapterLuid.LowPart != requestedLuid.LowPart
813 || desc.AdapterLuid.HighPart != requestedLuid.HighPart)
818 QD3D12Adapter *a =
new QD3D12Adapter;
819 a->luid = desc.AdapterLuid;
820 QRhiD3D::fillDriverInfo(&a->adapterInfo, desc);
828QRhiDriverInfo QD3D12Adapter::info()
const
833QList<
int> QRhiD3D12::supportedSampleCounts()
const
835 return { 1, 2, 4, 8 };
838QList<QSize> QRhiD3D12::supportedShadingRates(
int sampleCount)
const
841 switch (sampleCount) {
844 if (caps.vrsAdditionalRates) {
845 sizes.append(QSize(4, 4));
846 sizes.append(QSize(4, 2));
847 sizes.append(QSize(2, 4));
849 sizes.append(QSize(2, 2));
850 sizes.append(QSize(2, 1));
851 sizes.append(QSize(1, 2));
854 if (caps.vrsAdditionalRates)
855 sizes.append(QSize(2, 4));
856 sizes.append(QSize(2, 2));
857 sizes.append(QSize(2, 1));
858 sizes.append(QSize(1, 2));
861 sizes.append(QSize(2, 2));
862 sizes.append(QSize(2, 1));
863 sizes.append(QSize(1, 2));
868 sizes.append(QSize(1, 1));
872QRhiSwapChain *QRhiD3D12::createSwapChain()
874 return new QD3D12SwapChain(
this);
877QRhiBuffer *QRhiD3D12::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
879 return new QD3D12Buffer(
this, type, usage, size);
882int QRhiD3D12::ubufAlignment()
const
884 return D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT;
887bool QRhiD3D12::isYUpInFramebuffer()
const
892bool QRhiD3D12::isYUpInNDC()
const
897bool QRhiD3D12::isClipDepthZeroToOne()
const
902QMatrix4x4 QRhiD3D12::clipSpaceCorrMatrix()
const
907 static constexpr QMatrix4x4 m(1.0f, 0.0f, 0.0f, 0.0f,
908 0.0f, 1.0f, 0.0f, 0.0f,
909 0.0f, 0.0f, 0.5f, 0.5f,
910 0.0f, 0.0f, 0.0f, 1.0f);
914bool QRhiD3D12::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags)
const
918 if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ASTC_12x12)
924bool QRhiD3D12::isFeatureSupported(QRhi::Feature feature)
const
927 case QRhi::MultisampleTexture:
929 case QRhi::MultisampleRenderBuffer:
931 case QRhi::DebugMarkers:
932#ifdef QRHI_D3D12_HAS_OLD_PIX
937 case QRhi::Timestamps:
939 case QRhi::Instancing:
941 case QRhi::CustomInstanceStepRate:
943 case QRhi::PrimitiveRestart:
945 case QRhi::NonDynamicUniformBuffers:
947 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
949 case QRhi::NPOTTextureRepeat:
951 case QRhi::RedOrAlpha8IsRed:
953 case QRhi::ElementIndexUint:
957 case QRhi::FragmentStoresAndAtomics:
959 case QRhi::WideLines:
961 case QRhi::VertexShaderPointSize:
963 case QRhi::BaseVertex:
965 case QRhi::BaseInstance:
967 case QRhi::TriangleFanTopology:
969 case QRhi::ReadBackNonUniformBuffer:
971 case QRhi::ReadBackNonBaseMipLevel:
973 case QRhi::TexelFetch:
975 case QRhi::RenderToNonBaseMipLevel:
977 case QRhi::IntAttributes:
979 case QRhi::ScreenSpaceDerivatives:
981 case QRhi::ReadBackAnyTextureFormat:
983 case QRhi::PipelineCacheDataLoadSave:
984#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
989 case QRhi::ImageDataStride:
991 case QRhi::RenderBufferImport:
993 case QRhi::ThreeDimensionalTextures:
995 case QRhi::RenderTo3DTextureSlice:
997 case QRhi::TextureArrays:
999 case QRhi::Tessellation:
1001 case QRhi::GeometryShader:
1003 case QRhi::TextureArrayRange:
1005 case QRhi::NonFillPolygonMode:
1007 case QRhi::OneDimensionalTextures:
1009 case QRhi::OneDimensionalTextureMipmaps:
1011 case QRhi::HalfAttributes:
1013 case QRhi::RenderToOneDimensionalTexture:
1015 case QRhi::ThreeDimensionalTextureMipmaps:
1017 case QRhi::MultiView:
1018 return caps.multiView;
1019 case QRhi::TextureViewFormat:
1020 return caps.textureViewFormat;
1021 case QRhi::ResolveDepthStencil:
1025 case QRhi::VariableRateShading:
1027 case QRhi::VariableRateShadingMap:
1028 case QRhi::VariableRateShadingMapWithTexture:
1030 case QRhi::DualSourceBlend:
1031 case QRhi::PerRenderTargetBlending:
1032 case QRhi::SampleVariables:
1034 case QRhi::InstanceIndexIncludesBaseInstance:
1036 case QRhi::DepthClamp:
1038 case QRhi::DrawIndirect:
1039 case QRhi::BaseInstanceIndirect:
1040 return drawCommandSignature !=
nullptr && drawIndexedCommandSignature !=
nullptr;
1041 case QRhi::DrawIndirectMulti:
1042 return drawCommandSignature !=
nullptr && drawIndexedCommandSignature !=
nullptr;
1043 case QRhi::ShaderDrawParameters:
1045 case QRhi::DispatchIndirect:
1046 return dispatchCommandSignature !=
nullptr;
1047 case QRhi::PushConstants:
1049 case QRhi::DrawIndirectCount:
1051 return drawCommandSignature !=
nullptr && drawIndexedCommandSignature !=
nullptr;
1052 case QRhi::BufferToBufferCopy:
1054 case QRhi::StaticBuffersOnGpuTimeline:
1060int QRhiD3D12::resourceLimit(QRhi::ResourceLimit limit)
const
1063 case QRhi::TextureSizeMin:
1065 case QRhi::TextureSizeMax:
1067 case QRhi::MaxColorAttachments:
1069 case QRhi::FramesInFlight:
1070 return QD3D12_FRAMES_IN_FLIGHT;
1071 case QRhi::MaxAsyncReadbackFrames:
1072 return QD3D12_FRAMES_IN_FLIGHT;
1073 case QRhi::MaxThreadGroupsPerDimension:
1075 case QRhi::MaxThreadsPerThreadGroup:
1077 case QRhi::MaxThreadGroupX:
1079 case QRhi::MaxThreadGroupY:
1081 case QRhi::MaxThreadGroupZ:
1083 case QRhi::TextureArraySizeMax:
1085 case QRhi::MaxUniformBufferRange:
1087 case QRhi::MaxVertexInputs:
1089 case QRhi::MaxVertexOutputs:
1091 case QRhi::MaxPushConstantsSize:
1093 case QRhi::MaxVertexStorageBuffers:
1094 case QRhi::MaxFragmentStorageBuffers:
1096 case QRhi::MaxStorageBufferBindings:
1097 case QRhi::MaxStorageImageBindings:
1099 case QRhi::ShadingRateImageTileSize:
1100 return shadingRateImageTileSize;
1105const QRhiNativeHandles *QRhiD3D12::nativeHandles()
1107 return &nativeHandlesStruct;
1110QRhiDriverInfo QRhiD3D12::driverInfo()
const
1112 return driverInfoStruct;
1115QRhiStats QRhiD3D12::statistics()
1118 result.totalPipelineCreationTime = totalPipelineCreationTime();
1120 D3D12MA::Budget budgets[2];
1121 vma.getBudget(&budgets[0], &budgets[1]);
1122 for (
int i = 0; i < 2; ++i) {
1123 const D3D12MA::Statistics &stats(budgets[i].Stats);
1124 result.blockCount += stats.BlockCount;
1125 result.allocCount += stats.AllocationCount;
1126 result.usedBytes += stats.AllocationBytes;
1127 result.unusedBytes += stats.BlockBytes - stats.AllocationBytes;
1128 result.totalUsageBytes += budgets[i].UsageBytes;
1134bool QRhiD3D12::makeThreadLocalNativeContextCurrent()
1140void QRhiD3D12::setQueueSubmitParams(QRhiNativeHandles *)
1145void QRhiD3D12::releaseCachedResources()
1147 shaderBytecodeCache.clear();
1156static inline void addToKey(QCryptographicHash *h,
const void *p, size_t size)
1158 h->addData(QByteArrayView(
static_cast<
const char *>(p), qsizetype(size)));
1162static inline void addToKey(QCryptographicHash *h,
const T &v)
1164 addToKey(h, &v,
sizeof(T));
1167static inline void addToKey(QCryptographicHash *h,
const QByteArray &b)
1169 const quint32 size = quint32(b.size());
1174static inline void addToKey(QCryptographicHash *h,
const QVector<quint32> &v)
1176 const quint32 count = quint32(v.count());
1178 addToKey(h, v.constData(), v.count() *
sizeof(quint32));
1181bool QRhiD3D12::createPipelineLibrary(
const QByteArray &blob)
1183#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1184 destroyPipelineLibrary();
1186 pipelineLibraryBlob = blob;
1187 HRESULT hr = dev->CreatePipelineLibrary(pipelineLibraryBlob.isEmpty() ?
nullptr
1188 : pipelineLibraryBlob.constData(),
1189 SIZE_T(pipelineLibraryBlob.size()),
1190 __uuidof(ID3D12PipelineLibrary1),
1191 reinterpret_cast<
void **>(&pipelineLibrary));
1197 qCDebug(QRHI_LOG_INFO,
"Failed to create pipeline library: %s",
1198 qPrintable(QSystemError::windowsComString(hr)));
1199 pipelineLibrary =
nullptr;
1200 pipelineLibraryBlob.clear();
1210bool QRhiD3D12::ensurePipelineLibrary()
1212#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1213 if (pipelineLibrary)
1215 if (!rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
1217 return createPipelineLibrary(QByteArray());
1223void QRhiD3D12::destroyPipelineLibrary()
1225#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1226 if (pipelineLibrary) {
1227 pipelineLibrary->Release();
1228 pipelineLibrary =
nullptr;
1230 pipelineLibraryBlob.clear();
1231 pipelineLibraryNames.clear();
1235ID3D12PipelineState *QRhiD3D12::loadOrCreatePipelineState(
const D3D12_PIPELINE_STATE_STREAM_DESC *streamDesc,
1236 const QByteArray &cacheKey,
1239 ID3D12PipelineState *pso =
nullptr;
1241#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1242 QVarLengthArray<
wchar_t, 64> name;
1243 if (ensurePipelineLibrary() && !cacheKey.isEmpty()) {
1244 name.resize(cacheKey.size() + 1);
1245 for (qsizetype i = 0; i < cacheKey.size(); ++i)
1246 name[i] =
wchar_t(cacheKey.at(i));
1247 name[cacheKey.size()] = 0;
1248 HRESULT hr = pipelineLibrary->LoadPipeline(name.constData(),
1250 __uuidof(ID3D12PipelineState),
1251 reinterpret_cast<
void **>(&pso));
1257 HRESULT hr = dev->CreatePipelineState(streamDesc,
1258 __uuidof(ID3D12PipelineState),
1259 reinterpret_cast<
void **>(&pso));
1261 qWarning(
"Failed to create %s pipeline state: %s",
1262 what, qPrintable(QSystemError::windowsComString(hr)));
1266#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1267 if (pipelineLibrary && !name.isEmpty() && !pipelineLibraryNames.contains(cacheKey)) {
1268 if (SUCCEEDED(pipelineLibrary->StorePipeline(name.constData(), pso)))
1269 pipelineLibraryNames.insert(cacheKey);
1276struct QD3D12PipelineCacheDataHeader
1284 quint64 adapterLuid;
1287QByteArray QRhiD3D12::pipelineCacheData()
1289 static_assert(
sizeof(QD3D12PipelineCacheDataHeader) == 32);
1292#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1293 if (!pipelineLibrary || !rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
1296 const SIZE_T dataSize = pipelineLibrary->GetSerializedSize();
1300 const size_t headerSize =
sizeof(QD3D12PipelineCacheDataHeader);
1301 data.resize(qsizetype(headerSize + dataSize));
1302 HRESULT hr = pipelineLibrary->Serialize(data.data() + headerSize, dataSize);
1304 qCDebug(QRHI_LOG_INFO,
"Failed to serialize pipeline library: %s",
1305 qPrintable(QSystemError::windowsComString(hr)));
1306 return QByteArray();
1309 QD3D12PipelineCacheDataHeader header = {};
1310 header.rhiId = pipelineCacheRhiId();
1311 header.arch = quint32(
sizeof(
void *));
1312 header.dataSize = quint32(dataSize);
1313 header.vendorId = quint32(driverInfoStruct.vendorId);
1314 header.deviceId = quint32(driverInfoStruct.deviceId);
1315 header.adapterLuid = (quint64(quint32(adapterLuid.HighPart)) << 32) | quint64(adapterLuid.LowPart);
1316 memcpy(data.data(), &header, headerSize);
1321void QRhiD3D12::setPipelineCacheData(
const QByteArray &data)
1323#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1327 const size_t headerSize =
sizeof(QD3D12PipelineCacheDataHeader);
1328 if (data.size() < qsizetype(headerSize)) {
1329 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob size");
1332 QD3D12PipelineCacheDataHeader header;
1333 memcpy(&header, data.constData(), headerSize);
1335 const quint32 rhiId = pipelineCacheRhiId();
1336 if (header.rhiId != rhiId) {
1337 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: The data is for a different QRhi version or backend (%u, %u)",
1338 rhiId, header.rhiId);
1341 const quint32 arch = quint32(
sizeof(
void *));
1342 if (header.arch != arch) {
1343 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Architecture does not match (%u, %u)",
1347 if (header.vendorId != quint32(driverInfoStruct.vendorId)) {
1348 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: vendorId does not match (%u, %u)",
1349 quint32(driverInfoStruct.vendorId), header.vendorId);
1352 if (header.deviceId != quint32(driverInfoStruct.deviceId)) {
1353 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: deviceId does not match (%u, %u)",
1354 quint32(driverInfoStruct.deviceId), header.deviceId);
1357 const quint64 luid = (quint64(quint32(adapterLuid.HighPart)) << 32) | quint64(adapterLuid.LowPart);
1358 if (header.adapterLuid != luid) {
1359 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: adapter LUID does not match");
1362 if (quint64(data.size()) < quint64(headerSize) + header.dataSize) {
1363 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob, data missing");
1370 if (createPipelineLibrary(data.mid(qsizetype(headerSize)))) {
1371 qCDebug(QRHI_LOG_INFO,
"Created pipeline library with initial data of %u bytes",
1379bool QRhiD3D12::isDeviceLost()
const
1384QRhiRenderBuffer *QRhiD3D12::createRenderBuffer(QRhiRenderBuffer::Type type,
const QSize &pixelSize,
1385 int sampleCount, QRhiRenderBuffer::Flags flags,
1386 QRhiTexture::Format backingFormatHint)
1388 return new QD3D12RenderBuffer(
this, type, pixelSize, sampleCount, flags, backingFormatHint);
1391QRhiTexture *QRhiD3D12::createTexture(QRhiTexture::Format format,
1392 const QSize &pixelSize,
int depth,
int arraySize,
1393 int sampleCount, QRhiTexture::Flags flags)
1395 return new QD3D12Texture(
this, format, pixelSize, depth, arraySize, sampleCount, flags);
1398QRhiSampler *QRhiD3D12::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
1399 QRhiSampler::Filter mipmapMode,
1400 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
1402 return new QD3D12Sampler(
this, magFilter, minFilter, mipmapMode, u, v, w);
1405QRhiTextureRenderTarget *QRhiD3D12::createTextureRenderTarget(
const QRhiTextureRenderTargetDescription &desc,
1406 QRhiTextureRenderTarget::Flags flags)
1408 return new QD3D12TextureRenderTarget(
this, desc, flags);
1411QRhiShadingRateMap *QRhiD3D12::createShadingRateMap()
1413 return new QD3D12ShadingRateMap(
this);
1416QRhiGraphicsPipeline *QRhiD3D12::createGraphicsPipeline()
1418 return new QD3D12GraphicsPipeline(
this);
1421QRhiComputePipeline *QRhiD3D12::createComputePipeline()
1423 return new QD3D12ComputePipeline(
this);
1426QRhiShaderResourceBindings *QRhiD3D12::createShaderResourceBindings()
1428 return new QD3D12ShaderResourceBindings(
this);
1431void QRhiD3D12::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps)
1433 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
1434 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
1435 QD3D12GraphicsPipeline *psD = QRHI_RES(QD3D12GraphicsPipeline, ps);
1436 const bool pipelineChanged = cbD->currentGraphicsPipeline != psD || cbD->currentPipelineGeneration != psD->generation;
1438 if (pipelineChanged) {
1439 cbD->currentGraphicsPipeline = psD;
1440 cbD->currentComputePipeline =
nullptr;
1441 cbD->currentPipelineGeneration = psD->generation;
1443 if (QD3D12Pipeline *pipeline = pipelinePool.lookupRef(psD->handle)) {
1444 Q_ASSERT(pipeline->type == QD3D12Pipeline::Graphics);
1445 cbD->cmdList->SetPipelineState(pipeline->pso);
1446 if (QD3D12RootSignature *rs = rootSignaturePool.lookupRef(psD->rootSigHandle))
1447 cbD->cmdList->SetGraphicsRootSignature(rs->rootSig);
1450 cbD->cmdList->IASetPrimitiveTopology(psD->topology);
1452 if (psD->viewInstanceMask)
1453 cbD->cmdList->SetViewInstanceMask(psD->viewInstanceMask);
1455 if (cbD->hasCustomScissorSet && !psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor))
1456 setDefaultScissor(cbD);
1458 if (psD->m_stencilTest) {
1459 const quint32 ref = psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)
1460 ? cbD->currentStencilRef : 0;
1461 if (cbD->appliedStencilRef != ref) {
1462 cbD->cmdList->OMSetStencilRef(ref);
1463 cbD->appliedStencilRef = ref;
1469void QD3D12ShaderResourceBindings::cacheUniformBuffer(QD3D12Stage s,
1470 const QRhiShaderResourceBinding::Data::UniformBufferData &d,
1477 bindingCache.cbufs[s].append({ QRHI_RES(QD3D12Buffer, d.buf), d.offset, binding });
1480void QD3D12ShaderResourceBindings::cacheTextures(QD3D12Stage s,
1481 const QRhiShaderResourceBinding::TextureAndSampler *d,
1485 for (
int i = 0; i < count; ++i) {
1486 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, d[i].tex);
1487 bindingCache.srvs[s].append(texD->srv.cpuHandle);
1491void QD3D12ShaderResourceBindings::cacheSamplers(QD3D12Stage s,
1492 const QRhiShaderResourceBinding::TextureAndSampler *d,
1497 QD3D12Sampler *samplerD = QRHI_RES(QD3D12Sampler, d[0].sampler);
1498 bindingCache.samplers[s].append(samplerD->lookupOrCreateShaderVisibleDescriptor().gpuHandle);
1506 QRHI_RES_RHI(QRhiD3D12);
1507 QVarLengthArray<Q_D3D12_SAMPLER_DESC, 8> descs;
1508 for (
int i = 0; i < count; ++i)
1509 descs.append({ QRHI_RES(QD3D12Sampler, d[i].sampler)->desc });
1510 bindingCache.samplers[s].append(rhiD->samplerMgr.getShaderVisibleDescriptors(descs).gpuHandle);
1513void QD3D12ShaderResourceBindings::cacheStorageBuffer(QD3D12Stage s,
1514 const QRhiShaderResourceBinding::Data::StorageBufferData &d,
1515 QD3D12ShaderResourceVisitor::StorageOp,
1518 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, d.buf);
1520 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
1521 uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
1522 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
1523 uavDesc.Buffer.FirstElement = d.offset / 4;
1524 uavDesc.Buffer.NumElements = aligned(bufD->m_size - d.offset, 4u) / 4;
1525 uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
1526 bindingCache.uavs[s].append({ bufD->handles[0], uavDesc });
1529void QD3D12ShaderResourceBindings::cacheStorageImage(QD3D12Stage s,
1530 const QRhiShaderResourceBinding::Data::StorageImageData &d,
1531 QD3D12ShaderResourceVisitor::StorageOp,
1534 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, d.tex);
1535 const bool isCube = texD->m_flags.testFlag(QRhiTexture::CubeMap);
1536 const bool isArray = texD->m_flags.testFlag(QRhiTexture::TextureArray);
1537 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
1538 const bool is1D = texD->m_flags.testFlag(QRhiTexture::OneDimensional);
1539 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
1540 uavDesc.Format = texD->rtFormat;
1542 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
1543 uavDesc.Texture2DArray.MipSlice = UINT(d.level);
1544 uavDesc.Texture2DArray.FirstArraySlice = 0;
1545 uavDesc.Texture2DArray.ArraySize = 6;
1546 }
else if (isArray && is1D) {
1547 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
1548 uavDesc.Texture1DArray.MipSlice = UINT(d.level);
1549 uavDesc.Texture1DArray.FirstArraySlice = 0;
1550 uavDesc.Texture1DArray.ArraySize = UINT(qMax(0, texD->m_arraySize));
1552 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
1553 uavDesc.Texture1D.MipSlice = UINT(d.level);
1554 }
else if (isArray) {
1555 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
1556 uavDesc.Texture2DArray.MipSlice = UINT(d.level);
1557 uavDesc.Texture2DArray.FirstArraySlice = 0;
1558 uavDesc.Texture2DArray.ArraySize = UINT(qMax(0, texD->m_arraySize));
1560 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
1561 uavDesc.Texture3D.MipSlice = UINT(d.level);
1562 uavDesc.Texture3D.WSize = UINT(-1);
1564 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
1565 uavDesc.Texture2D.MipSlice = UINT(d.level);
1567 bindingCache.uavs[s].append({ texD->handle, uavDesc });
1570void QD3D12ShaderResourceBindings::rebuildBindingCache(
const QD3D12ShaderStageData *stageData,
1573 bindingCache.reset();
1575 QD3D12ShaderResourceVisitor visitor(
this, stageData, stageCount);
1577 using namespace std::placeholders;
1578 visitor.uniformBuffer = std::bind(&QD3D12ShaderResourceBindings::cacheUniformBuffer,
this, _1, _2, _3, _4);
1579 visitor.textures = std::bind(&QD3D12ShaderResourceBindings::cacheTextures,
this, _1, _2, _3, _4);
1580 visitor.samplers = std::bind(&QD3D12ShaderResourceBindings::cacheSamplers,
this, _1, _2, _3, _4);
1581 visitor.storageBuffer = std::bind(&QD3D12ShaderResourceBindings::cacheStorageBuffer,
this, _1, _2, _3, _4);
1582 visitor.storageImage = std::bind(&QD3D12ShaderResourceBindings::cacheStorageImage,
this, _1, _2, _3, _4);
1587 for (
int s = 0; s < 6; ++s) {
1588 bindingCache.srvUavCount += bindingCache.srvs[s].count();
1589 bindingCache.srvUavCount += bindingCache.uavs[s].count();
1592 bindingCacheValid =
true;
1593 bindingCacheGeneration = generation;
1596void QRhiD3D12::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb,
1597 int dynamicOffsetCount,
1598 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
1600 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
1601 Q_ASSERT(cbD->recordingPass != QD3D12CommandBuffer::NoPass);
1602 QD3D12GraphicsPipeline *gfxPsD = QRHI_RES(QD3D12GraphicsPipeline, cbD->currentGraphicsPipeline);
1603 QD3D12ComputePipeline *compPsD = QRHI_RES(QD3D12ComputePipeline, cbD->currentComputePipeline);
1607 srb = gfxPsD->m_shaderResourceBindings;
1609 srb = compPsD->m_shaderResourceBindings;
1612 QD3D12ShaderResourceBindings *srbD = QRHI_RES(QD3D12ShaderResourceBindings, srb);
1614 bool pipelineChanged =
false;
1616 pipelineChanged = srbD->lastUsedGraphicsPipeline != gfxPsD
1617 || srbD->lastUsedPipelineGeneration != gfxPsD->generation;
1618 srbD->lastUsedGraphicsPipeline = gfxPsD;
1619 srbD->lastUsedComputePipeline =
nullptr;
1620 srbD->lastUsedPipelineGeneration = gfxPsD->generation;
1622 pipelineChanged = srbD->lastUsedComputePipeline != compPsD
1623 || srbD->lastUsedPipelineGeneration != compPsD->generation;
1624 srbD->lastUsedGraphicsPipeline =
nullptr;
1625 srbD->lastUsedComputePipeline = compPsD;
1626 srbD->lastUsedPipelineGeneration = compPsD->generation;
1629 bool srbUpdate =
false;
1631 for (
int i = 0, ie = srbD->m_bindings.size(); i != ie; ++i) {
1632 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->m_bindings[i]);
1633 QD3D12ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
1634 switch (b->type()) {
1635 case QRhiShaderResourceBinding::UniformBuffer:
1637 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, b->ubuf().buf);
1638 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
1639 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
1640 sanityCheckResourceOwnership(bufD);
1641 bufD->executeHostWritesForFrameSlot(currentFrameSlot);
1642 if (bufD->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
1644 bd.ubuf.id = bufD->m_id;
1645 bd.ubuf.generation = bufD->generation;
1649 case QRhiShaderResourceBinding::SampledTexture:
1650 case QRhiShaderResourceBinding::Texture:
1651 case QRhiShaderResourceBinding::Sampler:
1653 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
1654 if (bd.stex.d.size() != data->count()) {
1655 bd.stex.d.resize(data->count());
1658 for (
int elem = 0; elem < data->count(); ++elem) {
1659 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, data->texSamplers[elem].tex);
1660 QD3D12Sampler *samplerD = QRHI_RES(QD3D12Sampler, data->texSamplers[elem].sampler);
1664 Q_ASSERT(texD || samplerD);
1665 sanityCheckResourceOwnership(texD);
1666 sanityCheckResourceOwnership(samplerD);
1667 const quint64 texId = texD ? texD->m_id : 0;
1668 const uint texGen = texD ? texD->generation : 0;
1669 const quint64 samplerId = samplerD ? samplerD->m_id : 0;
1670 const uint samplerGen = samplerD ? samplerD->generation : 0;
1671 if (texId != bd.stex.d[elem].texId || texGen != bd.stex.d[elem].texGeneration
1672 || samplerId != bd.stex.d[elem].samplerId
1673 || samplerGen != bd.stex.d[elem].samplerGeneration)
1676 bd.stex.d[elem].texId = texId;
1677 bd.stex.d[elem].texGeneration = texGen;
1678 bd.stex.d[elem].samplerId = samplerId;
1679 bd.stex.d[elem].samplerGeneration = samplerGen;
1683 if (b->stage == QRhiShaderResourceBinding::FragmentStage) {
1684 state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
1685 }
else if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
1686 state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1688 state = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1690 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATES(state));
1695 case QRhiShaderResourceBinding::ImageLoad:
1696 case QRhiShaderResourceBinding::ImageStore:
1697 case QRhiShaderResourceBinding::ImageLoadStore:
1699 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, b->simage().tex);
1700 sanityCheckResourceOwnership(texD);
1701 if (texD->generation != bd.simage.generation || texD->m_id != bd.simage.id) {
1703 bd.simage.id = texD->m_id;
1704 bd.simage.generation = texD->generation;
1706 if (QD3D12Resource *res = resourcePool.lookupRef(texD->handle)) {
1707 if (res->uavUsage) {
1708 if (res->uavUsage & QD3D12Resource::UavUsageWrite) {
1710 barrierGen.enqueueUavBarrier(cbD, texD->handle);
1712 if (b->type() == QRhiShaderResourceBinding::ImageStore
1713 || b->type() == QRhiShaderResourceBinding::ImageLoadStore)
1716 barrierGen.enqueueUavBarrier(cbD, texD->handle);
1721 if (b->type() == QRhiShaderResourceBinding::ImageLoad || b->type() == QRhiShaderResourceBinding::ImageLoadStore)
1722 res->uavUsage |= QD3D12Resource::UavUsageRead;
1723 if (b->type() == QRhiShaderResourceBinding::ImageStore || b->type() == QRhiShaderResourceBinding::ImageLoadStore)
1724 res->uavUsage |= QD3D12Resource::UavUsageWrite;
1725 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
1729 case QRhiShaderResourceBinding::BufferLoad:
1730 case QRhiShaderResourceBinding::BufferStore:
1731 case QRhiShaderResourceBinding::BufferLoadStore:
1733 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, b->sbuf().buf);
1734 sanityCheckResourceOwnership(bufD);
1735 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::StorageBuffer));
1736 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
1737 if (bufD->generation != bd.sbuf.generation || bufD->m_id != bd.sbuf.id) {
1739 bd.sbuf.id = bufD->m_id;
1740 bd.sbuf.generation = bufD->generation;
1742 if (QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[0])) {
1743 if (res->uavUsage) {
1744 if (res->uavUsage & QD3D12Resource::UavUsageWrite) {
1746 barrierGen.enqueueUavBarrier(cbD, bufD->handles[0]);
1748 if (b->type() == QRhiShaderResourceBinding::BufferStore
1749 || b->type() == QRhiShaderResourceBinding::BufferLoadStore)
1752 barrierGen.enqueueUavBarrier(cbD, bufD->handles[0]);
1757 if (b->type() == QRhiShaderResourceBinding::BufferLoad || b->type() == QRhiShaderResourceBinding::BufferLoadStore)
1758 res->uavUsage |= QD3D12Resource::UavUsageRead;
1759 if (b->type() == QRhiShaderResourceBinding::BufferStore || b->type() == QRhiShaderResourceBinding::BufferLoadStore)
1760 res->uavUsage |= QD3D12Resource::UavUsageWrite;
1761 barrierGen.addTransitionBarrier(bufD->handles[0], D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
1768 const bool srbChanged = gfxPsD ? (cbD->currentGraphicsSrb != srb) : (cbD->currentComputeSrb != srb);
1769 const bool srbRebuilt = cbD->currentSrbGeneration != srbD->generation;
1777 barrierGen.enqueueBufferedTransitionBarriers(cbD);
1783 if (pipelineChanged || srbUpdate || !srbD->bindingCacheValid
1784 || srbD->bindingCacheGeneration != srbD->generation)
1786 const QD3D12ShaderStageData *stageData = gfxPsD ? gfxPsD->stageData.data() : &compPsD->stageData;
1787 srbD->rebuildBindingCache(stageData, gfxPsD ? 5 : 1);
1790 if (pipelineChanged || srbChanged || srbRebuilt || srbUpdate || srbD->hasDynamicOffset) {
1795 const QD3D12ShaderResourceBindings::BindingCache &cache(srbD->bindingCache);
1797 bool gotNewHeap =
false;
1798 if (!ensureShaderVisibleDescriptorHeapCapacity(&shaderVisibleCbvSrvUavHeap,
1799 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
1807 qCDebug(QRHI_LOG_INFO,
"Created new shader-visible CBV/SRV/UAV descriptor heap,"
1808 " per-frame slice size is now %u,"
1809 " if this happens frequently then that's not great.",
1810 shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[0].capacity);
1811 bindShaderVisibleHeaps(cbD);
1814 int rootParamIndex = 0;
1815 for (
int s = 0; s < 6; ++s) {
1816 for (
const QD3D12ShaderResourceBindings::BindingCache::CBuf &cbuf : cache.cbufs[s]) {
1817 if (QD3D12Resource *res = resourcePool.lookupRef(cbuf.buf->handles[currentFrameSlot])) {
1818 quint32 offset = cbuf.offset;
1819 if (srbD->hasDynamicOffset) {
1820 for (
int i = 0; i < dynamicOffsetCount; ++i) {
1821 const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]);
1822 if (dynOfs.first == cbuf.binding) {
1823 Q_ASSERT(aligned(dynOfs.second, 256u) == dynOfs.second);
1824 offset += dynOfs.second;
1828 const D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = res->resource->GetGPUVirtualAddress() + offset;
1830 cbD->cmdList->SetGraphicsRootConstantBufferView(rootParamIndex, gpuAddr);
1832 cbD->cmdList->SetComputeRootConstantBufferView(rootParamIndex, gpuAddr);
1834 rootParamIndex += 1;
1837 for (
int s = 0; s < 6; ++s) {
1838 if (!cache.srvs[s].isEmpty()) {
1839 QD3D12DescriptorHeap &gpuSrvHeap(shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot]);
1840 const UINT count = UINT(cache.srvs[s].count());
1841 const QD3D12Descriptor startDesc = gpuSrvHeap.get(count);
1844 dev->CopyDescriptors(1, &startDesc.cpuHandle, &count,
1845 count, cache.srvs[s].constData(),
nullptr,
1846 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
1849 cbD->cmdList->SetGraphicsRootDescriptorTable(rootParamIndex, startDesc.gpuHandle);
1851 cbD->cmdList->SetComputeRootDescriptorTable(rootParamIndex, startDesc.gpuHandle);
1853 rootParamIndex += 1;
1856 for (
int s = 0; s < 6; ++s) {
1859 for (D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor : cache.samplers[s]) {
1861 cbD->cmdList->SetGraphicsRootDescriptorTable(rootParamIndex, samplerDescriptor);
1863 cbD->cmdList->SetComputeRootDescriptorTable(rootParamIndex, samplerDescriptor);
1865 rootParamIndex += 1;
1868 for (
int s = 0; s < 6; ++s) {
1869 if (!cache.uavs[s].isEmpty()) {
1870 QD3D12DescriptorHeap &gpuUavHeap(shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot]);
1871 const int count = cache.uavs[s].count();
1872 const QD3D12Descriptor startDesc = gpuUavHeap.get(count);
1873 for (
int i = 0; i < count; ++i) {
1874 const QD3D12ShaderResourceBindings::BindingCache::Uav &uav(cache.uavs[s][i]);
1875 if (QD3D12Resource *res = resourcePool.lookupRef(uav.handle)) {
1876 dev->CreateUnorderedAccessView(res->resource,
nullptr, &uav.desc,
1877 gpuUavHeap.incremented(startDesc, i).cpuHandle);
1879 dev->CreateUnorderedAccessView(
nullptr,
nullptr,
nullptr,
1880 gpuUavHeap.incremented(startDesc, i).cpuHandle);
1885 cbD->cmdList->SetGraphicsRootDescriptorTable(rootParamIndex, startDesc.gpuHandle);
1887 cbD->cmdList->SetComputeRootDescriptorTable(rootParamIndex, startDesc.gpuHandle);
1889 rootParamIndex += 1;
1894 cbD->currentGraphicsSrb = srb;
1895 cbD->currentComputeSrb =
nullptr;
1897 cbD->currentGraphicsSrb =
nullptr;
1898 cbD->currentComputeSrb = srb;
1900 cbD->currentSrbGeneration = srbD->generation;
1904void QRhiD3D12::setVertexInput(QRhiCommandBuffer *cb,
1905 int startBinding,
int bindingCount,
const QRhiCommandBuffer::VertexInput *bindings,
1906 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
1908 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
1909 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
1911 const QRhiVertexInputLayout *inputLayout = cbD->currentGraphicsPipeline
1912 ? &cbD->currentGraphicsPipeline->m_vertexInputLayout :
nullptr;
1913 const int inputBindingCount = inputLayout
1914 ? inputLayout->cendBindings() - inputLayout->cbeginBindings() : 0;
1915 const int vertexBindingCount = qMin(bindingCount, inputBindingCount - startBinding);
1919 bool needsBindVBuf =
false;
1920 for (
int i = 0; i < vertexBindingCount; ++i) {
1921 const int inputSlot = startBinding + i;
1922 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, bindings[i].first);
1923 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
1924 const bool isDynamic = bufD->m_type == QRhiBuffer::Dynamic;
1926 bufD->executeHostWritesForFrameSlot(currentFrameSlot);
1928 const QD3D12ObjectHandle handle = bufD->handles[isDynamic ? currentFrameSlot : 0];
1929 const quint32 offset = bindings[i].second;
1930 const quint32 stride = inputLayout->bindingAt(inputSlot)->stride();
1931 if (cbD->currentVertexBuffers[inputSlot] != handle
1932 || cbD->currentVertexOffsets[inputSlot] != offset
1933 || cbD->currentVertexStrides[inputSlot] != stride)
1935 needsBindVBuf =
true;
1936 cbD->currentVertexBuffers[inputSlot] = handle;
1937 cbD->currentVertexOffsets[inputSlot] = offset;
1938 cbD->currentVertexStrides[inputSlot] = stride;
1942 if (needsBindVBuf) {
1943 QVarLengthArray<D3D12_VERTEX_BUFFER_VIEW, 4> vbv;
1944 vbv.reserve(vertexBindingCount);
1946 for (
int i = 0; i < vertexBindingCount; ++i) {
1947 const int inputSlot = startBinding + i;
1948 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, bindings[i].first);
1949 const QD3D12ObjectHandle handle = cbD->currentVertexBuffers[inputSlot];
1950 const quint32 offset = cbD->currentVertexOffsets[inputSlot];
1951 const quint32 stride = cbD->currentVertexStrides[inputSlot];
1953 if (bufD->m_type != QRhiBuffer::Dynamic) {
1954 barrierGen.addTransitionBarrier(handle, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
1955 barrierGen.enqueueBufferedTransitionBarriers(cbD);
1958 if (QD3D12Resource *res = resourcePool.lookupRef(handle)) {
1960 res->resource->GetGPUVirtualAddress() + offset,
1961 UINT(res->desc.Width - offset),
1967 cbD->cmdList->IASetVertexBuffers(UINT(startBinding), vbv.count(), vbv.constData());
1971 QD3D12Buffer *ibufD = QRHI_RES(QD3D12Buffer, indexBuf);
1972 Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
1973 const bool isDynamic = ibufD->m_type == QRhiBuffer::Dynamic;
1975 ibufD->executeHostWritesForFrameSlot(currentFrameSlot);
1977 const DXGI_FORMAT dxgiFormat = indexFormat == QRhiCommandBuffer::IndexUInt16 ? DXGI_FORMAT_R16_UINT
1978 : DXGI_FORMAT_R32_UINT;
1979 if (cbD->currentIndexBuffer != ibufD->handles[isDynamic ? currentFrameSlot : 0]
1980 || cbD->currentIndexOffset != indexOffset
1981 || cbD->currentIndexFormat != dxgiFormat)
1983 cbD->currentIndexBuffer = ibufD->handles[isDynamic ? currentFrameSlot : 0];
1984 cbD->currentIndexOffset = indexOffset;
1985 cbD->currentIndexFormat = dxgiFormat;
1987 if (ibufD->m_type != QRhiBuffer::Dynamic) {
1988 barrierGen.addTransitionBarrier(cbD->currentIndexBuffer, D3D12_RESOURCE_STATE_INDEX_BUFFER);
1989 barrierGen.enqueueBufferedTransitionBarriers(cbD);
1992 if (QD3D12Resource *res = resourcePool.lookupRef(cbD->currentIndexBuffer)) {
1993 const D3D12_INDEX_BUFFER_VIEW ibv = {
1994 res->resource->GetGPUVirtualAddress() + indexOffset,
1995 UINT(res->desc.Width - indexOffset),
1998 cbD->cmdList->IASetIndexBuffer(&ibv);
2004void QRhiD3D12::setDefaultScissor(QD3D12CommandBuffer *cbD)
2006 cbD->hasCustomScissorSet =
false;
2008 const QSize outputSize = cbD->currentTarget->pixelSize();
2009 std::array<
float, 4> vp = cbD->currentViewport.viewport();
2010 float x = 0, y = 0, w = 0, h = 0;
2012 if (qFuzzyIsNull(vp[2]) && qFuzzyIsNull(vp[3])) {
2015 w = outputSize.width();
2016 h = outputSize.height();
2019 qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, vp, &x, &y, &w, &h);
2028 cbD->cmdList->RSSetScissorRects(1, &r);
2031void QRhiD3D12::setViewport(QRhiCommandBuffer *cb,
const QRhiViewport &viewport)
2033 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2034 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2035 Q_ASSERT(cbD->currentTarget);
2036 const QSize outputSize = cbD->currentTarget->pixelSize();
2040 if (!qrhi_toTopLeftRenderTargetRect<UnBounded>(outputSize, viewport.viewport(), &x, &y, &w, &h))
2048 v.MinDepth = viewport.minDepth();
2049 v.MaxDepth = viewport.maxDepth();
2050 cbD->cmdList->RSSetViewports(1, &v);
2052 cbD->currentViewport = viewport;
2053 if (cbD->currentGraphicsPipeline
2054 && !cbD->currentGraphicsPipeline->flags().testFlag(QRhiGraphicsPipeline::UsesScissor))
2056 setDefaultScissor(cbD);
2060void QRhiD3D12::setScissor(QRhiCommandBuffer *cb,
const QRhiScissor &scissor)
2062 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2063 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2064 Q_ASSERT(cbD->currentTarget);
2065 const QSize outputSize = cbD->currentTarget->pixelSize();
2069 if (!qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, scissor.scissor(), &x, &y, &w, &h))
2078 cbD->cmdList->RSSetScissorRects(1, &r);
2080 cbD->hasCustomScissorSet =
true;
2083void QRhiD3D12::setBlendConstants(QRhiCommandBuffer *cb,
const QColor &c)
2085 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2086 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2087 float v[4] = { c.redF(), c.greenF(), c.blueF(), c.alphaF() };
2088 cbD->cmdList->OMSetBlendFactor(v);
2091void QRhiD3D12::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
2093 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2094 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2095 cbD->cmdList->OMSetStencilRef(refValue);
2096 cbD->currentStencilRef = refValue;
2097 cbD->appliedStencilRef = refValue;
2100void QRhiD3D12::setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size,
const void *data)
2102 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2103 Q_ASSERT(cbD->recordingPass != QD3D12CommandBuffer::NoPass);
2105 const bool compute = cbD->recordingPass == QD3D12CommandBuffer::ComputePass;
2106 const int index = compute ? (cbD->currentComputePipeline ? cbD->currentComputePipeline->pushConstantRootParamIndex : -1)
2107 : (cbD->currentGraphicsPipeline ? cbD->currentGraphicsPipeline->pushConstantRootParamIndex : -1);
2109 qWarning(
"No pipeline with a push constant block is active; setPushConstants ignored");
2114 cbD->cmdList->SetComputeRoot32BitConstants(UINT(index), size / 4, data, offset / 4);
2116 cbD->cmdList->SetGraphicsRoot32BitConstants(UINT(index), size / 4, data, offset / 4);
2119static inline D3D12_SHADING_RATE toD3DShadingRate(
const QSize &coarsePixelSize)
2121 if (coarsePixelSize == QSize(1, 2))
2122 return D3D12_SHADING_RATE_1X2;
2123 if (coarsePixelSize == QSize(2, 1))
2124 return D3D12_SHADING_RATE_2X1;
2125 if (coarsePixelSize == QSize(2, 2))
2126 return D3D12_SHADING_RATE_2X2;
2127 if (coarsePixelSize == QSize(2, 4))
2128 return D3D12_SHADING_RATE_2X4;
2129 if (coarsePixelSize == QSize(4, 2))
2130 return D3D12_SHADING_RATE_4X2;
2131 if (coarsePixelSize == QSize(4, 4))
2132 return D3D12_SHADING_RATE_4X4;
2133 return D3D12_SHADING_RATE_1X1;
2136void QRhiD3D12::setShadingRate(QRhiCommandBuffer *cb,
const QSize &coarsePixelSize)
2138 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2139 cbD->hasShadingRateSet =
false;
2141#ifdef QRHI_D3D12_CL5_AVAILABLE
2145 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2146 const D3D12_SHADING_RATE_COMBINER combiners[] = { D3D12_SHADING_RATE_COMBINER_MAX, D3D12_SHADING_RATE_COMBINER_MAX };
2147 cbD->cmdList->RSSetShadingRate(toD3DShadingRate(coarsePixelSize), combiners);
2148 if (coarsePixelSize.width() != 1 || coarsePixelSize.height() != 1)
2149 cbD->hasShadingRateSet =
true;
2152 Q_UNUSED(coarsePixelSize);
2153 qWarning(
"Attempted to set ShadingRate without building Qt against a sufficiently new Windows SDK and d3d12.h. This cannot work.");
2157void QRhiD3D12::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
2158 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
2160 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2161 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2162 cbD->cmdList->DrawInstanced(vertexCount, instanceCount, firstVertex, firstInstance);
2165void QRhiD3D12::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
2166 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
2168 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2169 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2170 cbD->cmdList->DrawIndexedInstanced(indexCount, instanceCount,
2171 firstIndex, vertexOffset,
2175void QRhiD3D12::drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
2176 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
2178 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2179 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2181 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
2182 const bool isDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
2183 const QD3D12ObjectHandle indirectBufferHandle = indirectBufferD->handles[isDynamic ? currentFrameSlot : 0];
2185 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
2187 barrierGen.addTransitionBarrier(indirectBufferHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
2188 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2190 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectBufferHandle);
2193 ID3D12Resource *indirectBufferRes = indirectRes->resource;
2195 const bool canUseMulti = (stride ==
sizeof(QRhiIndirectDrawCommand) && drawCommandSignature);
2197 if (canUseMulti && drawCount > 1) {
2198 cbD->cmdList->ExecuteIndirect(drawCommandSignature, drawCount,
2199 indirectBufferRes, indirectBufferOffset,
2202 UINT offset = indirectBufferOffset;
2203 for (quint32 i = 0; i < drawCount; ++i) {
2204 cbD->cmdList->ExecuteIndirect(drawCommandSignature, 1,
2205 indirectBufferRes, offset,
2212void QRhiD3D12::drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
2213 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
2215 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2216 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2218 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
2219 const bool isDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
2220 const QD3D12ObjectHandle indirectBufferHandle = indirectBufferD->handles[isDynamic ? currentFrameSlot : 0];
2222 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
2224 barrierGen.addTransitionBarrier(indirectBufferHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
2225 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2227 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectBufferHandle);
2230 ID3D12Resource *indirectBufferRes = indirectRes->resource;
2232 const bool canUseMulti = (stride ==
sizeof(QRhiIndexedIndirectDrawCommand) && drawIndexedCommandSignature);
2234 if (canUseMulti && drawCount > 1) {
2235 cbD->cmdList->ExecuteIndirect(drawIndexedCommandSignature, drawCount,
2236 indirectBufferRes, indirectBufferOffset,
2239 UINT offset = indirectBufferOffset;
2240 for (quint32 i = 0; i < drawCount; ++i) {
2241 cbD->cmdList->ExecuteIndirect(drawIndexedCommandSignature, 1,
2242 indirectBufferRes, offset,
2249void QRhiD3D12::debugMarkBegin(QRhiCommandBuffer *cb,
const QByteArray &name)
2254 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2255#ifdef QRHI_D3D12_HAS_OLD_PIX
2256 PIXBeginEvent(cbD->cmdList, PIX_COLOR_DEFAULT,
reinterpret_cast<LPCWSTR>(QString::fromLatin1(name).utf16()));
2263void QRhiD3D12::debugMarkEnd(QRhiCommandBuffer *cb)
2268 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2269#ifdef QRHI_D3D12_HAS_OLD_PIX
2270 PIXEndEvent(cbD->cmdList);
2276void QRhiD3D12::debugMarkMsg(QRhiCommandBuffer *cb,
const QByteArray &msg)
2281 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2282#ifdef QRHI_D3D12_HAS_OLD_PIX
2283 PIXSetMarker(cbD->cmdList, PIX_COLOR_DEFAULT,
reinterpret_cast<LPCWSTR>(QString::fromLatin1(msg).utf16()));
2290const QRhiNativeHandles *QRhiD3D12::nativeHandles(QRhiCommandBuffer *cb)
2292 return QRHI_RES(QD3D12CommandBuffer, cb)->nativeHandles();
2295void QRhiD3D12::beginExternal(QRhiCommandBuffer *cb)
2300void QRhiD3D12::endExternal(QRhiCommandBuffer *cb)
2302 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2303 cbD->resetPerPassState();
2304 bindShaderVisibleHeaps(cbD);
2305 if (cbD->currentTarget) {
2306 QD3D12RenderTargetData *rtD = rtData(cbD->currentTarget);
2307 cbD->cmdList->OMSetRenderTargets(UINT(rtD->colorAttCount),
2310 rtD->dsAttCount ? &rtD->dsv :
nullptr);
2314double QRhiD3D12::lastCompletedGpuTime(QRhiCommandBuffer *cb)
2316 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2317 return cbD->lastGpuTime;
2320static void calculateGpuTime(QD3D12CommandBuffer *cbD,
2321 int timestampPairStartIndex,
2322 const quint8 *readbackBufPtr,
2323 quint64 timestampTicksPerSecond)
2325 const size_t byteOffset = timestampPairStartIndex *
sizeof(quint64);
2326 const quint64 *p =
reinterpret_cast<
const quint64 *>(readbackBufPtr + byteOffset);
2327 const quint64 startTime = *p++;
2328 const quint64 endTime = *p;
2329 if (startTime < endTime) {
2330 const quint64 ticks = endTime - startTime;
2331 const double timeSec = ticks /
double(timestampTicksPerSecond);
2332 cbD->lastGpuTime = timeSec;
2336QRhi::FrameOpResult QRhiD3D12::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags)
2346 return QRhi::FrameOpDeviceLost;
2348 QD3D12SwapChain *swapChainD = QRHI_RES(QD3D12SwapChain, swapChain);
2349 currentSwapChain = swapChainD;
2350 currentFrameSlot = swapChainD->currentFrameSlot;
2351 QD3D12SwapChain::FrameResources &fr(swapChainD->frameRes[currentFrameSlot]);
2364 for (QD3D12SwapChain *sc : std::as_const(swapchains))
2365 sc->waitCommandCompletionForFrameSlot(currentFrameSlot);
2367 if (swapChainD->frameLatencyWaitableObject) {
2369 if (swapChainD->lastFrameLatencyWaitSlot != currentFrameSlot) {
2370 WaitForSingleObjectEx(swapChainD->frameLatencyWaitableObject, 1000,
true);
2371 swapChainD->lastFrameLatencyWaitSlot = currentFrameSlot;
2375 HRESULT hr = cmdAllocators[currentFrameSlot]->Reset();
2377 qWarning(
"Failed to reset command allocator: %s",
2378 qPrintable(QSystemError::windowsComString(hr)));
2379 return QRhi::FrameOpError;
2382 if (!startCommandListForCurrentFrameSlot(&fr.cmdList))
2383 return QRhi::FrameOpError;
2385 QD3D12CommandBuffer *cbD = &swapChainD->cbWrapper;
2386 cbD->cmdList = fr.cmdList;
2388 swapChainD->rtWrapper.d.rtv[0] = swapChainD->sampleDesc.Count > 1
2389 ? swapChainD->msaaRtvs[currentFrameSlot].cpuHandle
2390 : swapChainD->rtvs[swapChainD->currentBackBufferIndex].cpuHandle;
2392 swapChainD->rtWrapper.d.dsv = swapChainD->ds ? swapChainD->ds->dsv.cpuHandle
2393 : D3D12_CPU_DESCRIPTOR_HANDLE { 0 };
2395 if (swapChainD->stereo) {
2396 swapChainD->rtWrapperRight.d.rtv[0] = swapChainD->sampleDesc.Count > 1
2397 ? swapChainD->msaaRtvs[currentFrameSlot].cpuHandle
2398 : swapChainD->rtvsRight[swapChainD->currentBackBufferIndex].cpuHandle;
2400 swapChainD->rtWrapperRight.d.dsv =
2401 swapChainD->ds ? swapChainD->ds->dsv.cpuHandle : D3D12_CPU_DESCRIPTOR_HANDLE{ 0 };
2408 releaseQueue.executeDeferredReleases(currentFrameSlot);
2414 shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot].head = 0;
2417 resetAndResizeSmallStagingArea(currentFrameSlot);
2419 bindShaderVisibleHeaps(cbD);
2421 finishActiveReadbacks();
2423 if (timestampQueryHeap.isValid() && timestampTicksPerSecond) {
2426 const int timestampPairStartIndex = currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT;
2427 calculateGpuTime(cbD,
2428 timestampPairStartIndex,
2429 timestampReadbackArea.mem.p,
2430 timestampTicksPerSecond);
2432 cbD->cmdList->EndQuery(timestampQueryHeap.heap,
2433 D3D12_QUERY_TYPE_TIMESTAMP,
2434 timestampPairStartIndex);
2437 QDxgiVSyncService::instance()->beginFrame(adapterLuid);
2439 return QRhi::FrameOpSuccess;
2442QRhi::FrameOpResult QRhiD3D12::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
2444 QD3D12SwapChain *swapChainD = QRHI_RES(QD3D12SwapChain, swapChain);
2445 Q_ASSERT(currentSwapChain == swapChainD);
2446 QD3D12CommandBuffer *cbD = &swapChainD->cbWrapper;
2448 QD3D12ObjectHandle backBufferResourceHandle = swapChainD->colorBuffers[swapChainD->currentBackBufferIndex];
2449 if (swapChainD->sampleDesc.Count > 1) {
2450 QD3D12ObjectHandle msaaBackBufferResourceHandle = swapChainD->msaaBuffers[currentFrameSlot];
2451 barrierGen.addTransitionBarrier(msaaBackBufferResourceHandle, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
2452 barrierGen.addTransitionBarrier(backBufferResourceHandle, D3D12_RESOURCE_STATE_RESOLVE_DEST);
2453 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2454 const QD3D12Resource *src = resourcePool.lookupRef(msaaBackBufferResourceHandle);
2455 const QD3D12Resource *dst = resourcePool.lookupRef(backBufferResourceHandle);
2457 cbD->cmdList->ResolveSubresource(dst->resource, 0, src->resource, 0, swapChainD->colorFormat);
2460 barrierGen.addTransitionBarrier(backBufferResourceHandle, D3D12_RESOURCE_STATE_PRESENT);
2461 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2463 if (timestampQueryHeap.isValid()) {
2464 const int timestampPairStartIndex = currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT;
2465 cbD->cmdList->EndQuery(timestampQueryHeap.heap,
2466 D3D12_QUERY_TYPE_TIMESTAMP,
2467 timestampPairStartIndex + 1);
2468 cbD->cmdList->ResolveQueryData(timestampQueryHeap.heap,
2469 D3D12_QUERY_TYPE_TIMESTAMP,
2470 timestampPairStartIndex,
2472 timestampReadbackArea.mem.buffer,
2473 timestampPairStartIndex *
sizeof(quint64));
2476 D3D12GraphicsCommandList *cmdList = cbD->cmdList;
2477 HRESULT hr = cmdList->Close();
2479 qWarning(
"Failed to close command list: %s",
2480 qPrintable(QSystemError::windowsComString(hr)));
2481 return QRhi::FrameOpError;
2484 ID3D12CommandList *execList[] = { cmdList };
2485 cmdQueue->ExecuteCommandLists(1, execList);
2487 if (!flags.testFlag(QRhi::SkipPresent)) {
2488 UINT presentFlags = 0;
2489 if (swapChainD->swapInterval == 0
2490 && (swapChainD->swapChainFlags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING))
2492 presentFlags |= DXGI_PRESENT_ALLOW_TEARING;
2494 if (!swapChainD->swapChain) {
2495 qWarning(
"Failed to present, no swapchain");
2496 return QRhi::FrameOpError;
2498 HRESULT hr = swapChainD->swapChain->Present(swapChainD->swapInterval, presentFlags);
2499 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
2500 qWarning(
"Device loss detected in Present()");
2502 return QRhi::FrameOpDeviceLost;
2503 }
else if (FAILED(hr)) {
2504 qWarning(
"Failed to present: %s", qPrintable(QSystemError::windowsComString(hr)));
2505 return QRhi::FrameOpError;
2508 if (dcompDevice && swapChainD->dcompTarget && swapChainD->dcompVisual)
2509 dcompDevice->Commit();
2512 swapChainD->addCommandCompletionSignalForCurrentFrameSlot();
2519 releaseQueue.activatePendingDeferredReleaseRequests(currentFrameSlot);
2521 if (!flags.testFlag(QRhi::SkipPresent)) {
2525 swapChainD->currentFrameSlot = (swapChainD->currentFrameSlot + 1) % QD3D12_FRAMES_IN_FLIGHT;
2526 swapChainD->currentBackBufferIndex = swapChainD->swapChain->GetCurrentBackBufferIndex();
2529 currentSwapChain =
nullptr;
2530 return QRhi::FrameOpSuccess;
2533QRhi::FrameOpResult QRhiD3D12::beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags)
2546 currentFrameSlot = (currentFrameSlot + 1) % QD3D12_FRAMES_IN_FLIGHT;
2548 for (QD3D12SwapChain *sc : std::as_const(swapchains))
2549 sc->waitCommandCompletionForFrameSlot(currentFrameSlot);
2551 HRESULT hr = cmdAllocators[currentFrameSlot]->Reset();
2553 qWarning(
"Failed to reset command allocator: %s",
2554 qPrintable(QSystemError::windowsComString(hr)));
2555 return QRhi::FrameOpError;
2558 if (!offscreenCb[currentFrameSlot])
2559 offscreenCb[currentFrameSlot] =
new QD3D12CommandBuffer(
this);
2560 QD3D12CommandBuffer *cbD = offscreenCb[currentFrameSlot];
2561 if (!startCommandListForCurrentFrameSlot(&cbD->cmdList))
2562 return QRhi::FrameOpError;
2564 releaseQueue.executeDeferredReleases(currentFrameSlot);
2566 shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot].head = 0;
2567 resetAndResizeSmallStagingArea(currentFrameSlot);
2569 bindShaderVisibleHeaps(cbD);
2571 if (timestampQueryHeap.isValid() && timestampTicksPerSecond) {
2572 cbD->cmdList->EndQuery(timestampQueryHeap.heap,
2573 D3D12_QUERY_TYPE_TIMESTAMP,
2574 currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT);
2577 offscreenActive =
true;
2580 return QRhi::FrameOpSuccess;
2583QRhi::FrameOpResult QRhiD3D12::endOffscreenFrame(QRhi::EndFrameFlags flags)
2586 Q_ASSERT(offscreenActive);
2587 offscreenActive =
false;
2589 QD3D12CommandBuffer *cbD = offscreenCb[currentFrameSlot];
2590 if (timestampQueryHeap.isValid()) {
2591 const int timestampPairStartIndex = currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT;
2592 cbD->cmdList->EndQuery(timestampQueryHeap.heap,
2593 D3D12_QUERY_TYPE_TIMESTAMP,
2594 timestampPairStartIndex + 1);
2595 cbD->cmdList->ResolveQueryData(timestampQueryHeap.heap,
2596 D3D12_QUERY_TYPE_TIMESTAMP,
2597 timestampPairStartIndex,
2599 timestampReadbackArea.mem.buffer,
2600 timestampPairStartIndex *
sizeof(quint64));
2603 D3D12GraphicsCommandList *cmdList = cbD->cmdList;
2604 HRESULT hr = cmdList->Close();
2606 qWarning(
"Failed to close command list: %s",
2607 qPrintable(QSystemError::windowsComString(hr)));
2608 return QRhi::FrameOpError;
2611 ID3D12CommandList *execList[] = { cmdList };
2612 cmdQueue->ExecuteCommandLists(1, execList);
2614 releaseQueue.activatePendingDeferredReleaseRequests(currentFrameSlot);
2621 finishActiveReadbacks(
true);
2624 if (timestampQueryHeap.isValid()) {
2625 calculateGpuTime(cbD,
2626 currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT,
2627 timestampReadbackArea.mem.p,
2628 timestampTicksPerSecond);
2631 return QRhi::FrameOpSuccess;
2634QRhi::FrameOpResult QRhiD3D12::finish()
2636 QD3D12CommandBuffer *cbD =
nullptr;
2638 if (offscreenActive) {
2639 Q_ASSERT(!currentSwapChain);
2640 cbD = offscreenCb[currentFrameSlot];
2642 Q_ASSERT(currentSwapChain);
2643 cbD = ¤tSwapChain->cbWrapper;
2646 return QRhi::FrameOpError;
2648 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::NoPass);
2650 D3D12GraphicsCommandList *cmdList = cbD->cmdList;
2651 HRESULT hr = cmdList->Close();
2653 qWarning(
"Failed to close command list: %s",
2654 qPrintable(QSystemError::windowsComString(hr)));
2655 return QRhi::FrameOpError;
2658 ID3D12CommandList *execList[] = { cmdList };
2659 cmdQueue->ExecuteCommandLists(1, execList);
2661 releaseQueue.activatePendingDeferredReleaseRequests(currentFrameSlot);
2668 HRESULT hr = cmdAllocators[currentFrameSlot]->Reset();
2670 qWarning(
"Failed to reset command allocator: %s",
2671 qPrintable(QSystemError::windowsComString(hr)));
2672 return QRhi::FrameOpError;
2675 if (!startCommandListForCurrentFrameSlot(&cbD->cmdList))
2676 return QRhi::FrameOpError;
2680 shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot].head = 0;
2681 smallStagingAreas[currentFrameSlot].head = 0;
2683 bindShaderVisibleHeaps(cbD);
2686 releaseQueue.releaseAll();
2687 finishActiveReadbacks(
true);
2689 return QRhi::FrameOpSuccess;
2692void QRhiD3D12::resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2694 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2695 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::NoPass);
2696 enqueueResourceUpdates(cbD, resourceUpdates);
2699void QRhiD3D12::beginPass(QRhiCommandBuffer *cb,
2700 QRhiRenderTarget *rt,
2701 const QColor &colorClearValue,
2702 const QRhiDepthStencilClearValue &depthStencilClearValue,
2703 QRhiResourceUpdateBatch *resourceUpdates,
2704 QRhiCommandBuffer::BeginPassFlags)
2706 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2707 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::NoPass);
2709 if (resourceUpdates)
2710 enqueueResourceUpdates(cbD, resourceUpdates);
2712 QD3D12RenderTargetData *rtD = rtData(rt);
2713 bool wantsColorClear =
true;
2714 bool wantsDsClear =
true;
2715 if (rt->resourceType() == QRhiRenderTarget::TextureRenderTarget) {
2716 QD3D12TextureRenderTarget *rtTex = QRHI_RES(QD3D12TextureRenderTarget, rt);
2717 wantsColorClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
2718 wantsDsClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
2719 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QD3D12Texture, QD3D12RenderBuffer>(rtTex->description(), rtD->currentResIdList))
2722 for (
auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments(); it != itEnd; ++it) {
2723 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, it->texture());
2724 QD3D12Texture *resolveTexD = QRHI_RES(QD3D12Texture, it->resolveTexture());
2725 QD3D12RenderBuffer *rbD = QRHI_RES(QD3D12RenderBuffer, it->renderBuffer());
2727 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
2729 barrierGen.addTransitionBarrier(rbD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
2731 barrierGen.addTransitionBarrier(resolveTexD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
2733 if (rtTex->m_desc.depthStencilBuffer()) {
2734 QD3D12RenderBuffer *rbD = QRHI_RES(QD3D12RenderBuffer, rtTex->m_desc.depthStencilBuffer());
2735 Q_ASSERT(rbD->m_type == QRhiRenderBuffer::DepthStencil);
2736 barrierGen.addTransitionBarrier(rbD->handle, D3D12_RESOURCE_STATE_DEPTH_WRITE);
2737 }
else if (rtTex->m_desc.depthTexture()) {
2738 QD3D12Texture *depthTexD = QRHI_RES(QD3D12Texture, rtTex->m_desc.depthTexture());
2739 barrierGen.addTransitionBarrier(depthTexD->handle, D3D12_RESOURCE_STATE_DEPTH_WRITE);
2741 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2743 Q_ASSERT(currentSwapChain);
2744 barrierGen.addTransitionBarrier(currentSwapChain->sampleDesc.Count > 1
2745 ? currentSwapChain->msaaBuffers[currentFrameSlot]
2746 : currentSwapChain->colorBuffers[currentSwapChain->currentBackBufferIndex],
2747 D3D12_RESOURCE_STATE_RENDER_TARGET);
2748 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2751 cbD->cmdList->OMSetRenderTargets(UINT(rtD->colorAttCount),
2754 rtD->dsAttCount ? &rtD->dsv :
nullptr);
2756 if (rtD->colorAttCount && wantsColorClear) {
2757 float clearColor[4] = {
2758 colorClearValue.redF(),
2759 colorClearValue.greenF(),
2760 colorClearValue.blueF(),
2761 colorClearValue.alphaF()
2763 for (
int i = 0; i < rtD->colorAttCount; ++i)
2764 cbD->cmdList->ClearRenderTargetView(rtD->rtv[i], clearColor, 0,
nullptr);
2766 if (rtD->dsAttCount && wantsDsClear) {
2767 cbD->cmdList->ClearDepthStencilView(rtD->dsv,
2768 D3D12_CLEAR_FLAGS(D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL),
2769 depthStencilClearValue.depthClearValue(),
2770 UINT8(depthStencilClearValue.stencilClearValue()),
2775 cbD->recordingPass = QD3D12CommandBuffer::RenderPass;
2776 cbD->currentTarget = rt;
2778 bool hasShadingRateMapSet =
false;
2779#ifdef QRHI_D3D12_CL5_AVAILABLE
2780 if (rtD->rp->hasShadingRateMap) {
2781 cbD->setShadingRate(QSize(1, 1));
2782 QD3D12ShadingRateMap *rateMapD = rt->resourceType() == QRhiRenderTarget::TextureRenderTarget
2783 ? QRHI_RES(QD3D12ShadingRateMap, QRHI_RES(QD3D12TextureRenderTarget, rt)->m_desc.shadingRateMap())
2784 : QRHI_RES(QD3D12ShadingRateMap, QRHI_RES(QD3D12SwapChainRenderTarget, rt)->swapChain()->shadingRateMap());
2785 if (QD3D12Resource *res = resourcePool.lookupRef(rateMapD->handle)) {
2786 barrierGen.addTransitionBarrier(rateMapD->handle, D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE);
2787 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2788 cbD->cmdList->RSSetShadingRateImage(res->resource);
2789 hasShadingRateMapSet =
true;
2791 }
else if (cbD->hasShadingRateMapSet) {
2792 cbD->cmdList->RSSetShadingRateImage(
nullptr);
2793 cbD->setShadingRate(QSize(1, 1));
2794 }
else if (cbD->hasShadingRateSet) {
2795 cbD->setShadingRate(QSize(1, 1));
2799 cbD->resetPerPassState();
2802 cbD->hasShadingRateMapSet = hasShadingRateMapSet;
2805void QRhiD3D12::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2807 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2808 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2810 if (cbD->currentTarget->resourceType() == QRhiResource::TextureRenderTarget) {
2811 QD3D12TextureRenderTarget *rtTex = QRHI_RES(QD3D12TextureRenderTarget, cbD->currentTarget);
2812 for (
auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments();
2815 const QRhiColorAttachment &colorAtt(*it);
2816 if (!colorAtt.resolveTexture())
2819 QD3D12Texture *dstTexD = QRHI_RES(QD3D12Texture, colorAtt.resolveTexture());
2820 QD3D12Resource *dstRes = resourcePool.lookupRef(dstTexD->handle);
2824 QD3D12Texture *srcTexD = QRHI_RES(QD3D12Texture, colorAtt.texture());
2825 QD3D12RenderBuffer *srcRbD = QRHI_RES(QD3D12RenderBuffer, colorAtt.renderBuffer());
2826 Q_ASSERT(srcTexD || srcRbD);
2827 QD3D12Resource *srcRes = resourcePool.lookupRef(srcTexD ? srcTexD->handle : srcRbD->handle);
2832 if (srcTexD->dxgiFormat != dstTexD->dxgiFormat) {
2833 qWarning(
"Resolve source (%d) and destination (%d) formats do not match",
2834 int(srcTexD->dxgiFormat),
int(dstTexD->dxgiFormat));
2837 if (srcTexD->sampleDesc.Count <= 1) {
2838 qWarning(
"Cannot resolve a non-multisample texture");
2841 if (srcTexD->m_pixelSize != dstTexD->m_pixelSize) {
2842 qWarning(
"Resolve source and destination sizes do not match");
2846 if (srcRbD->dxgiFormat != dstTexD->dxgiFormat) {
2847 qWarning(
"Resolve source (%d) and destination (%d) formats do not match",
2848 int(srcRbD->dxgiFormat),
int(dstTexD->dxgiFormat));
2851 if (srcRbD->m_pixelSize != dstTexD->m_pixelSize) {
2852 qWarning(
"Resolve source and destination sizes do not match");
2863 const UINT resolveCount = colorAtt.multiViewCount() >= 2 ? colorAtt.multiViewCount() : 1;
2864 QBitArray &initialized(dstTexD->subresourceInitialized);
2865 QVarLengthArray<UINT, 4> dstSubresources;
2866 QVarLengthArray<UINT, 4> subresourcesToDiscard;
2867 for (UINT resolveIdx = 0; resolveIdx < resolveCount; ++resolveIdx) {
2868 const UINT dstSubresource = calcSubresource(UINT(colorAtt.resolveLevel()),
2869 UINT(colorAtt.resolveLayer()) + resolveIdx,
2870 dstTexD->mipLevelCount);
2871 dstSubresources.append(dstSubresource);
2872 if (
int(dstSubresource) >= initialized.size())
2873 initialized.resize(
int(dstSubresource) + 1);
2874 if (!initialized.testBit(
int(dstSubresource))) {
2875 initialized.setBit(
int(dstSubresource));
2876 subresourcesToDiscard.append(dstSubresource);
2880 barrierGen.addTransitionBarrier(srcTexD ? srcTexD->handle : srcRbD->handle, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
2883 if (!subresourcesToDiscard.isEmpty()) {
2884 barrierGen.addTransitionBarrier(dstTexD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
2885 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2886 for (UINT dstSubresource : subresourcesToDiscard) {
2887 D3D12_DISCARD_REGION region = {};
2888 region.FirstSubresource = dstSubresource;
2889 region.NumSubresources = 1;
2890 cbD->cmdList->DiscardResource(dstRes->resource, ®ion);
2894 barrierGen.addTransitionBarrier(dstTexD->handle, D3D12_RESOURCE_STATE_RESOLVE_DEST);
2895 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2897 for (UINT resolveIdx = 0; resolveIdx < resolveCount; ++resolveIdx) {
2898 const UINT srcSubresource = calcSubresource(0, UINT(colorAtt.layer()) + resolveIdx, 1);
2899 cbD->cmdList->ResolveSubresource(dstRes->resource, dstSubresources[resolveIdx],
2900 srcRes->resource, srcSubresource,
2901 dstTexD->dxgiFormat);
2904 if (rtTex->m_desc.depthResolveTexture())
2905 qWarning(
"Resolving multisample depth-stencil buffers is not supported with D3D");
2908 cbD->recordingPass = QD3D12CommandBuffer::NoPass;
2909 cbD->currentTarget =
nullptr;
2911 if (resourceUpdates)
2912 enqueueResourceUpdates(cbD, resourceUpdates);
2915void QRhiD3D12::beginComputePass(QRhiCommandBuffer *cb,
2916 QRhiResourceUpdateBatch *resourceUpdates,
2917 QRhiCommandBuffer::BeginPassFlags)
2919 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2920 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::NoPass);
2922 if (resourceUpdates)
2923 enqueueResourceUpdates(cbD, resourceUpdates);
2925 cbD->recordingPass = QD3D12CommandBuffer::ComputePass;
2927 cbD->resetPerPassState();
2930void QRhiD3D12::endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2932 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2933 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::ComputePass);
2935 cbD->recordingPass = QD3D12CommandBuffer::NoPass;
2937 if (resourceUpdates)
2938 enqueueResourceUpdates(cbD, resourceUpdates);
2941void QRhiD3D12::setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps)
2943 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2944 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::ComputePass);
2945 QD3D12ComputePipeline *psD = QRHI_RES(QD3D12ComputePipeline, ps);
2946 const bool pipelineChanged = cbD->currentComputePipeline != psD || cbD->currentPipelineGeneration != psD->generation;
2948 if (pipelineChanged) {
2949 cbD->currentGraphicsPipeline =
nullptr;
2950 cbD->currentComputePipeline = psD;
2951 cbD->currentPipelineGeneration = psD->generation;
2953 if (QD3D12Pipeline *pipeline = pipelinePool.lookupRef(psD->handle)) {
2954 Q_ASSERT(pipeline->type == QD3D12Pipeline::Compute);
2955 cbD->cmdList->SetPipelineState(pipeline->pso);
2956 if (QD3D12RootSignature *rs = rootSignaturePool.lookupRef(psD->rootSigHandle))
2957 cbD->cmdList->SetComputeRootSignature(rs->rootSig);
2962void QRhiD3D12::dispatch(QRhiCommandBuffer *cb,
int x,
int y,
int z)
2964 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2965 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::ComputePass);
2966 cbD->cmdList->Dispatch(UINT(x), UINT(y), UINT(z));
2972ID3D12CommandSignature *QRhiD3D12::indirectDrawCommandSignature(
bool indexed, quint32 stride)
2974 const quint32 canonicalStride = indexed ?
sizeof(QRhiIndexedIndirectDrawCommand)
2975 :
sizeof(QRhiIndirectDrawCommand);
2976 if (stride == canonicalStride)
2977 return indexed ? drawIndexedCommandSignature : drawCommandSignature;
2979 QHash<quint32, ID3D12CommandSignature *> &cache(indexed ? drawIndexedCommandSignaturesByStride
2980 : drawCommandSignaturesByStride);
2981 auto it = cache.constFind(stride);
2982 if (it != cache.constEnd())
2985 D3D12_INDIRECT_ARGUMENT_DESC arg = {};
2986 arg.Type = indexed ? D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED : D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
2988 D3D12_COMMAND_SIGNATURE_DESC sigDesc = {};
2989 sigDesc.ByteStride = stride;
2990 sigDesc.NumArgumentDescs = 1;
2991 sigDesc.pArgumentDescs = &arg;
2993 ID3D12CommandSignature *sig =
nullptr;
2994 HRESULT hr = dev->CreateCommandSignature(&sigDesc,
nullptr, IID_PPV_ARGS(&sig));
2996 qWarning(
"Failed to create indirect draw command signature with stride %u: %s",
2997 stride, qPrintable(QSystemError::windowsComString(hr)));
3001 cache.insert(stride, sig);
3005void QRhiD3D12::drawIndirectCount(QRhiCommandBuffer *cb,
3006 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
3007 QRhiBuffer *countBuffer, quint32 countBufferOffset,
3008 quint32 maxDrawCount, quint32 stride)
3010 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
3011 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
3013 ID3D12CommandSignature *sig = indirectDrawCommandSignature(
false, stride);
3017 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
3018 const bool indirectIsDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
3019 const QD3D12ObjectHandle indirectHandle = indirectBufferD->handles[indirectIsDynamic ? currentFrameSlot : 0];
3020 if (indirectIsDynamic)
3021 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3023 barrierGen.addTransitionBarrier(indirectHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3025 QD3D12Buffer *countBufferD = QRHI_RES(QD3D12Buffer, countBuffer);
3026 const bool countIsDynamic = countBufferD->m_type == QRhiBuffer::Dynamic;
3027 const QD3D12ObjectHandle countHandle = countBufferD->handles[countIsDynamic ? currentFrameSlot : 0];
3029 countBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3031 barrierGen.addTransitionBarrier(countHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3033 if (!indirectIsDynamic || !countIsDynamic)
3034 barrierGen.enqueueBufferedTransitionBarriers(cbD);
3036 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectHandle);
3037 QD3D12Resource *countRes = resourcePool.lookupRef(countHandle);
3038 if (!indirectRes || !countRes)
3041 cbD->cmdList->ExecuteIndirect(sig, maxDrawCount,
3042 indirectRes->resource, indirectBufferOffset,
3043 countRes->resource, countBufferOffset);
3046void QRhiD3D12::drawIndexedIndirectCount(QRhiCommandBuffer *cb,
3047 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
3048 QRhiBuffer *countBuffer, quint32 countBufferOffset,
3049 quint32 maxDrawCount, quint32 stride)
3051 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
3052 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
3054 ID3D12CommandSignature *sig = indirectDrawCommandSignature(
true, stride);
3058 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
3059 const bool indirectIsDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
3060 const QD3D12ObjectHandle indirectHandle = indirectBufferD->handles[indirectIsDynamic ? currentFrameSlot : 0];
3061 if (indirectIsDynamic)
3062 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3064 barrierGen.addTransitionBarrier(indirectHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3066 QD3D12Buffer *countBufferD = QRHI_RES(QD3D12Buffer, countBuffer);
3067 const bool countIsDynamic = countBufferD->m_type == QRhiBuffer::Dynamic;
3068 const QD3D12ObjectHandle countHandle = countBufferD->handles[countIsDynamic ? currentFrameSlot : 0];
3070 countBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3072 barrierGen.addTransitionBarrier(countHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3074 if (!indirectIsDynamic || !countIsDynamic)
3075 barrierGen.enqueueBufferedTransitionBarriers(cbD);
3077 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectHandle);
3078 QD3D12Resource *countRes = resourcePool.lookupRef(countHandle);
3079 if (!indirectRes || !countRes)
3082 cbD->cmdList->ExecuteIndirect(sig, maxDrawCount,
3083 indirectRes->resource, indirectBufferOffset,
3084 countRes->resource, countBufferOffset);
3087void QRhiD3D12::dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
3088 quint32 indirectBufferOffset)
3090 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
3091 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::ComputePass);
3093 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
3094 const bool isDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
3095 const QD3D12ObjectHandle indirectBufferHandle = indirectBufferD->handles[isDynamic ? currentFrameSlot : 0];
3097 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3102 barrierGen.addTransitionBarrier(indirectBufferHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3103 barrierGen.enqueueBufferedTransitionBarriers(cbD);
3105 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectBufferHandle);
3109 cbD->cmdList->ExecuteIndirect(dispatchCommandSignature, 1,
3110 indirectRes->resource, indirectBufferOffset,
3114bool QD3D12DescriptorHeap::create(ID3D12Device *device,
3115 quint32 descriptorCount,
3116 D3D12_DESCRIPTOR_HEAP_TYPE heapType,
3117 D3D12_DESCRIPTOR_HEAP_FLAGS heapFlags)
3120 capacity = descriptorCount;
3121 this->heapType = heapType;
3122 this->heapFlags = heapFlags;
3124 D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
3125 heapDesc.Type = heapType;
3126 heapDesc.NumDescriptors = capacity;
3127 heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAGS(heapFlags);
3129 HRESULT hr = device->CreateDescriptorHeap(&heapDesc, __uuidof(ID3D12DescriptorHeap),
reinterpret_cast<
void **>(&heap));
3131 qWarning(
"Failed to create descriptor heap: %s", qPrintable(QSystemError::windowsComString(hr)));
3133 capacity = descriptorByteSize = 0;
3137 descriptorByteSize = device->GetDescriptorHandleIncrementSize(heapType);
3138 heapStart.cpuHandle = heap->GetCPUDescriptorHandleForHeapStart();
3139 if (heapFlags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)
3140 heapStart.gpuHandle = heap->GetGPUDescriptorHandleForHeapStart();
3145void QD3D12DescriptorHeap::createWithExisting(
const QD3D12DescriptorHeap &other,
3146 quint32 offsetInDescriptors,
3147 quint32 descriptorCount)
3151 capacity = descriptorCount;
3152 heapType = other.heapType;
3153 heapFlags = other.heapFlags;
3154 descriptorByteSize = other.descriptorByteSize;
3155 heapStart = incremented(other.heapStart, offsetInDescriptors);
3158void QD3D12DescriptorHeap::destroy()
3167void QD3D12DescriptorHeap::destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue)
3170 releaseQueue->deferredReleaseDescriptorHeap(heap);
3176QD3D12Descriptor QD3D12DescriptorHeap::get(quint32 count)
3178 Q_ASSERT(count > 0);
3179 if (head + count > capacity) {
3180 qWarning(
"Cannot get %u descriptors as that would exceed capacity %u", count, capacity);
3184 return at(head - count);
3187QD3D12Descriptor QD3D12DescriptorHeap::at(quint32 index)
const
3189 const quint32 startOffset = index * descriptorByteSize;
3190 QD3D12Descriptor result;
3191 result.cpuHandle.ptr = heapStart.cpuHandle.ptr + startOffset;
3192 if (heapStart.gpuHandle.ptr != 0)
3193 result.gpuHandle.ptr = heapStart.gpuHandle.ptr + startOffset;
3197bool QD3D12CpuDescriptorPool::create(ID3D12Device *device, D3D12_DESCRIPTOR_HEAP_TYPE heapType,
const char *debugName)
3199 QD3D12DescriptorHeap firstHeap;
3200 if (!firstHeap.create(device, DESCRIPTORS_PER_HEAP, heapType, D3D12_DESCRIPTOR_HEAP_FLAG_NONE))
3202 heaps.append(HeapWithMap::init(firstHeap, DESCRIPTORS_PER_HEAP));
3203 descriptorByteSize = heaps[0].heap.descriptorByteSize;
3204 this->device = device;
3205 this->debugName = debugName;
3209void QD3D12CpuDescriptorPool::destroy()
3213 static bool leakCheck =
true;
3216 static bool leakCheck = qEnvironmentVariableIntValue(
"QT_RHI_LEAK_CHECK");
3219 for (
const HeapWithMap &heap : std::as_const(heaps)) {
3220 const int leakedDescriptorCount = heap.map.count(
true);
3221 if (leakedDescriptorCount > 0) {
3222 qWarning(
"QD3D12CpuDescriptorPool::destroy(): "
3223 "Heap %p for descriptor pool %p '%s' has %d unreleased descriptors",
3224 &heap.heap,
this, debugName, leakedDescriptorCount);
3228 for (HeapWithMap &heap : heaps)
3229 heap.heap.destroy();
3233QD3D12Descriptor QD3D12CpuDescriptorPool::allocate(quint32 count)
3235 Q_ASSERT(count > 0 && count <= DESCRIPTORS_PER_HEAP);
3237 HeapWithMap &last(heaps.last());
3238 if (last.heap.head + count <= last.heap.capacity) {
3239 quint32 firstIndex = last.heap.head;
3240 for (quint32 i = 0; i < count; ++i)
3241 last.map.setBit(firstIndex + i);
3242 return last.heap.get(count);
3245 for (HeapWithMap &heap : heaps) {
3246 quint32 freeCount = 0;
3247 for (quint32 i = 0; i < DESCRIPTORS_PER_HEAP; ++i) {
3248 if (heap.map.testBit(i)) {
3252 if (freeCount == count) {
3253 const quint32 firstIndex = i - (freeCount - 1);
3254 for (quint32 j = 0; j < count; ++j)
3255 heap.map.setBit(firstIndex + j);
3259 if (firstIndex + count > heap.heap.head)
3260 heap.heap.head = firstIndex + count;
3261 return heap.heap.at(firstIndex);
3267 QD3D12DescriptorHeap newHeap;
3268 if (!newHeap.create(device, DESCRIPTORS_PER_HEAP, last.heap.heapType, last.heap.heapFlags))
3271 heaps.append(HeapWithMap::init(newHeap, DESCRIPTORS_PER_HEAP));
3273 for (quint32 i = 0; i < count; ++i)
3274 heaps.last().map.setBit(i);
3276 return heaps.last().heap.get(count);
3279void QD3D12CpuDescriptorPool::release(
const QD3D12Descriptor &descriptor, quint32 count)
3281 Q_ASSERT(count > 0 && count <= DESCRIPTORS_PER_HEAP);
3282 if (!descriptor.isValid())
3285 const SIZE_T addr = descriptor.cpuHandle.ptr;
3286 for (HeapWithMap &heap : heaps) {
3287 const SIZE_T begin = heap.heap.heapStart.cpuHandle.ptr;
3288 const SIZE_T end = begin + heap.heap.descriptorByteSize * heap.heap.capacity;
3289 if (addr >= begin && addr < end) {
3290 quint32 firstIndex = (addr - begin) / heap.heap.descriptorByteSize;
3291 for (quint32 i = 0; i < count; ++i)
3292 heap.map.setBit(firstIndex + i,
false);
3297 qWarning(
"QD3D12CpuDescriptorPool::release: Descriptor with address %llu is not in any heap",
3298 quint64(descriptor.cpuHandle.ptr));
3301bool QD3D12QueryHeap::create(ID3D12Device *device,
3303 D3D12_QUERY_HEAP_TYPE heapType)
3305 capacity = queryCount;
3307 D3D12_QUERY_HEAP_DESC heapDesc = {};
3308 heapDesc.Type = heapType;
3309 heapDesc.Count = capacity;
3311 HRESULT hr = device->CreateQueryHeap(&heapDesc, __uuidof(ID3D12QueryHeap),
reinterpret_cast<
void **>(&heap));
3313 qWarning(
"Failed to create query heap: %s", qPrintable(QSystemError::windowsComString(hr)));
3322void QD3D12QueryHeap::destroy()
3331bool QD3D12StagingArea::create(QRhiD3D12 *rhi, quint32 capacity, D3D12_HEAP_TYPE heapType)
3333 Q_ASSERT(heapType == D3D12_HEAP_TYPE_UPLOAD || heapType == D3D12_HEAP_TYPE_READBACK);
3334 D3D12_RESOURCE_DESC resourceDesc = {};
3335 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
3336 resourceDesc.Width = capacity;
3337 resourceDesc.Height = 1;
3338 resourceDesc.DepthOrArraySize = 1;
3339 resourceDesc.MipLevels = 1;
3340 resourceDesc.Format = DXGI_FORMAT_UNKNOWN;
3341 resourceDesc.SampleDesc = { 1, 0 };
3342 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
3343 resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
3344 UINT state = heapType == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST;
3345 HRESULT hr = rhi->vma.createResource(heapType,
3347 D3D12_RESOURCE_STATES(state),
3350 __uuidof(ID3D12Resource),
3351 reinterpret_cast<
void **>(&resource));
3353 qWarning(
"Failed to create buffer for staging area: %s",
3354 qPrintable(QSystemError::windowsComString(hr)));
3358 hr = resource->Map(0,
nullptr, &p);
3360 qWarning(
"Failed to map buffer for staging area: %s",
3361 qPrintable(QSystemError::windowsComString(hr)));
3366 mem.p =
static_cast<quint8 *>(p);
3367 mem.gpuAddr = resource->GetGPUVirtualAddress();
3368 mem.buffer = resource;
3369 mem.bufferOffset = 0;
3371 this->capacity = capacity;
3377void QD3D12StagingArea::destroy()
3380 resource->Release();
3384 allocation->Release();
3385 allocation =
nullptr;
3390void QD3D12StagingArea::destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue)
3393 releaseQueue->deferredReleaseResourceAndAllocation(resource, allocation);
3397QD3D12StagingArea::Allocation QD3D12StagingArea::get(quint32 byteSize)
3399 const quint32 allocSize = aligned(byteSize, ALIGNMENT);
3400 if (head + allocSize > capacity) {
3401 qWarning(
"Failed to allocate %u (%u) bytes from staging area of size %u with %u bytes left",
3402 allocSize, byteSize, capacity, remainingCapacity());
3405 const quint32 offset = head;
3409 mem.gpuAddr + offset,
3418void QD3D12ReleaseQueue::deferredReleaseResource(
const QD3D12ObjectHandle &handle)
3420 DeferredReleaseEntry e;
3425void QD3D12ReleaseQueue::deferredReleaseResourceWithViews(
const QD3D12ObjectHandle &handle,
3426 QD3D12CpuDescriptorPool *pool,
3427 const QD3D12Descriptor &viewsStart,
3430 DeferredReleaseEntry e;
3431 e.type = DeferredReleaseEntry::Resource;
3433 e.poolForViews = pool;
3434 e.viewsStart = viewsStart;
3435 e.viewCount = viewCount;
3439void QD3D12ReleaseQueue::deferredReleasePipeline(
const QD3D12ObjectHandle &handle)
3441 DeferredReleaseEntry e;
3442 e.type = DeferredReleaseEntry::Pipeline;
3447void QD3D12ReleaseQueue::deferredReleaseRootSignature(
const QD3D12ObjectHandle &handle)
3449 DeferredReleaseEntry e;
3450 e.type = DeferredReleaseEntry::RootSignature;
3455void QD3D12ReleaseQueue::deferredReleaseCallback(std::function<
void(
void*)> callback,
void *userData)
3457 DeferredReleaseEntry e;
3458 e.type = DeferredReleaseEntry::Callback;
3459 e.callback = callback;
3460 e.callbackUserData = userData;
3464void QD3D12ReleaseQueue::deferredReleaseResourceAndAllocation(ID3D12Resource *resource,
3465 D3D12MA::Allocation *allocation)
3467 DeferredReleaseEntry e;
3468 e.type = DeferredReleaseEntry::ResourceAndAllocation;
3469 e.resourceAndAllocation = { resource, allocation };
3473void QD3D12ReleaseQueue::deferredReleaseDescriptorHeap(ID3D12DescriptorHeap *heap)
3475 DeferredReleaseEntry e;
3476 e.type = DeferredReleaseEntry::DescriptorHeap;
3477 e.descriptorHeap = heap;
3481void QD3D12ReleaseQueue::deferredReleaseViews(QD3D12CpuDescriptorPool *pool,
3482 const QD3D12Descriptor &viewsStart,
3485 DeferredReleaseEntry e;
3486 e.type = DeferredReleaseEntry::Views;
3487 e.poolForViews = pool;
3488 e.viewsStart = viewsStart;
3489 e.viewCount = viewCount;
3493void QD3D12ReleaseQueue::activatePendingDeferredReleaseRequests(
int frameSlot)
3495 for (DeferredReleaseEntry &e : queue) {
3496 if (!e.frameSlotToBeReleasedIn.has_value())
3497 e.frameSlotToBeReleasedIn = frameSlot;
3501void QD3D12ReleaseQueue::executeDeferredReleases(
int frameSlot,
bool forced)
3503 qsizetype keepBegin = queue.size();
3504 for (qsizetype i = keepBegin - 1; i >= 0; --i) {
3505 const DeferredReleaseEntry &e(queue[i]);
3506 if (forced || (e.frameSlotToBeReleasedIn.has_value() && e.frameSlotToBeReleasedIn.value() == frameSlot)) {
3508 case DeferredReleaseEntry::Resource:
3509 resourcePool->remove(e.handle);
3510 if (e.poolForViews && e.viewsStart.isValid() && e.viewCount > 0)
3511 e.poolForViews->release(e.viewsStart, e.viewCount);
3513 case DeferredReleaseEntry::Pipeline:
3514 pipelinePool->remove(e.handle);
3516 case DeferredReleaseEntry::RootSignature:
3517 rootSignaturePool->remove(e.handle);
3519 case DeferredReleaseEntry::Callback:
3520 e.callback(e.callbackUserData);
3522 case DeferredReleaseEntry::ResourceAndAllocation:
3525 e.resourceAndAllocation.first->Release();
3526 if (e.resourceAndAllocation.second)
3527 e.resourceAndAllocation.second->Release();
3529 case DeferredReleaseEntry::DescriptorHeap:
3530 e.descriptorHeap->Release();
3532 case DeferredReleaseEntry::Views:
3533 e.poolForViews->release(e.viewsStart, e.viewCount);
3536 }
else if (--keepBegin != i) {
3537 queue[keepBegin] = std::move(queue[i]);
3541 queue.remove(0, keepBegin);
3544void QD3D12ReleaseQueue::releaseAll()
3546 executeDeferredReleases(0,
true);
3549void QD3D12ResourceBarrierGenerator::addTransitionBarrier(
const QD3D12ObjectHandle &resourceHandle,
3550 D3D12_RESOURCE_STATES stateAfter)
3552 if (QD3D12Resource *res = resourcePool->lookupRef(resourceHandle)) {
3553 if (stateAfter != res->state) {
3554 transitionResourceBarriers.append({ resourceHandle, res->state, stateAfter });
3555 res->state = stateAfter;
3560void QD3D12ResourceBarrierGenerator::enqueueBufferedTransitionBarriers(QD3D12CommandBuffer *cbD)
3562 QVarLengthArray<D3D12_RESOURCE_BARRIER, PREALLOC> barriers;
3563 for (
const TransitionResourceBarrier &trb : transitionResourceBarriers) {
3564 if (QD3D12Resource *res = resourcePool->lookupRef(trb.resourceHandle)) {
3565 D3D12_RESOURCE_BARRIER barrier = {};
3566 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
3567 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
3568 barrier.Transition.pResource = res->resource;
3569 barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
3570 barrier.Transition.StateBefore = trb.stateBefore;
3571 barrier.Transition.StateAfter = trb.stateAfter;
3572 barriers.append(barrier);
3575 transitionResourceBarriers.clear();
3576 if (!barriers.isEmpty())
3577 cbD->cmdList->ResourceBarrier(barriers.count(), barriers.constData());
3580void QD3D12ResourceBarrierGenerator::enqueueSubresourceTransitionBarrier(QD3D12CommandBuffer *cbD,
3581 const QD3D12ObjectHandle &resourceHandle,
3583 D3D12_RESOURCE_STATES stateBefore,
3584 D3D12_RESOURCE_STATES stateAfter)
3586 if (QD3D12Resource *res = resourcePool->lookupRef(resourceHandle)) {
3587 D3D12_RESOURCE_BARRIER barrier = {};
3588 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
3589 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
3590 barrier.Transition.pResource = res->resource;
3591 barrier.Transition.Subresource = subresource;
3592 barrier.Transition.StateBefore = stateBefore;
3593 barrier.Transition.StateAfter = stateAfter;
3594 cbD->cmdList->ResourceBarrier(1, &barrier);
3598void QD3D12ResourceBarrierGenerator::enqueueUavBarrier(QD3D12CommandBuffer *cbD,
3599 const QD3D12ObjectHandle &resourceHandle)
3601 if (QD3D12Resource *res = resourcePool->lookupRef(resourceHandle)) {
3602 D3D12_RESOURCE_BARRIER barrier = {};
3603 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
3604 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
3605 barrier.UAV.pResource = res->resource;
3606 cbD->cmdList->ResourceBarrier(1, &barrier);
3610bool QD3D12ShaderVisibleDescriptorHeap::create(ID3D12Device *device,
3611 D3D12_DESCRIPTOR_HEAP_TYPE type,
3612 quint32 perFrameDescriptorCount)
3614 Q_ASSERT(type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
3616 quint32 size = perFrameDescriptorCount * QD3D12_FRAMES_IN_FLIGHT;
3619 const quint32 CBV_SRV_UAV_MAX = 1000000;
3620 const quint32 SAMPLER_MAX = 2048;
3621 if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
3622 size = qMin(size, CBV_SRV_UAV_MAX);
3623 else if (type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)
3624 size = qMin(size, SAMPLER_MAX);
3626 if (!heap.create(device, size, type, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) {
3627 qWarning(
"Failed to create shader-visible descriptor heap of size %u", size);
3631 perFrameDescriptorCount = size / QD3D12_FRAMES_IN_FLIGHT;
3632 quint32 currentOffsetInDescriptors = 0;
3633 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
3634 perFrameHeapSlice[i].createWithExisting(heap, currentOffsetInDescriptors, perFrameDescriptorCount);
3635 currentOffsetInDescriptors += perFrameDescriptorCount;
3641void QD3D12ShaderVisibleDescriptorHeap::destroy()
3646void QD3D12ShaderVisibleDescriptorHeap::destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue)
3648 heap.destroyWithDeferredRelease(releaseQueue);
3651static inline std::pair<
int,
int> mapBinding(
int binding,
const QD3D12ShaderStageData *sd)
3653 const QShader::NativeResourceBindingMap &map(sd->nativeResourceBindingMap);
3654 if (map.isEmpty()) {
3662 if (sd->pushConstantRegister >= 0)
3664 return { binding, binding };
3667 auto it = map.constFind(binding);
3668 if (it != map.cend())
3677void QD3D12ShaderResourceVisitor::visit()
3679 for (
int bindingIdx = 0, bindingCount = srb->m_bindings.count(); bindingIdx != bindingCount; ++bindingIdx) {
3680 const QRhiShaderResourceBinding &b(srb->m_bindings[bindingIdx]);
3681 const QRhiShaderResourceBinding::Data *bd = QRhiImplementation::shaderResourceBindingData(b);
3683 for (
int stageIdx = 0; stageIdx < stageCount; ++stageIdx) {
3684 const QD3D12ShaderStageData *sd = &stageData[stageIdx];
3688 if (!bd->stage.testFlag(qd3d12_stageToSrb(sd->stage)))
3691 switch (bd->type()) {
3692 case QRhiShaderResourceBinding::UniformBuffer:
3694 const int shaderRegister = mapBinding(bd->binding, sd).first;
3695 if (shaderRegister >= 0 && uniformBuffer)
3696 uniformBuffer(sd->stage, bd->ubuf(), shaderRegister, bd->binding);
3699 case QRhiShaderResourceBinding::SampledTexture:
3701 Q_ASSERT(bd->stex().count() > 0);
3702 const int textureBaseShaderRegister = mapBinding(bd->binding, sd).first;
3703 const int samplerBaseShaderRegister = mapBinding(bd->binding, sd).second;
3704 if (textureBaseShaderRegister >= 0 && textures)
3705 textures(sd->stage, bd->stex().texSamplers.constData(), bd->stex().count(), textureBaseShaderRegister);
3706 if (samplerBaseShaderRegister >= 0 && samplers)
3707 samplers(sd->stage, bd->stex().texSamplers.constData(), bd->stex().count(), samplerBaseShaderRegister);
3710 case QRhiShaderResourceBinding::Texture:
3712 Q_ASSERT(bd->stex().count() > 0);
3713 const int baseShaderRegister = mapBinding(bd->binding, sd).first;
3714 if (baseShaderRegister >= 0 && textures)
3715 textures(sd->stage, bd->stex().texSamplers.constData(), bd->stex().count(), baseShaderRegister);
3718 case QRhiShaderResourceBinding::Sampler:
3720 Q_ASSERT(bd->stex().count() > 0);
3721 const int baseShaderRegister = mapBinding(bd->binding, sd).first;
3722 if (baseShaderRegister >= 0 && samplers)
3723 samplers(sd->stage, bd->stex().texSamplers.constData(), bd->stex().count(), baseShaderRegister);
3726 case QRhiShaderResourceBinding::ImageLoad:
3728 const int shaderRegister = mapBinding(bd->binding, sd).first;
3729 if (shaderRegister >= 0 && storageImage)
3730 storageImage(sd->stage, bd->simage(), Load, shaderRegister);
3733 case QRhiShaderResourceBinding::ImageStore:
3735 const int shaderRegister = mapBinding(bd->binding, sd).first;
3736 if (shaderRegister >= 0 && storageImage)
3737 storageImage(sd->stage, bd->simage(), Store, shaderRegister);
3740 case QRhiShaderResourceBinding::ImageLoadStore:
3742 const int shaderRegister = mapBinding(bd->binding, sd).first;
3743 if (shaderRegister >= 0 && storageImage)
3744 storageImage(sd->stage, bd->simage(), LoadStore, shaderRegister);
3747 case QRhiShaderResourceBinding::BufferLoad:
3749 const int shaderRegister = mapBinding(bd->binding, sd).first;
3750 if (shaderRegister >= 0 && storageBuffer)
3751 storageBuffer(sd->stage, bd->sbuf(), Load, shaderRegister);
3754 case QRhiShaderResourceBinding::BufferStore:
3756 const int shaderRegister = mapBinding(bd->binding, sd).first;
3757 if (shaderRegister >= 0 && storageBuffer)
3758 storageBuffer(sd->stage, bd->sbuf(), Store, shaderRegister);
3761 case QRhiShaderResourceBinding::BufferLoadStore:
3763 const int shaderRegister = mapBinding(bd->binding, sd).first;
3764 if (shaderRegister >= 0 && storageBuffer)
3765 storageBuffer(sd->stage, bd->sbuf(), LoadStore, shaderRegister);
3773bool QD3D12SamplerManager::create(ID3D12Device *device)
3776 if (!shaderVisibleSamplerHeap.create(device,
3777 D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
3778 MAX_SAMPLERS / QD3D12_FRAMES_IN_FLIGHT))
3780 qWarning(
"Could not create shader-visible SAMPLER heap");
3784 this->device = device;
3788void QD3D12SamplerManager::destroy()
3791 shaderVisibleSamplerHeap.destroy();
3796QD3D12Descriptor QD3D12SamplerManager::getShaderVisibleDescriptor(
const D3D12_SAMPLER_DESC &desc)
3798 auto it = gpuMap.constFind({desc});
3799 if (it != gpuMap.cend())
3802 QD3D12Descriptor descriptor = shaderVisibleSamplerHeap.heap.get(1);
3803 if (descriptor.isValid()) {
3804 device->CreateSampler(&desc, descriptor.cpuHandle);
3805 gpuMap.insert({desc}, descriptor);
3807 qWarning(
"Out of shader-visible SAMPLER descriptor heap space,"
3808 " this should not happen, maximum number of unique samplers is %u",
3809 shaderVisibleSamplerHeap.heap.capacity);
3815QD3D12Descriptor QD3D12SamplerManager::getShaderVisibleDescriptors(
const QVarLengthArray<Q_D3D12_SAMPLER_DESC, 8> &descs)
3821 auto it = gpuArrayMap.constFind({ descs });
3822 if (it != gpuArrayMap.cend())
3825 const quint32 count = quint32(descs.count());
3826 QD3D12Descriptor startDescriptor = shaderVisibleSamplerHeap.heap.get(count);
3827 if (startDescriptor.isValid()) {
3828 for (quint32 i = 0; i < count; ++i) {
3829 device->CreateSampler(&descs[
int(i)].desc,
3830 shaderVisibleSamplerHeap.heap.incremented(startDescriptor, i).cpuHandle);
3832 gpuArrayMap.insert({ descs }, startDescriptor);
3839 qWarning(
"Out of shader-visible SAMPLER descriptor heap space when reserving"
3840 " %u consecutive descriptors for a sampler array, maximum number of"
3841 " sampler descriptors is %u",
3842 count, shaderVisibleSamplerHeap.heap.capacity);
3845 return startDescriptor;
3848void QD3D12MipmapGenerator::create(QRhiD3D12 *rhiD)
3853bool QD3D12MipmapGenerator::ensureCreated()
3855 if (!pipelineHandle.isNull())
3861 if (!buildPipeline()) {
3862 createFailed =
true;
3869bool QD3D12MipmapGenerator::buildPipeline()
3871 qCDebug(QRHI_LOG_INFO,
"Building mipmap generator compute pipeline on first use");
3873 D3D12_ROOT_PARAMETER1 rootParams[3] = {};
3874 D3D12_DESCRIPTOR_RANGE1 descriptorRanges[2] = {};
3877 rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
3878 rootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
3879 rootParams[0].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC;
3882 descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
3883 descriptorRanges[0].NumDescriptors = 1;
3884 descriptorRanges[0].Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
3885 rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
3886 rootParams[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
3887 rootParams[1].DescriptorTable.NumDescriptorRanges = 1;
3888 rootParams[1].DescriptorTable.pDescriptorRanges = &descriptorRanges[0];
3891 descriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
3892 descriptorRanges[1].NumDescriptors = 4;
3893 rootParams[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
3894 rootParams[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
3895 rootParams[2].DescriptorTable.NumDescriptorRanges = 1;
3896 rootParams[2].DescriptorTable.pDescriptorRanges = &descriptorRanges[1];
3899 D3D12_STATIC_SAMPLER_DESC samplerDesc = {};
3900 samplerDesc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
3901 samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
3902 samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
3903 samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
3904 samplerDesc.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
3906 D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsDesc = {};
3907 rsDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
3908 rsDesc.Desc_1_1.NumParameters = 3;
3909 rsDesc.Desc_1_1.pParameters = rootParams;
3910 rsDesc.Desc_1_1.NumStaticSamplers = 1;
3911 rsDesc.Desc_1_1.pStaticSamplers = &samplerDesc;
3913 ID3DBlob *signature =
nullptr;
3914 HRESULT hr = D3D12SerializeVersionedRootSignature(&rsDesc, &signature,
nullptr);
3916 qWarning(
"Failed to serialize root signature: %s", qPrintable(QSystemError::windowsComString(hr)));
3919 ID3D12RootSignature *rootSig =
nullptr;
3920 hr = rhiD->dev->CreateRootSignature(0,
3921 signature->GetBufferPointer(),
3922 signature->GetBufferSize(),
3923 __uuidof(ID3D12RootSignature),
3924 reinterpret_cast<
void **>(&rootSig));
3925 signature->Release();
3927 qWarning(
"Failed to create root signature: %s",
3928 qPrintable(QSystemError::windowsComString(hr)));
3932 rootSigHandle = QD3D12RootSignature::addToPool(&rhiD->rootSignaturePool, rootSig);
3934 D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {};
3935 psoDesc.pRootSignature = rootSig;
3936 psoDesc.CS.pShaderBytecode = g_csMipmap;
3937 psoDesc.CS.BytecodeLength =
sizeof(g_csMipmap);
3938 ID3D12PipelineState *pso =
nullptr;
3939 hr = rhiD->dev->CreateComputePipelineState(&psoDesc,
3940 __uuidof(ID3D12PipelineState),
3941 reinterpret_cast<
void **>(&pso));
3943 qWarning(
"Failed to create compute pipeline state: %s",
3944 qPrintable(QSystemError::windowsComString(hr)));
3945 rhiD->rootSignaturePool.remove(rootSigHandle);
3950 pipelineHandle = QD3D12Pipeline::addToPool(&rhiD->pipelinePool, QD3D12Pipeline::Compute, pso);
3955void QD3D12MipmapGenerator::destroy()
3962 rhiD->pipelinePool.remove(pipelineHandle);
3963 pipelineHandle = {};
3964 rhiD->rootSignaturePool.remove(rootSigHandle);
3966 createFailed =
false;
3969void QD3D12MipmapGenerator::generate(QD3D12CommandBuffer *cbD,
const QD3D12ObjectHandle &textureHandle)
3971 if (!ensureCreated())
3974 QD3D12Pipeline *pipeline = rhiD->pipelinePool.lookupRef(pipelineHandle);
3977 QD3D12RootSignature *rootSig = rhiD->rootSignaturePool.lookupRef(rootSigHandle);
3980 QD3D12Resource *res = rhiD->resourcePool.lookupRef(textureHandle);
3984 const quint32 mipLevelCount = res->desc.MipLevels;
3985 if (mipLevelCount < 2)
3988 if (res->desc.SampleDesc.Count > 1) {
3989 qWarning(
"Cannot generate mipmaps for MSAA texture");
3993 const bool is1D = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D;
3995 qWarning(
"Cannot generate mipmaps for 1D texture");
3999 const bool is3D = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
4000 const bool isCubeOrArray = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D
4001 && res->desc.DepthOrArraySize > 1;
4002 const quint32 layerCount = isCubeOrArray ? res->desc.DepthOrArraySize : 1;
4005 qWarning(
"2D mipmap generator invoked for 3D texture, this should not happen");
4009 rhiD->barrierGen.addTransitionBarrier(textureHandle, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4010 rhiD->barrierGen.enqueueBufferedTransitionBarriers(cbD);
4012 cbD->cmdList->SetPipelineState(pipeline->pso);
4013 cbD->cmdList->SetComputeRootSignature(rootSig->rootSig);
4015 const quint32 descriptorByteSize = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].descriptorByteSize;
4018 quint32 srcMipLevel;
4019 quint32 numMipLevels;
4024 const quint32 allocSize = QD3D12StagingArea::allocSizeForArray(
sizeof(CBufData), mipLevelCount * layerCount);
4025 std::optional<QD3D12StagingArea> ownStagingArea;
4026 rhiD->recordSmallStagingAreaDemand(allocSize);
4027 if (rhiD->smallStagingAreas[rhiD->currentFrameSlot].remainingCapacity() < allocSize) {
4028 ownStagingArea = QD3D12StagingArea();
4029 if (!ownStagingArea->create(rhiD, allocSize, D3D12_HEAP_TYPE_UPLOAD)) {
4030 qWarning(
"Could not create staging area for mipmap generation");
4034 QD3D12StagingArea *workArea = ownStagingArea.has_value()
4035 ? &ownStagingArea.value()
4036 : &rhiD->smallStagingAreas[rhiD->currentFrameSlot];
4038 bool gotNewHeap =
false;
4039 if (!rhiD->ensureShaderVisibleDescriptorHeapCapacity(&rhiD->shaderVisibleCbvSrvUavHeap,
4040 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
4041 rhiD->currentFrameSlot,
4042 (1 + 4) * mipLevelCount * layerCount,
4045 qWarning(
"Could not ensure enough space in descriptor heap for mipmap generation");
4049 rhiD->bindShaderVisibleHeaps(cbD);
4051 for (quint32 layer = 0; layer < layerCount; ++layer) {
4053 for (quint32 level = 0; level + 1 < mipLevelCount ;) {
4054 UINT subresource = calcSubresource(level, layer, res->desc.MipLevels);
4055 rhiD->barrierGen.enqueueSubresourceTransitionBarrier(cbD, textureHandle, subresource,
4056 D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
4057 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
4059 quint32 levelPlusOneMipWidth = res->desc.Width >> (level + 1);
4060 quint32 levelPlusOneMipHeight = res->desc.Height >> (level + 1);
4061 const quint32 dw = levelPlusOneMipWidth == 1 ? levelPlusOneMipHeight : levelPlusOneMipWidth;
4062 const quint32 dh = levelPlusOneMipHeight == 1 ? levelPlusOneMipWidth : levelPlusOneMipHeight;
4064 const quint32 additionalMips = qCountTrailingZeroBits(dw | dh);
4065 const quint32 numGenMips = qMin(1u + qMin(3u, additionalMips), res->desc.MipLevels - 1u - level);
4066 levelPlusOneMipWidth = qMax(1u, levelPlusOneMipWidth);
4067 levelPlusOneMipHeight = qMax(1u, levelPlusOneMipHeight);
4071 CBufData cbufData = {
4074 1.0f /
float(levelPlusOneMipWidth),
4075 1.0f /
float(levelPlusOneMipHeight)
4078 QD3D12StagingArea::Allocation cbuf = workArea->get(
sizeof(cbufData));
4079 memcpy(cbuf.p, &cbufData,
sizeof(cbufData));
4080 cbD->cmdList->SetComputeRootConstantBufferView(0, cbuf.gpuAddr);
4082 QD3D12Descriptor srv = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].get(1);
4083 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
4084 srvDesc.Format = res->desc.Format;
4085 srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
4086 if (isCubeOrArray) {
4087 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
4088 srvDesc.Texture2DArray.MostDetailedMip = level;
4089 srvDesc.Texture2DArray.MipLevels = 1;
4090 srvDesc.Texture2DArray.FirstArraySlice = layer;
4091 srvDesc.Texture2DArray.ArraySize = 1;
4093 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
4094 srvDesc.Texture2D.MostDetailedMip = level;
4095 srvDesc.Texture2D.MipLevels = 1;
4097 rhiD->dev->CreateShaderResourceView(res->resource, &srvDesc, srv.cpuHandle);
4098 cbD->cmdList->SetComputeRootDescriptorTable(1, srv.gpuHandle);
4100 QD3D12Descriptor uavStart = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].get(4);
4101 D3D12_CPU_DESCRIPTOR_HANDLE uavCpuHandle = uavStart.cpuHandle;
4103 for (quint32 uavIdx = 0; uavIdx < 4; ++uavIdx) {
4104 const quint32 uavMipLevel = qMin(level + 1u + uavIdx, res->desc.MipLevels - 1u);
4105 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
4106 uavDesc.Format = res->desc.Format;
4107 if (isCubeOrArray) {
4108 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
4109 uavDesc.Texture2DArray.MipSlice = uavMipLevel;
4110 uavDesc.Texture2DArray.FirstArraySlice = layer;
4111 uavDesc.Texture2DArray.ArraySize = 1;
4113 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
4114 uavDesc.Texture2D.MipSlice = uavMipLevel;
4116 rhiD->dev->CreateUnorderedAccessView(res->resource,
nullptr, &uavDesc, uavCpuHandle);
4117 uavCpuHandle.ptr += descriptorByteSize;
4119 cbD->cmdList->SetComputeRootDescriptorTable(2, uavStart.gpuHandle);
4121 cbD->cmdList->Dispatch(levelPlusOneMipWidth, levelPlusOneMipHeight, 1);
4123 rhiD->barrierGen.enqueueUavBarrier(cbD, textureHandle);
4124 rhiD->barrierGen.enqueueSubresourceTransitionBarrier(cbD, textureHandle, subresource,
4125 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
4126 D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4128 level += numGenMips;
4132 if (ownStagingArea.has_value())
4133 ownStagingArea->destroyWithDeferredRelease(&rhiD->releaseQueue);
4136void QD3D12MipmapGenerator3D::create(QRhiD3D12 *rhiD)
4141bool QD3D12MipmapGenerator3D::ensureCreated()
4143 if (!pipelineHandle.isNull())
4149 if (!buildPipeline()) {
4150 createFailed =
true;
4157bool QD3D12MipmapGenerator3D::buildPipeline()
4159 qCDebug(QRHI_LOG_INFO,
"Building 3D texture mipmap generator compute pipeline on first use");
4161 D3D12_ROOT_PARAMETER1 rootParams[3] = {};
4162 D3D12_DESCRIPTOR_RANGE1 descriptorRanges[2] = {};
4165 rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
4166 rootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
4167 rootParams[0].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC;
4170 descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
4171 descriptorRanges[0].NumDescriptors = 1;
4172 descriptorRanges[0].Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
4173 rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
4174 rootParams[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
4175 rootParams[1].DescriptorTable.NumDescriptorRanges = 1;
4176 rootParams[1].DescriptorTable.pDescriptorRanges = &descriptorRanges[0];
4179 descriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
4180 descriptorRanges[1].NumDescriptors = 1;
4181 rootParams[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
4182 rootParams[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
4183 rootParams[2].DescriptorTable.NumDescriptorRanges = 1;
4184 rootParams[2].DescriptorTable.pDescriptorRanges = &descriptorRanges[1];
4187 D3D12_STATIC_SAMPLER_DESC samplerDesc = {};
4188 samplerDesc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
4189 samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
4190 samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
4191 samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
4192 samplerDesc.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
4194 D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsDesc = {};
4195 rsDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
4196 rsDesc.Desc_1_1.NumParameters = 3;
4197 rsDesc.Desc_1_1.pParameters = rootParams;
4198 rsDesc.Desc_1_1.NumStaticSamplers = 1;
4199 rsDesc.Desc_1_1.pStaticSamplers = &samplerDesc;
4201 ID3DBlob *signature =
nullptr;
4202 HRESULT hr = D3D12SerializeVersionedRootSignature(&rsDesc, &signature,
nullptr);
4204 qWarning(
"Failed to serialize root signature: %s", qPrintable(QSystemError::windowsComString(hr)));
4207 ID3D12RootSignature *rootSig =
nullptr;
4208 hr = rhiD->dev->CreateRootSignature(0,
4209 signature->GetBufferPointer(),
4210 signature->GetBufferSize(),
4211 __uuidof(ID3D12RootSignature),
4212 reinterpret_cast<
void **>(&rootSig));
4213 signature->Release();
4215 qWarning(
"Failed to create root signature: %s",
4216 qPrintable(QSystemError::windowsComString(hr)));
4220 rootSigHandle = QD3D12RootSignature::addToPool(&rhiD->rootSignaturePool, rootSig);
4222 D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {};
4223 psoDesc.pRootSignature = rootSig;
4224 psoDesc.CS.pShaderBytecode = g_csMipmap3D;
4225 psoDesc.CS.BytecodeLength =
sizeof(g_csMipmap3D);
4226 ID3D12PipelineState *pso =
nullptr;
4227 hr = rhiD->dev->CreateComputePipelineState(&psoDesc,
4228 __uuidof(ID3D12PipelineState),
4229 reinterpret_cast<
void **>(&pso));
4231 qWarning(
"Failed to create compute pipeline state: %s",
4232 qPrintable(QSystemError::windowsComString(hr)));
4233 rhiD->rootSignaturePool.remove(rootSigHandle);
4238 pipelineHandle = QD3D12Pipeline::addToPool(&rhiD->pipelinePool, QD3D12Pipeline::Compute, pso);
4243void QD3D12MipmapGenerator3D::destroy()
4248 rhiD->pipelinePool.remove(pipelineHandle);
4249 pipelineHandle = {};
4250 rhiD->rootSignaturePool.remove(rootSigHandle);
4252 createFailed =
false;
4255void QD3D12MipmapGenerator3D::generate(QD3D12CommandBuffer *cbD,
const QD3D12ObjectHandle &textureHandle)
4257 if (!ensureCreated())
4260 QD3D12Pipeline *pipeline = rhiD->pipelinePool.lookupRef(pipelineHandle);
4263 QD3D12RootSignature *rootSig = rhiD->rootSignaturePool.lookupRef(rootSigHandle);
4266 QD3D12Resource *res = rhiD->resourcePool.lookupRef(textureHandle);
4270 const quint32 mipLevelCount = res->desc.MipLevels;
4271 if (mipLevelCount < 2)
4274 const bool is3D = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
4276 qWarning(
"3D mipmap generator invoked for non-3D texture, this should not happen");
4280 rhiD->barrierGen.addTransitionBarrier(textureHandle, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4281 rhiD->barrierGen.enqueueBufferedTransitionBarriers(cbD);
4283 cbD->cmdList->SetPipelineState(pipeline->pso);
4284 cbD->cmdList->SetComputeRootSignature(rootSig->rootSig);
4286 const quint32 descriptorByteSize = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].descriptorByteSize;
4292 quint32 srcMipLevel;
4295 const quint32 allocSize = QD3D12StagingArea::allocSizeForArray(
sizeof(CBufData), mipLevelCount);
4296 std::optional<QD3D12StagingArea> ownStagingArea;
4297 rhiD->recordSmallStagingAreaDemand(allocSize);
4298 if (rhiD->smallStagingAreas[rhiD->currentFrameSlot].remainingCapacity() < allocSize) {
4299 ownStagingArea = QD3D12StagingArea();
4300 if (!ownStagingArea->create(rhiD, allocSize, D3D12_HEAP_TYPE_UPLOAD)) {
4301 qWarning(
"Could not create staging area for mipmap generation");
4305 QD3D12StagingArea *workArea = ownStagingArea.has_value()
4306 ? &ownStagingArea.value()
4307 : &rhiD->smallStagingAreas[rhiD->currentFrameSlot];
4309 bool gotNewHeap =
false;
4310 if (!rhiD->ensureShaderVisibleDescriptorHeapCapacity(&rhiD->shaderVisibleCbvSrvUavHeap,
4311 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
4312 rhiD->currentFrameSlot,
4313 (1 + 1) * mipLevelCount,
4316 qWarning(
"Could not ensure enough space in descriptor heap for mipmap generation");
4320 rhiD->bindShaderVisibleHeaps(cbD);
4323 for (quint32 level = 0; level + 1 < mipLevelCount; ++level) {
4324 UINT subresource = calcSubresource(level, 0u, res->desc.MipLevels);
4325 rhiD->barrierGen.enqueueSubresourceTransitionBarrier(cbD, textureHandle, subresource,
4326 D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
4327 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
4329 quint32 levelPlusOneMipWidth = qMax<quint32>(1, res->desc.Width >> (level + 1));
4330 quint32 levelPlusOneMipHeight = qMax<quint32>(1, res->desc.Height >> (level + 1));
4331 quint32 levelPlusOneMipDepth = qMax<quint32>(1, res->desc.DepthOrArraySize >> (level + 1));
4335 CBufData cbufData = {
4336 1.0f /
float(levelPlusOneMipWidth),
4337 1.0f /
float(levelPlusOneMipHeight),
4338 1.0f /
float(levelPlusOneMipDepth),
4342 QD3D12StagingArea::Allocation cbuf = workArea->get(
sizeof(cbufData));
4343 memcpy(cbuf.p, &cbufData,
sizeof(cbufData));
4344 cbD->cmdList->SetComputeRootConstantBufferView(0, cbuf.gpuAddr);
4346 QD3D12Descriptor srv = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].get(1);
4347 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
4348 srvDesc.Format = res->desc.Format;
4349 srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
4350 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
4351 srvDesc.Texture3D.MostDetailedMip = level;
4352 srvDesc.Texture3D.MipLevels = 1;
4354 rhiD->dev->CreateShaderResourceView(res->resource, &srvDesc, srv.cpuHandle);
4355 cbD->cmdList->SetComputeRootDescriptorTable(1, srv.gpuHandle);
4357 QD3D12Descriptor uavStart = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].get(1);
4358 D3D12_CPU_DESCRIPTOR_HANDLE uavCpuHandle = uavStart.cpuHandle;
4359 const quint32 uavMipLevel = qMin(level + 1u, res->desc.MipLevels - 1u);
4360 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
4361 uavDesc.Format = res->desc.Format;
4362 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
4363 uavDesc.Texture3D.MipSlice = uavMipLevel;
4364 uavDesc.Texture3D.WSize = UINT(-1);
4365 rhiD->dev->CreateUnorderedAccessView(res->resource,
nullptr, &uavDesc, uavCpuHandle);
4366 uavCpuHandle.ptr += descriptorByteSize;
4367 cbD->cmdList->SetComputeRootDescriptorTable(2, uavStart.gpuHandle);
4369 cbD->cmdList->Dispatch(levelPlusOneMipWidth, levelPlusOneMipHeight, levelPlusOneMipDepth);
4371 rhiD->barrierGen.enqueueUavBarrier(cbD, textureHandle);
4372 rhiD->barrierGen.enqueueSubresourceTransitionBarrier(cbD, textureHandle, subresource,
4373 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
4374 D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4377 if (ownStagingArea.has_value())
4378 ownStagingArea->destroyWithDeferredRelease(&rhiD->releaseQueue);
4381bool QD3D12MemoryAllocator::create(ID3D12Device *device, IDXGIAdapter1 *adapter)
4383 this->device = device;
4390 static bool disableMA = qEnvironmentVariableIntValue(
"QT_D3D_NO_SUBALLOC");
4394 DXGI_ADAPTER_DESC1 desc;
4395 adapter->GetDesc1(&desc);
4396 if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
4399 D3D12MA::ALLOCATOR_DESC allocatorDesc = {};
4400 allocatorDesc.pDevice = device;
4401 allocatorDesc.pAdapter = adapter;
4404 allocatorDesc.Flags = D3D12MA::ALLOCATOR_FLAG_SINGLETHREADED;
4405 HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);
4407 qWarning(
"Failed to initialize D3D12 Memory Allocator: %s",
4408 qPrintable(QSystemError::windowsComString(hr)));
4414void QD3D12MemoryAllocator::destroy()
4417 allocator->Release();
4418 allocator =
nullptr;
4422HRESULT QD3D12MemoryAllocator::createResource(D3D12_HEAP_TYPE heapType,
4423 const D3D12_RESOURCE_DESC *resourceDesc,
4424 D3D12_RESOURCE_STATES initialState,
4425 const D3D12_CLEAR_VALUE *optimizedClearValue,
4426 D3D12MA::Allocation **maybeAllocation,
4427 REFIID riidResource,
4431 D3D12MA::ALLOCATION_DESC allocDesc = {};
4432 allocDesc.HeapType = heapType;
4433 return allocator->CreateResource(&allocDesc,
4436 optimizedClearValue,
4441 *maybeAllocation =
nullptr;
4442 D3D12_HEAP_PROPERTIES heapProps = {};
4443 heapProps.Type = heapType;
4444 return device->CreateCommittedResource(&heapProps,
4445 D3D12_HEAP_FLAG_NONE,
4448 optimizedClearValue,
4454void QD3D12MemoryAllocator::getBudget(D3D12MA::Budget *localBudget, D3D12MA::Budget *nonLocalBudget)
4457 allocator->GetBudget(localBudget, nonLocalBudget);
4460 *nonLocalBudget = {};
4464void QRhiD3D12::waitGpu()
4466 fullFenceCounter += 1u;
4467 if (SUCCEEDED(cmdQueue->Signal(fullFence, fullFenceCounter))) {
4468 if (SUCCEEDED(fullFence->SetEventOnCompletion(fullFenceCounter, fullFenceEvent)))
4469 WaitForSingleObject(fullFenceEvent, INFINITE);
4473DXGI_SAMPLE_DESC QRhiD3D12::effectiveSampleDesc(
int sampleCount, DXGI_FORMAT format)
const
4475 DXGI_SAMPLE_DESC desc;
4479 const int s = effectiveSampleCount(sampleCount);
4482 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msaaInfo = {};
4483 msaaInfo.Format = format;
4484 msaaInfo.SampleCount = UINT(s);
4485 if (SUCCEEDED(dev->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msaaInfo,
sizeof(msaaInfo)))) {
4486 if (msaaInfo.NumQualityLevels > 0) {
4487 desc.Count = UINT(s);
4488 desc.Quality = msaaInfo.NumQualityLevels - 1;
4490 qWarning(
"No quality levels for multisampling with sample count %d", s);
4498bool QRhiD3D12::startCommandListForCurrentFrameSlot(D3D12GraphicsCommandList **cmdList)
4500 ID3D12CommandAllocator *cmdAlloc = cmdAllocators[currentFrameSlot];
4502 HRESULT hr = dev->CreateCommandList(0,
4503 D3D12_COMMAND_LIST_TYPE_DIRECT,
4506 __uuidof(D3D12GraphicsCommandList),
4507 reinterpret_cast<
void **>(cmdList));
4509 qWarning(
"Failed to create command list: %s", qPrintable(QSystemError::windowsComString(hr)));
4513 HRESULT hr = (*cmdList)->Reset(cmdAlloc,
nullptr);
4515 qWarning(
"Failed to reset command list: %s", qPrintable(QSystemError::windowsComString(hr)));
4522static inline QRhiTexture::Format swapchainReadbackTextureFormat(DXGI_FORMAT format, QRhiTexture::Flags *flags)
4525 case DXGI_FORMAT_R8G8B8A8_UNORM:
4526 return QRhiTexture::RGBA8;
4527 case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
4529 (*flags) |= QRhiTexture::sRGB;
4530 return QRhiTexture::RGBA8;
4531 case DXGI_FORMAT_B8G8R8A8_UNORM:
4532 return QRhiTexture::BGRA8;
4533 case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
4535 (*flags) |= QRhiTexture::sRGB;
4536 return QRhiTexture::BGRA8;
4537 case DXGI_FORMAT_R16G16B16A16_FLOAT:
4538 return QRhiTexture::RGBA16F;
4539 case DXGI_FORMAT_R32G32B32A32_FLOAT:
4540 return QRhiTexture::RGBA32F;
4541 case DXGI_FORMAT_R10G10B10A2_UNORM:
4542 return QRhiTexture::RGB10A2;
4544 qWarning(
"DXGI_FORMAT %d cannot be read back", format);
4547 return QRhiTexture::UnknownFormat;
4550static inline bool isDepthTextureFormat(QRhiTexture::Format format)
4553 case QRhiTexture::Format::D16:
4554 case QRhiTexture::Format::D24:
4555 case QRhiTexture::Format::D24S8:
4556 case QRhiTexture::Format::D32F:
4557 case QRhiTexture::Format::D32FS8:
4564void QRhiD3D12::enqueueResourceUpdates(QD3D12CommandBuffer *cbD, QRhiResourceUpdateBatch *resourceUpdates)
4566 QRhiResourceUpdateBatchPrivate *ud = QRhiResourceUpdateBatchPrivate::get(resourceUpdates);
4568 for (
int opIdx = 0; opIdx < ud->activeBufferOpCount; ++opIdx) {
4569 const QRhiResourceUpdateBatchPrivate::BufferOp &u(ud->bufferOps[opIdx]);
4570 if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::DynamicUpdate) {
4571 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, u.buf);
4572 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
4573 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
4574 if (u.offset == 0 && u.data.size() == bufD->m_size)
4575 bufD->pendingHostWrites[i].clear();
4576 bufD->pendingHostWrites[i].append({ u.offset, u.data });
4578 }
else if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::StaticUpload) {
4579 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, u.buf);
4580 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
4581 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
4589 QD3D12StagingArea::Allocation stagingAlloc;
4590 const quint32 allocSize = QD3D12StagingArea::allocSizeForArray(bufD->m_size, 1);
4591 recordSmallStagingAreaDemand(allocSize);
4592 if (smallStagingAreas[currentFrameSlot].remainingCapacity() >= allocSize)
4593 stagingAlloc = smallStagingAreas[currentFrameSlot].get(bufD->m_size);
4595 std::optional<QD3D12StagingArea> ownStagingArea;
4596 if (!stagingAlloc.isValid()) {
4597 ownStagingArea = QD3D12StagingArea();
4598 if (!ownStagingArea->create(
this, allocSize, D3D12_HEAP_TYPE_UPLOAD))
4600 stagingAlloc = ownStagingArea->get(allocSize);
4601 if (!stagingAlloc.isValid()) {
4602 ownStagingArea->destroy();
4607 memcpy(stagingAlloc.p + u.offset, u.data.constData(), u.data.size());
4609 barrierGen.addTransitionBarrier(bufD->handles[0], D3D12_RESOURCE_STATE_COPY_DEST);
4610 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4612 if (QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[0])) {
4613 cbD->cmdList->CopyBufferRegion(res->resource,
4615 stagingAlloc.buffer,
4616 stagingAlloc.bufferOffset + u.offset,
4620 if (ownStagingArea.has_value())
4621 ownStagingArea->destroyWithDeferredRelease(&releaseQueue);
4622 }
else if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::Read) {
4623 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, u.buf);
4624 if (bufD->m_type == QRhiBuffer::Dynamic) {
4625 bufD->executeHostWritesForFrameSlot(currentFrameSlot);
4626 if (QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[currentFrameSlot])) {
4627 Q_ASSERT(res->cpuMapPtr);
4628 u.result->data.resize(u.readSize);
4629 memcpy(u.result->data.data(),
reinterpret_cast<
char *>(res->cpuMapPtr) + u.offset, u.readSize);
4631 if (u.result->completed)
4632 u.result->completed();
4634 QD3D12Readback readback;
4635 readback.frameSlot = currentFrameSlot;
4636 readback.result = u.result;
4637 readback.byteSize = u.readSize;
4638 const quint32 allocSize = aligned(u.readSize, QD3D12StagingArea::ALIGNMENT);
4639 if (!readback.staging.create(
this, allocSize, D3D12_HEAP_TYPE_READBACK)) {
4640 if (u.result->completed)
4641 u.result->completed();
4644 QD3D12StagingArea::Allocation stagingAlloc = readback.staging.get(u.readSize);
4645 if (!stagingAlloc.isValid()) {
4646 readback.staging.destroy();
4647 if (u.result->completed)
4648 u.result->completed();
4651 Q_ASSERT(stagingAlloc.bufferOffset == 0);
4652 barrierGen.addTransitionBarrier(bufD->handles[0], D3D12_RESOURCE_STATE_COPY_SOURCE);
4653 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4654 if (QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[0])) {
4655 cbD->cmdList->CopyBufferRegion(stagingAlloc.buffer, 0, res->resource, u.offset, u.readSize);
4656 activeReadbacks.append(readback);
4658 readback.staging.destroy();
4659 if (u.result->completed)
4660 u.result->completed();
4663 }
else if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::Copy) {
4664 QD3D12Buffer *dstD = QRHI_RES(QD3D12Buffer, u.buf);
4665 QD3D12Buffer *srcD = QRHI_RES(QD3D12Buffer, u.src);
4666 Q_ASSERT(dstD->m_type != QRhiBuffer::Dynamic && srcD->m_type != QRhiBuffer::Dynamic);
4668 QD3D12Resource *dstRes = resourcePool.lookupRef(dstD->handles[0]);
4669 QD3D12Resource *srcRes = resourcePool.lookupRef(srcD->handles[0]);
4670 if (!dstRes || !srcRes)
4673 barrierGen.addTransitionBarrier(srcD->handles[0], D3D12_RESOURCE_STATE_COPY_SOURCE);
4674 barrierGen.addTransitionBarrier(dstD->handles[0], D3D12_RESOURCE_STATE_COPY_DEST);
4675 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4677 cbD->cmdList->CopyBufferRegion(dstRes->resource, u.offset,
4678 srcRes->resource, u.srcOffset,
4680 }
else if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::Clear) {
4681 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, u.buf);
4682 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
4684 QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[0]);
4688 bool gotNewHeap =
false;
4689 if (!ensureShaderVisibleDescriptorHeapCapacity(&shaderVisibleCbvSrvUavHeap,
4690 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
4691 currentFrameSlot, 1, &gotNewHeap))
4696 bindShaderVisibleHeaps(cbD);
4698 const QD3D12Descriptor cpuDesc = cbvSrvUavPool.allocate(1);
4699 if (!cpuDesc.isValid())
4701 const QD3D12Descriptor gpuDesc = shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot].get(1);
4704 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
4705 uavDesc.Format = DXGI_FORMAT_R32_UINT;
4706 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
4707 uavDesc.Buffer.FirstElement = u.offset / 4u;
4708 uavDesc.Buffer.NumElements = u.readSize / 4u;
4709 dev->CreateUnorderedAccessView(res->resource,
nullptr, &uavDesc, cpuDesc.cpuHandle);
4710 dev->CopyDescriptorsSimple(1, gpuDesc.cpuHandle, cpuDesc.cpuHandle,
4711 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
4713 if (res->state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS && res->uavUsage)
4714 barrierGen.enqueueUavBarrier(cbD, bufD->handles[0]);
4715 barrierGen.addTransitionBarrier(bufD->handles[0], D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4716 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4718 const UINT values[4] = { u.fillValue32(), u.fillValue32(), u.fillValue32(), u.fillValue32() };
4719 cbD->cmdList->ClearUnorderedAccessViewUint(gpuDesc.gpuHandle, cpuDesc.cpuHandle,
4720 res->resource, values, 0,
nullptr);
4722 res->uavUsage = QD3D12Resource::UavUsageWrite;
4724 releaseQueue.deferredReleaseViews(&cbvSrvUavPool, cpuDesc, 1);
4728 for (
int opIdx = 0; opIdx < ud->activeTextureOpCount; ++opIdx) {
4729 const QRhiResourceUpdateBatchPrivate::TextureOp &u(ud->textureOps[opIdx]);
4730 if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::Upload) {
4731 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, u.dst);
4732 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4733 QD3D12Resource *res = resourcePool.lookupRef(texD->handle);
4736 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATE_COPY_DEST);
4737 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4738 for (
const auto &subres : u.subresDesc) {
4739 const int layer = subres.layer;
4740 const int level = subres.level;
4741 const QRhiTextureSubresourceUploadDescription &subresDesc(subres.desc);
4742 D3D12_SUBRESOURCE_FOOTPRINT footprint = {};
4743 footprint.Format = res->desc.Format;
4744 footprint.Depth = 1;
4745 quint32 totalBytes = 0;
4747 QSize subresSize = subresDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
4748 : subresDesc.sourceSize();
4749 const QPoint srcPos = subresDesc.sourceTopLeft();
4750 QPoint dstPos = subresDesc.destinationTopLeft();
4752 if (subresDesc.image().isNull() && !subresDesc.data().isEmpty()) {
4753 if (isCompressedFormat(texD->m_format)) {
4754 subresSize = clampedCompressedSubResourceUploadSizeForSourceData(
4755 texD->m_format, subresSize, subresDesc.data().size());
4757 subresSize = clampedSubResourceUploadSize(subresSize, dstPos, level, texD->m_pixelSize);
4758 quint32 bytesPerPixel = 0;
4759 textureFormatInfo(texD->m_format, subresSize,
nullptr,
nullptr, &bytesPerPixel);
4760 subresSize = clampedSubResourceUploadSizeForSourceData(subresSize,
4761 subresDesc.dataStride(),
4763 subresDesc.data().size());
4765 if (subresSize.isEmpty())
4769 if (!subresDesc.image().isNull()) {
4770 const QImage img = subresDesc.image();
4771 const int bpl = img.bytesPerLine();
4772 footprint.RowPitch = aligned<UINT>(bpl, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
4773 totalBytes = footprint.RowPitch * img.height();
4774 }
else if (!subresDesc.data().isEmpty() && isCompressedFormat(texD->m_format)) {
4777 compressedFormatInfo(texD->m_format, subresSize, &bpl,
nullptr, &blockDim);
4778 footprint.RowPitch = aligned<UINT>(bpl, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
4779 const int rowCount = aligned(subresSize.height(), blockDim.height()) / blockDim.height();
4780 totalBytes = footprint.RowPitch * rowCount;
4781 }
else if (!subresDesc.data().isEmpty()) {
4783 if (subresDesc.dataStride())
4784 bpl = subresDesc.dataStride();
4786 textureFormatInfo(texD->m_format, subresSize, &bpl,
nullptr,
nullptr);
4787 footprint.RowPitch = aligned<UINT>(bpl, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
4788 totalBytes = footprint.RowPitch * subresSize.height();
4790 qWarning(
"Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
4794 const quint32 allocSize = QD3D12StagingArea::allocSizeForArray(totalBytes, 1);
4795 QD3D12StagingArea::Allocation stagingAlloc;
4796 recordSmallStagingAreaDemand(allocSize);
4797 if (smallStagingAreas[currentFrameSlot].remainingCapacity() >= allocSize)
4798 stagingAlloc = smallStagingAreas[currentFrameSlot].get(allocSize);
4800 std::optional<QD3D12StagingArea> ownStagingArea;
4801 if (!stagingAlloc.isValid()) {
4802 ownStagingArea = QD3D12StagingArea();
4803 if (!ownStagingArea->create(
this, allocSize, D3D12_HEAP_TYPE_UPLOAD))
4805 stagingAlloc = ownStagingArea->get(allocSize);
4806 if (!stagingAlloc.isValid()) {
4807 ownStagingArea->destroy();
4812 D3D12_TEXTURE_COPY_LOCATION dst;
4813 dst.pResource = res->resource;
4814 dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
4815 dst.SubresourceIndex = calcSubresource(UINT(level), is3D ? 0u : UINT(layer), texD->mipLevelCount);
4816 D3D12_TEXTURE_COPY_LOCATION src;
4817 src.pResource = stagingAlloc.buffer;
4818 src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
4819 src.PlacedFootprint.Offset = stagingAlloc.bufferOffset;
4823 if (!subresDesc.image().isNull()) {
4824 const QImage img = subresDesc.image();
4825 const int bpc = qMax(1, img.depth() / 8);
4826 const int bpl = img.bytesPerLine();
4828 QSize size = subresDesc.sourceSize().isEmpty() ? img.size() : subresDesc.sourceSize();
4829 size.setWidth(qMin(size.width(), img.width() - srcPos.x()));
4830 size.setHeight(qMin(size.height(), img.height() - srcPos.y()));
4831 size = clampedSubResourceUploadSize(size, dstPos, level, texD->m_pixelSize);
4833 footprint.Width = size.width();
4834 footprint.Height = size.height();
4838 srcBox.right = UINT(size.width());
4839 srcBox.bottom = UINT(size.height());
4843 const uchar *imgPtr = img.constBits();
4844 const quint32 lineBytes = size.width() * bpc;
4845 for (
int y = 0, h = size.height(); y < h; ++y) {
4846 memcpy(stagingAlloc.p + y * footprint.RowPitch,
4847 imgPtr + srcPos.x() * bpc + (y + srcPos.y()) * bpl,
4850 }
else if (!subresDesc.data().isEmpty() && isCompressedFormat(texD->m_format)) {
4853 compressedFormatInfo(texD->m_format, subresSize, &bpl,
nullptr, &blockDim);
4855 dstPos.setX(aligned(dstPos.x(), blockDim.width()));
4856 dstPos.setY(aligned(dstPos.y(), blockDim.height()));
4861 srcBox.right = aligned(subresSize.width(), blockDim.width());
4862 srcBox.bottom = aligned(subresSize.height(), blockDim.height());
4867 footprint.Width = aligned(subresSize.width(), blockDim.width());
4868 footprint.Height = aligned(subresSize.height(), blockDim.height());
4870 const quint32 copyBytes = qMin(bpl, footprint.RowPitch);
4871 const QByteArray imgData = subresDesc.data();
4872 const char *imgPtr = imgData.constData();
4873 const int rowCount = aligned(subresSize.height(), blockDim.height()) / blockDim.height();
4874 for (
int y = 0; y < rowCount; ++y) {
4875 const quint64 srcOffset = quint64(y) * bpl;
4876 if (srcOffset >= quint64(imgData.size()))
4878 const quint32 n = quint32(qMin(quint64(copyBytes),
4879 quint64(imgData.size()) - srcOffset));
4880 memcpy(stagingAlloc.p + y * footprint.RowPitch, imgPtr + srcOffset, n);
4882 }
else if (!subresDesc.data().isEmpty()) {
4885 srcBox.right = subresSize.width();
4886 srcBox.bottom = subresSize.height();
4890 footprint.Width = subresSize.width();
4891 footprint.Height = subresSize.height();
4894 if (subresDesc.dataStride())
4895 bpl = subresDesc.dataStride();
4897 textureFormatInfo(texD->m_format, subresSize, &bpl,
nullptr,
nullptr);
4899 const quint32 copyBytes = qMin(bpl, footprint.RowPitch);
4900 const QByteArray data = subresDesc.data();
4901 const char *imgPtr = data.constData();
4902 for (
int y = 0, h = subresSize.height(); y < h; ++y) {
4907 const quint64 srcOffset = quint64(y) * bpl;
4908 if (srcOffset >= quint64(data.size()))
4910 const quint32 n = quint32(qMin(quint64(copyBytes),
4911 quint64(data.size()) - srcOffset));
4912 memcpy(stagingAlloc.p + y * footprint.RowPitch, imgPtr + srcOffset, n);
4916 src.PlacedFootprint.Footprint = footprint;
4918 cbD->cmdList->CopyTextureRegion(&dst,
4921 is3D ? UINT(layer) : 0u,
4925 if (ownStagingArea.has_value())
4926 ownStagingArea->destroyWithDeferredRelease(&releaseQueue);
4928 }
else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::Copy) {
4929 Q_ASSERT(u.src && u.dst);
4930 QD3D12Texture *srcD = QRHI_RES(QD3D12Texture, u.src);
4931 QD3D12Texture *dstD = QRHI_RES(QD3D12Texture, u.dst);
4932 const bool srcIs3D = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4933 const bool dstIs3D = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4934 QD3D12Resource *srcRes = resourcePool.lookupRef(srcD->handle);
4935 QD3D12Resource *dstRes = resourcePool.lookupRef(dstD->handle);
4936 if (!srcRes || !dstRes)
4939 barrierGen.addTransitionBarrier(srcD->handle, D3D12_RESOURCE_STATE_COPY_SOURCE);
4940 barrierGen.addTransitionBarrier(dstD->handle, D3D12_RESOURCE_STATE_COPY_DEST);
4941 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4943 const UINT srcSubresource = calcSubresource(UINT(u.desc.sourceLevel()),
4944 srcIs3D ? 0u : UINT(u.desc.sourceLayer()),
4945 srcD->mipLevelCount);
4946 const UINT dstSubresource = calcSubresource(UINT(u.desc.destinationLevel()),
4947 dstIs3D ? 0u : UINT(u.desc.destinationLayer()),
4948 dstD->mipLevelCount);
4949 const QPoint dp = u.desc.destinationTopLeft();
4950 const QSize mipSize = q->sizeForMipLevel(u.desc.sourceLevel(), srcD->m_pixelSize);
4951 const QSize copySize = u.desc.pixelSize().isEmpty() ? mipSize : u.desc.pixelSize();
4952 const QPoint sp = u.desc.sourceTopLeft();
4955 srcBox.left = UINT(sp.x());
4956 srcBox.top = UINT(sp.y());
4957 srcBox.front = srcIs3D ? UINT(u.desc.sourceLayer()) : 0u;
4959 srcBox.right = srcBox.left + UINT(copySize.width());
4960 srcBox.bottom = srcBox.top + UINT(copySize.height());
4961 srcBox.back = srcBox.front + 1;
4963 D3D12_TEXTURE_COPY_LOCATION src;
4964 src.pResource = srcRes->resource;
4965 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
4966 src.SubresourceIndex = srcSubresource;
4967 D3D12_TEXTURE_COPY_LOCATION dst;
4968 dst.pResource = dstRes->resource;
4969 dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
4970 dst.SubresourceIndex = dstSubresource;
4972 cbD->cmdList->CopyTextureRegion(&dst,
4975 dstIs3D ? UINT(u.desc.destinationLayer()) : 0u,
4978 }
else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::Read) {
4979 QD3D12Readback readback;
4980 readback.frameSlot = currentFrameSlot;
4981 readback.result = u.result;
4983 QD3D12ObjectHandle srcHandle;
4986 if (u.rb.texture()) {
4987 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, u.rb.texture());
4988 if (texD->sampleDesc.Count > 1) {
4989 qWarning(
"Multisample texture cannot be read back");
4992 is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4993 const QRect levelRect({0, 0}, q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize));
4994 readback.format = texD->m_format;
4995 rect = u.rb.rect().isValid() ? u.rb.rect() : levelRect;
4996 if (isDepthTextureFormat(readback.format)) {
5001 rect = rect.intersected(levelRect);
5002 readback.cropOrigin = rect.topLeft();
5004 srcHandle = texD->handle;
5006 Q_ASSERT(currentSwapChain);
5007 if (u.rb.rect().isValid())
5010 rect = QRect({0, 0}, currentSwapChain->pixelSize);
5011 readback.format = swapchainReadbackTextureFormat(currentSwapChain->colorFormat,
nullptr);
5012 if (readback.format == QRhiTexture::UnknownFormat)
5014 srcHandle = currentSwapChain->colorBuffers[currentSwapChain->currentBackBufferIndex];
5016 readback.pixelSize = rect.size();
5018 textureFormatInfo(readback.format,
5020 &readback.bytesPerLine,
5022 &readback.bytesPerPixel);
5024 QD3D12Resource *srcRes = resourcePool.lookupRef(srcHandle);
5035 const bool combinedDepthStencil = u.rb.texture() && isStencilSupportingFormat(readback.format);
5036 const bool depthTexture = u.rb.texture() && isDepthTextureFormat(readback.format);
5038 const UINT subresource = calcSubresource(UINT(u.rb.level()),
5039 is3D ? 0u : UINT(u.rb.layer()),
5040 srcRes->desc.MipLevels);
5041 D3D12_PLACED_SUBRESOURCE_FOOTPRINT layout;
5044 UINT64 totalBytes = 0;
5045 dev->GetCopyableFootprints(&srcRes->desc, subresource, 1, 0,
5046 &layout,
nullptr,
nullptr, &totalBytes);
5047 readback.stagingRowPitch = layout.Footprint.RowPitch;
5049 UINT stencilSubresource = 0;
5050 D3D12_PLACED_SUBRESOURCE_FOOTPRINT stencilLayout;
5051 UINT64 stencilTotalBytes = 0;
5052 if (combinedDepthStencil) {
5053 stencilSubresource = subresource
5054 + srcRes->desc.MipLevels * UINT(srcRes->desc.DepthOrArraySize);
5055 dev->GetCopyableFootprints(&srcRes->desc, stencilSubresource, 1, 0,
5056 &stencilLayout,
nullptr,
nullptr, &stencilTotalBytes);
5057 readback.stencilStagingRowPitch = stencilLayout.Footprint.RowPitch;
5060 const quint32 allocSize = aligned<quint32>(totalBytes, QD3D12StagingArea::ALIGNMENT)
5061 + (combinedDepthStencil ? aligned<quint32>(stencilTotalBytes, QD3D12StagingArea::ALIGNMENT) : 0);
5062 if (!readback.staging.create(
this, allocSize, D3D12_HEAP_TYPE_READBACK)) {
5063 if (u.result->completed)
5064 u.result->completed();
5067 QD3D12StagingArea::Allocation stagingAlloc = readback.staging.get(totalBytes);
5068 QD3D12StagingArea::Allocation stencilStagingAlloc;
5069 if (combinedDepthStencil)
5070 stencilStagingAlloc = readback.staging.get(stencilTotalBytes);
5071 if (!stagingAlloc.isValid() || (combinedDepthStencil && !stencilStagingAlloc.isValid())) {
5072 readback.staging.destroy();
5073 if (u.result->completed)
5074 u.result->completed();
5077 Q_ASSERT(stagingAlloc.bufferOffset == 0);
5078 readback.stencilStagingOffset = stencilStagingAlloc.bufferOffset;
5080 barrierGen.addTransitionBarrier(srcHandle, D3D12_RESOURCE_STATE_COPY_SOURCE);
5081 barrierGen.enqueueBufferedTransitionBarriers(cbD);
5083 D3D12_TEXTURE_COPY_LOCATION dst;
5084 dst.pResource = stagingAlloc.buffer;
5085 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
5086 dst.PlacedFootprint.Offset = 0;
5087 dst.PlacedFootprint.Footprint = layout.Footprint;
5089 D3D12_TEXTURE_COPY_LOCATION src;
5090 src.pResource = srcRes->resource;
5091 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
5092 src.SubresourceIndex = subresource;
5094 D3D12_BOX srcBox = {};
5095 srcBox.left = UINT(rect.left());
5096 srcBox.top = UINT(rect.top());
5097 srcBox.front = is3D ? UINT(u.rb.layer()) : 0u;
5099 srcBox.right = srcBox.left + UINT(rect.width());
5100 srcBox.bottom = srcBox.top + UINT(rect.height());
5101 srcBox.back = srcBox.front + 1;
5104 const D3D12_BOX *srcBoxPtr = depthTexture ?
nullptr : &srcBox;
5106 cbD->cmdList->CopyTextureRegion(&dst, 0, 0, 0, &src, srcBoxPtr);
5108 if (combinedDepthStencil) {
5109 D3D12_TEXTURE_COPY_LOCATION stencilDst;
5110 stencilDst.pResource = stencilStagingAlloc.buffer;
5111 stencilDst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
5112 stencilDst.PlacedFootprint.Offset = stencilStagingAlloc.bufferOffset;
5113 stencilDst.PlacedFootprint.Footprint = stencilLayout.Footprint;
5115 D3D12_TEXTURE_COPY_LOCATION stencilSrc;
5116 stencilSrc.pResource = srcRes->resource;
5117 stencilSrc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
5118 stencilSrc.SubresourceIndex = stencilSubresource;
5120 cbD->cmdList->CopyTextureRegion(&stencilDst, 0, 0, 0, &stencilSrc, srcBoxPtr);
5123 activeReadbacks.append(readback);
5124 }
else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::GenMips) {
5125 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, u.dst);
5126 Q_ASSERT(texD->flags().testFlag(QRhiTexture::UsedWithGenerateMips));
5132 QD3D12Resource *res = resourcePool.lookupRef(texD->handle);
5133 if (res && texD->mipLevelCount >= 2
5134 && (res->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET))
5136 const bool is3D = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
5137 const UINT layerCount = is3D ? 1u : UINT(res->desc.DepthOrArraySize);
5138 QBitArray &initialized(texD->subresourceInitialized);
5139 QVarLengthArray<UINT, 16> subresourcesToDiscard;
5140 for (UINT layer = 0; layer < layerCount; ++layer) {
5141 for (UINT level = 1; level < texD->mipLevelCount; ++level) {
5142 const UINT subresource = calcSubresource(level, layer, texD->mipLevelCount);
5143 if (
int(subresource) >= initialized.size())
5144 initialized.resize(
int(subresource) + 1);
5145 if (!initialized.testBit(
int(subresource))) {
5146 initialized.setBit(
int(subresource));
5147 subresourcesToDiscard.append(subresource);
5151 if (!subresourcesToDiscard.isEmpty()) {
5153 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
5154 barrierGen.enqueueBufferedTransitionBarriers(cbD);
5155 for (UINT subresource : subresourcesToDiscard) {
5156 D3D12_DISCARD_REGION region = {};
5157 region.FirstSubresource = subresource;
5158 region.NumSubresources = 1;
5159 cbD->cmdList->DiscardResource(res->resource, ®ion);
5164 if (texD->flags().testFlag(QRhiTexture::ThreeDimensional))
5165 mipmapGen3D.generate(cbD, texD->handle);
5167 mipmapGen.generate(cbD, texD->handle);
5174void QRhiD3D12::finishActiveReadbacks(
bool forced)
5176 QVarLengthArray<std::function<
void()>, 4> completedCallbacks;
5178 for (
int i = activeReadbacks.size() - 1; i >= 0; --i) {
5179 QD3D12Readback &readback(activeReadbacks[i]);
5180 if (forced || currentFrameSlot == readback.frameSlot || readback.frameSlot < 0) {
5181 readback.result->format = readback.format;
5182 readback.result->pixelSize = readback.pixelSize;
5183 readback.result->data.resize(
int(readback.byteSize));
5185 if (readback.format != QRhiTexture::UnknownFormat) {
5186 if (isStencilSupportingFormat(readback.format)) {
5198 const quint8 *depthBase = readback.staging.mem.p
5199 + readback.cropOrigin.y() * readback.stagingRowPitch
5200 + readback.cropOrigin.x() * 4;
5201 const quint8 *stencilBase = readback.staging.mem.p + readback.stencilStagingOffset
5202 + readback.cropOrigin.y() * readback.stencilStagingRowPitch
5203 + readback.cropOrigin.x();
5204 char *dst = readback.result->data.data();
5205 const int w = readback.pixelSize.width();
5206 const int h = readback.pixelSize.height();
5207 if (readback.format == QRhiTexture::D32FS8) {
5210 for (
int y = 0; y < h; ++y) {
5211 const quint8 *depthRow = depthBase + y * readback.stagingRowPitch;
5212 const quint8 *stencilRow = stencilBase + y * readback.stencilStagingRowPitch;
5213 for (
int x = 0; x < w; ++x) {
5214 const quint32 stencilWord = stencilRow[x];
5215 char *dstPixel = dst + (y * w + x) * 8;
5216 memcpy(dstPixel, depthRow + x * 4,
sizeof(quint32));
5217 memcpy(dstPixel + 4, &stencilWord,
sizeof(quint32));
5223 for (
int y = 0; y < h; ++y) {
5224 const quint8 *depthRow = depthBase + y * readback.stagingRowPitch;
5225 const quint8 *stencilRow = stencilBase + y * readback.stencilStagingRowPitch;
5226 for (
int x = 0; x < w; ++x) {
5231 memcpy(&depthWord, depthRow + x * 4,
sizeof(quint32));
5232 const quint32 combined = ((depthWord & 0x00FFFFFFu) << 8) | stencilRow[x];
5233 memcpy(dst + (y * w + x) * 4, &combined,
sizeof(quint32));
5238 quint8 *dstPtr =
reinterpret_cast<quint8 *>(readback.result->data.data());
5239 const quint8 *srcPtr = readback.staging.mem.p
5240 + readback.cropOrigin.y() * readback.stagingRowPitch
5241 + readback.cropOrigin.x() * readback.bytesPerPixel;
5242 const quint32 lineSize = qMin(readback.bytesPerLine, readback.stagingRowPitch);
5243 for (
int y = 0, h = readback.pixelSize.height(); y < h; ++y)
5244 memcpy(dstPtr + y * readback.bytesPerLine, srcPtr + y * readback.stagingRowPitch, lineSize);
5245 if (readback.format == QRhiTexture::D24) {
5249 char *p = readback.result->data.data();
5250 for (qsizetype px = 0, count = readback.result->data.size() / 4; px < count; ++px)
5251 qToUnaligned((qFromUnaligned<quint32>(p + px * 4) & 0x00FFFFFFu) << 8, p + px * 4);
5255 memcpy(readback.result->data.data(), readback.staging.mem.p, readback.byteSize);
5258 readback.staging.destroy();
5260 if (readback.result->completed)
5261 completedCallbacks.append(readback.result->completed);
5263 activeReadbacks.remove(i);
5267 for (
auto f : completedCallbacks)
5271bool QRhiD3D12::ensureShaderVisibleDescriptorHeapCapacity(QD3D12ShaderVisibleDescriptorHeap *h,
5272 D3D12_DESCRIPTOR_HEAP_TYPE type,
5274 quint32 neededDescriptorCount,
5282 if (h->perFrameHeapSlice[frameSlot].remainingCapacity() < neededDescriptorCount) {
5283 const quint32 newPerFrameSize = qMax(h->perFrameHeapSlice[frameSlot].capacity * 2,
5284 neededDescriptorCount);
5285 QD3D12ShaderVisibleDescriptorHeap newHeap;
5286 if (!newHeap.create(dev, type, newPerFrameSize)) {
5287 qWarning(
"Could not create new shader-visible descriptor heap");
5290 h->destroyWithDeferredRelease(&releaseQueue);
5297void QRhiD3D12::resetAndResizeSmallStagingArea(
int frameSlot)
5299 QD3D12StagingArea &area(smallStagingAreas[frameSlot]);
5305 const quint32 needed = smallStagingAreaBytesNeeded[frameSlot];
5306 smallStagingAreaBytesNeeded[frameSlot] = 0;
5308 quint32 newCapacity = 0;
5309 if (needed > area.capacity) {
5312 smallStagingAreaLowDemandFrames[frameSlot] = 0;
5313 newCapacity = qMin(qNextPowerOfTwo(needed), SMALL_STAGING_AREA_BYTES_PER_FRAME_MAX);
5314 }
else if (needed <= area.capacity / 4 && area.capacity > SMALL_STAGING_AREA_BYTES_PER_FRAME_START) {
5315 if (++smallStagingAreaLowDemandFrames[frameSlot] >= SMALL_STAGING_AREA_LOW_DEMAND_FRAMES) {
5316 smallStagingAreaLowDemandFrames[frameSlot] = 0;
5317 newCapacity = qMax(area.capacity / 2, SMALL_STAGING_AREA_BYTES_PER_FRAME_START);
5320 smallStagingAreaLowDemandFrames[frameSlot] = 0;
5323 if (newCapacity && newCapacity != area.capacity) {
5324 QD3D12StagingArea newArea;
5325 if (newArea.create(
this, aligned(newCapacity, QD3D12StagingArea::ALIGNMENT), D3D12_HEAP_TYPE_UPLOAD)) {
5326 area.destroyWithDeferredRelease(&releaseQueue);
5328 QString decoratedName = QLatin1String(
"Small staging area buffer/");
5329 decoratedName += QString::number(frameSlot);
5330 area.mem.buffer->SetName(
reinterpret_cast<LPCWSTR>(decoratedName.utf16()));
5339void QRhiD3D12::bindShaderVisibleHeaps(QD3D12CommandBuffer *cbD)
5341 ID3D12DescriptorHeap *heaps[] = {
5342 shaderVisibleCbvSrvUavHeap.heap.heap,
5343 samplerMgr.shaderVisibleSamplerHeap.heap.heap
5345 cbD->cmdList->SetDescriptorHeaps(2, heaps);
5348QD3D12Buffer::QD3D12Buffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
5349 : QRhiBuffer(rhi, type, usage, size)
5353QD3D12Buffer::~QD3D12Buffer()
5358void QD3D12Buffer::destroy()
5360 if (handles[0].isNull())
5363 QRHI_RES_RHI(QRhiD3D12);
5372 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
5374 rhiD->releaseQueue.deferredReleaseResource(handles[i]);
5376 pendingHostWrites[i].clear();
5380 rhiD->unregisterResource(
this);
5383bool QD3D12Buffer::create()
5385 if (!handles[0].isNull())
5388 if (m_usage.testFlag(QRhiBuffer::UniformBuffer) && m_type != Dynamic) {
5389 qWarning(
"UniformBuffer must always be Dynamic");
5393 if (m_usage.testFlag(QRhiBuffer::StorageBuffer) && m_type == Dynamic) {
5394 qWarning(
"StorageBuffer cannot be combined with Dynamic");
5398 const quint32 nonZeroSize = m_size <= 0 ? 256 : m_size;
5399 const quint32 roundedSize = aligned(nonZeroSize, m_usage.testFlag(QRhiBuffer::UniformBuffer) ? 256u : 4u);
5401 UINT resourceFlags = D3D12_RESOURCE_FLAG_NONE;
5402 if (m_usage.testFlag(QRhiBuffer::StorageBuffer))
5403 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
5405 QRHI_RES_RHI(QRhiD3D12);
5407 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
5408 if (i == 0 || m_type == Dynamic) {
5409 D3D12_RESOURCE_DESC resourceDesc = {};
5410 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
5411 resourceDesc.Width = roundedSize;
5412 resourceDesc.Height = 1;
5413 resourceDesc.DepthOrArraySize = 1;
5414 resourceDesc.MipLevels = 1;
5415 resourceDesc.Format = DXGI_FORMAT_UNKNOWN;
5416 resourceDesc.SampleDesc = { 1, 0 };
5417 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
5418 resourceDesc.Flags = D3D12_RESOURCE_FLAGS(resourceFlags);
5419 ID3D12Resource *resource =
nullptr;
5420 D3D12MA::Allocation *allocation =
nullptr;
5422 D3D12_HEAP_TYPE heapType = m_type == Dynamic
5423 ? D3D12_HEAP_TYPE_UPLOAD
5424 : D3D12_HEAP_TYPE_DEFAULT;
5425 D3D12_RESOURCE_STATES resourceState = m_type == Dynamic
5426 ? D3D12_RESOURCE_STATE_GENERIC_READ
5427 : D3D12_RESOURCE_STATE_COMMON;
5428 hr = rhiD->vma.createResource(heapType,
5434 reinterpret_cast<
void **>(&resource));
5437 if (!m_objectName.isEmpty()) {
5438 QString decoratedName = QString::fromUtf8(m_objectName);
5439 if (m_type == Dynamic) {
5440 decoratedName += QLatin1Char(
'/');
5441 decoratedName += QString::number(i);
5443 resource->SetName(
reinterpret_cast<LPCWSTR>(decoratedName.utf16()));
5445 void *cpuMemPtr =
nullptr;
5446 if (m_type == Dynamic) {
5448 hr = resource->Map(0,
nullptr, &cpuMemPtr);
5450 qWarning(
"Map() failed to dynamic buffer");
5451 resource->Release();
5453 allocation->Release();
5457 handles[i] = QD3D12Resource::addToPool(&rhiD->resourcePool,
5465 qWarning(
"Failed to create buffer: '%s' Type was %d, size was %u, using D3D12MA was %d.",
5466 qPrintable(QSystemError::windowsComString(hr)),
5469 int(rhiD->vma.isUsingD3D12MA()));
5474 rhiD->registerResource(
this);
5478QRhiBuffer::NativeBuffer QD3D12Buffer::nativeBuffer()
5481 Q_ASSERT(
sizeof(b.objects) /
sizeof(b.objects[0]) >= size_t(QD3D12_FRAMES_IN_FLIGHT));
5482 QRHI_RES_RHI(QRhiD3D12);
5483 if (m_type == Dynamic) {
5484 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
5485 executeHostWritesForFrameSlot(i);
5486 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handles[i]))
5487 b.objects[i] = res->resource;
5489 b.objects[i] =
nullptr;
5491 b.slotCount = QD3D12_FRAMES_IN_FLIGHT;
5494 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handles[0]))
5495 b.objects[0] = res->resource;
5497 b.objects[0] =
nullptr;
5502char *QD3D12Buffer::beginFullDynamicBufferUpdateForCurrentFrame()
5510 Q_ASSERT(m_type == Dynamic);
5511 QRHI_RES_RHI(QRhiD3D12);
5512 Q_ASSERT(rhiD->inFrame);
5513 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handles[rhiD->currentFrameSlot]))
5514 return static_cast<
char *>(res->cpuMapPtr);
5519void QD3D12Buffer::endFullDynamicBufferUpdateForCurrentFrame()
5524void QD3D12Buffer::executeHostWritesForFrameSlot(
int frameSlot)
5526 if (pendingHostWrites[frameSlot].isEmpty())
5529 Q_ASSERT(m_type == QRhiBuffer::Dynamic);
5530 QRHI_RES_RHI(QRhiD3D12);
5531 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handles[frameSlot])) {
5532 Q_ASSERT(res->cpuMapPtr);
5533 for (
const QD3D12Buffer::HostWrite &u : std::as_const(pendingHostWrites[frameSlot]))
5534 memcpy(
static_cast<
char *>(res->cpuMapPtr) + u.offset, u.data.constData(), u.data.size());
5536 pendingHostWrites[frameSlot].clear();
5539static inline DXGI_FORMAT toD3DTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
5541 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
5543 case QRhiTexture::RGBA8:
5544 return srgb ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
5545 case QRhiTexture::BGRA8:
5546 return srgb ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : DXGI_FORMAT_B8G8R8A8_UNORM;
5547 case QRhiTexture::R8:
5548 return DXGI_FORMAT_R8_UNORM;
5549 case QRhiTexture::R8SI:
5550 return DXGI_FORMAT_R8_SINT;
5551 case QRhiTexture::R8UI:
5552 return DXGI_FORMAT_R8_UINT;
5553 case QRhiTexture::RG8:
5554 return DXGI_FORMAT_R8G8_UNORM;
5555 case QRhiTexture::R16:
5556 return DXGI_FORMAT_R16_UNORM;
5557 case QRhiTexture::RG16:
5558 return DXGI_FORMAT_R16G16_UNORM;
5559 case QRhiTexture::RED_OR_ALPHA8:
5560 return DXGI_FORMAT_R8_UNORM;
5562 case QRhiTexture::RGBA16F:
5563 return DXGI_FORMAT_R16G16B16A16_FLOAT;
5564 case QRhiTexture::RGBA32F:
5565 return DXGI_FORMAT_R32G32B32A32_FLOAT;
5566 case QRhiTexture::R16F:
5567 return DXGI_FORMAT_R16_FLOAT;
5568 case QRhiTexture::R32F:
5569 return DXGI_FORMAT_R32_FLOAT;
5571 case QRhiTexture::RGB10A2:
5572 return DXGI_FORMAT_R10G10B10A2_UNORM;
5574 case QRhiTexture::R32SI:
5575 return DXGI_FORMAT_R32_SINT;
5576 case QRhiTexture::R32UI:
5577 return DXGI_FORMAT_R32_UINT;
5578 case QRhiTexture::RG32SI:
5579 return DXGI_FORMAT_R32G32_SINT;
5580 case QRhiTexture::RG32UI:
5581 return DXGI_FORMAT_R32G32_UINT;
5582 case QRhiTexture::RGBA32SI:
5583 return DXGI_FORMAT_R32G32B32A32_SINT;
5584 case QRhiTexture::RGBA32UI:
5585 return DXGI_FORMAT_R32G32B32A32_UINT;
5587 case QRhiTexture::D16:
5588 return DXGI_FORMAT_R16_TYPELESS;
5589 case QRhiTexture::D24:
5590 return DXGI_FORMAT_R24G8_TYPELESS;
5591 case QRhiTexture::D24S8:
5592 return DXGI_FORMAT_R24G8_TYPELESS;
5593 case QRhiTexture::D32F:
5594 return DXGI_FORMAT_R32_TYPELESS;
5595 case QRhiTexture::Format::D32FS8:
5596 return DXGI_FORMAT_R32G8X24_TYPELESS;
5598 case QRhiTexture::BC1:
5599 return srgb ? DXGI_FORMAT_BC1_UNORM_SRGB : DXGI_FORMAT_BC1_UNORM;
5600 case QRhiTexture::BC2:
5601 return srgb ? DXGI_FORMAT_BC2_UNORM_SRGB : DXGI_FORMAT_BC2_UNORM;
5602 case QRhiTexture::BC3:
5603 return srgb ? DXGI_FORMAT_BC3_UNORM_SRGB : DXGI_FORMAT_BC3_UNORM;
5604 case QRhiTexture::BC4:
5605 return DXGI_FORMAT_BC4_UNORM;
5606 case QRhiTexture::BC5:
5607 return DXGI_FORMAT_BC5_UNORM;
5608 case QRhiTexture::BC6H:
5609 return DXGI_FORMAT_BC6H_UF16;
5610 case QRhiTexture::BC7:
5611 return srgb ? DXGI_FORMAT_BC7_UNORM_SRGB : DXGI_FORMAT_BC7_UNORM;
5613 case QRhiTexture::ETC2_RGB8:
5614 case QRhiTexture::ETC2_RGB8A1:
5615 case QRhiTexture::ETC2_RGBA8:
5616 qWarning(
"QRhiD3D12 does not support ETC2 textures");
5617 return DXGI_FORMAT_R8G8B8A8_UNORM;
5619 case QRhiTexture::ASTC_4x4:
5620 case QRhiTexture::ASTC_5x4:
5621 case QRhiTexture::ASTC_5x5:
5622 case QRhiTexture::ASTC_6x5:
5623 case QRhiTexture::ASTC_6x6:
5624 case QRhiTexture::ASTC_8x5:
5625 case QRhiTexture::ASTC_8x6:
5626 case QRhiTexture::ASTC_8x8:
5627 case QRhiTexture::ASTC_10x5:
5628 case QRhiTexture::ASTC_10x6:
5629 case QRhiTexture::ASTC_10x8:
5630 case QRhiTexture::ASTC_10x10:
5631 case QRhiTexture::ASTC_12x10:
5632 case QRhiTexture::ASTC_12x12:
5633 qWarning(
"QRhiD3D12 does not support ASTC textures");
5634 return DXGI_FORMAT_R8G8B8A8_UNORM;
5639 return DXGI_FORMAT_R8G8B8A8_UNORM;
5642QD3D12RenderBuffer::QD3D12RenderBuffer(QRhiImplementation *rhi,
5644 const QSize &pixelSize,
5647 QRhiTexture::Format backingFormatHint)
5648 : QRhiRenderBuffer(rhi, type, pixelSize, sampleCount, flags, backingFormatHint)
5652QD3D12RenderBuffer::~QD3D12RenderBuffer()
5657void QD3D12RenderBuffer::destroy()
5659 if (handle.isNull())
5662 QRHI_RES_RHI(QRhiD3D12);
5665 rhiD->releaseQueue.deferredReleaseResourceWithViews(handle, &rhiD->rtvPool, rtv, 1);
5666 else if (dsv.isValid())
5667 rhiD->releaseQueue.deferredReleaseResourceWithViews(handle, &rhiD->dsvPool, dsv, 1);
5675 rhiD->unregisterResource(
this);
5678bool QD3D12RenderBuffer::create()
5680 if (!handle.isNull())
5683 if (m_pixelSize.isEmpty())
5686 QRHI_RES_RHI(QRhiD3D12);
5689 case QRhiRenderBuffer::Color:
5691 dxgiFormat = toD3DTextureFormat(backingFormat(), {});
5692 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, dxgiFormat);
5693 D3D12_RESOURCE_DESC resourceDesc = {};
5694 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
5695 resourceDesc.Width = UINT64(m_pixelSize.width());
5696 resourceDesc.Height = UINT(m_pixelSize.height());
5697 resourceDesc.DepthOrArraySize = 1;
5698 resourceDesc.MipLevels = 1;
5699 resourceDesc.Format = dxgiFormat;
5700 resourceDesc.SampleDesc = sampleDesc;
5701 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
5702 resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
5703 D3D12_CLEAR_VALUE clearValue = {};
5704 clearValue.Format = dxgiFormat;
5706 ID3D12Resource *resource =
nullptr;
5707 D3D12MA::Allocation *allocation =
nullptr;
5708 HRESULT hr = rhiD->vma.createResource(D3D12_HEAP_TYPE_DEFAULT,
5710 D3D12_RESOURCE_STATE_RENDER_TARGET,
5713 __uuidof(ID3D12Resource),
5714 reinterpret_cast<
void **>(&resource));
5716 qWarning(
"Failed to create color buffer: %s", qPrintable(QSystemError::windowsComString(hr)));
5719 handle = QD3D12Resource::addToPool(&rhiD->resourcePool, resource, D3D12_RESOURCE_STATE_RENDER_TARGET, allocation);
5720 rtv = rhiD->rtvPool.allocate(1);
5723 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
5724 rtvDesc.Format = dxgiFormat;
5725 rtvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D12_RTV_DIMENSION_TEXTURE2DMS
5726 : D3D12_RTV_DIMENSION_TEXTURE2D;
5727 rhiD->dev->CreateRenderTargetView(resource, &rtvDesc, rtv.cpuHandle);
5730 case QRhiRenderBuffer::DepthStencil:
5732 dxgiFormat = DS_FORMAT;
5733 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, dxgiFormat);
5734 D3D12_RESOURCE_DESC resourceDesc = {};
5735 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
5736 resourceDesc.Width = UINT64(m_pixelSize.width());
5737 resourceDesc.Height = UINT(m_pixelSize.height());
5738 resourceDesc.DepthOrArraySize = 1;
5739 resourceDesc.MipLevels = 1;
5740 resourceDesc.Format = dxgiFormat;
5741 resourceDesc.SampleDesc = sampleDesc;
5742 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
5743 resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
5744 if (m_flags.testFlag(UsedWithSwapChainOnly))
5745 resourceDesc.Flags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
5746 D3D12_CLEAR_VALUE clearValue = {};
5747 clearValue.Format = dxgiFormat;
5748 clearValue.DepthStencil.Depth = 1.0f;
5749 clearValue.DepthStencil.Stencil = 0;
5750 ID3D12Resource *resource =
nullptr;
5751 D3D12MA::Allocation *allocation =
nullptr;
5752 HRESULT hr = rhiD->vma.createResource(D3D12_HEAP_TYPE_DEFAULT,
5754 D3D12_RESOURCE_STATE_DEPTH_WRITE,
5757 __uuidof(ID3D12Resource),
5758 reinterpret_cast<
void **>(&resource));
5760 qWarning(
"Failed to create depth-stencil buffer: %s", qPrintable(QSystemError::windowsComString(hr)));
5763 handle = QD3D12Resource::addToPool(&rhiD->resourcePool, resource, D3D12_RESOURCE_STATE_DEPTH_WRITE, allocation);
5764 dsv = rhiD->dsvPool.allocate(1);
5767 D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
5768 dsvDesc.Format = dxgiFormat;
5769 dsvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D12_DSV_DIMENSION_TEXTURE2DMS
5770 : D3D12_DSV_DIMENSION_TEXTURE2D;
5771 rhiD->dev->CreateDepthStencilView(resource, &dsvDesc, dsv.cpuHandle);
5776 if (!m_objectName.isEmpty()) {
5777 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handle)) {
5778 const QString name = QString::fromUtf8(m_objectName);
5779 res->resource->SetName(
reinterpret_cast<LPCWSTR>(name.utf16()));
5784 rhiD->registerResource(
this);
5788QRhiTexture::Format QD3D12RenderBuffer::backingFormat()
const
5790 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
5791 return m_backingFormatHint;
5793 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
5796QD3D12Texture::QD3D12Texture(QRhiImplementation *rhi, Format format,
const QSize &pixelSize,
int depth,
5797 int arraySize,
int sampleCount, Flags flags)
5798 : QRhiTexture(rhi, format, pixelSize, depth, arraySize, sampleCount, flags)
5802QD3D12Texture::~QD3D12Texture()
5807void QD3D12Texture::destroy()
5809 if (handle.isNull())
5812 QRHI_RES_RHI(QRhiD3D12);
5814 rhiD->releaseQueue.deferredReleaseResourceWithViews(handle, &rhiD->cbvSrvUavPool, srv, 1);
5818 subresourceInitialized.clear();
5821 rhiD->unregisterResource(
this);
5824static inline DXGI_FORMAT toD3DDepthTextureSRVFormat(QRhiTexture::Format format)
5827 case QRhiTexture::Format::D16:
5828 return DXGI_FORMAT_R16_UNORM;
5829 case QRhiTexture::Format::D24:
5830 return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
5831 case QRhiTexture::Format::D24S8:
5832 return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
5833 case QRhiTexture::Format::D32F:
5834 return DXGI_FORMAT_R32_FLOAT;
5835 case QRhiTexture::Format::D32FS8:
5836 return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
5840 Q_UNREACHABLE_RETURN(DXGI_FORMAT_R32_FLOAT);
5843static inline DXGI_FORMAT toD3DDepthTextureDSVFormat(QRhiTexture::Format format)
5847 case QRhiTexture::Format::D16:
5848 return DXGI_FORMAT_D16_UNORM;
5849 case QRhiTexture::Format::D24:
5850 return DXGI_FORMAT_D24_UNORM_S8_UINT;
5851 case QRhiTexture::Format::D24S8:
5852 return DXGI_FORMAT_D24_UNORM_S8_UINT;
5853 case QRhiTexture::Format::D32F:
5854 return DXGI_FORMAT_D32_FLOAT;
5855 case QRhiTexture::Format::D32FS8:
5856 return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
5860 Q_UNREACHABLE_RETURN(DXGI_FORMAT_D32_FLOAT);
5863bool QD3D12Texture::prepareCreate(QSize *adjustedSize)
5865 if (!handle.isNull())
5868 QRHI_RES_RHI(QRhiD3D12);
5869 if (!rhiD->isTextureFormatSupported(m_format, m_flags))
5872 const bool isDepth = isDepthTextureFormat(m_format);
5873 const bool isCube = m_flags.testFlag(CubeMap);
5874 const bool is3D = m_flags.testFlag(ThreeDimensional);
5875 const bool isArray = m_flags.testFlag(TextureArray);
5876 const bool hasMipMaps = m_flags.testFlag(MipMapped);
5877 const bool is1D = m_flags.testFlag(OneDimensional);
5879 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
5880 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
5882 dxgiFormat = toD3DTextureFormat(m_format, m_flags);
5884 srvFormat = toD3DDepthTextureSRVFormat(m_format);
5885 rtFormat = toD3DDepthTextureDSVFormat(m_format);
5887 srvFormat = dxgiFormat;
5888 rtFormat = dxgiFormat;
5890 if (m_writeViewFormat.format != UnknownFormat) {
5892 rtFormat = toD3DDepthTextureDSVFormat(m_writeViewFormat.format);
5894 rtFormat = toD3DTextureFormat(m_writeViewFormat.format, m_writeViewFormat.srgb ? sRGB : Flags());
5896 if (m_readViewFormat.format != UnknownFormat) {
5898 srvFormat = toD3DDepthTextureSRVFormat(m_readViewFormat.format);
5900 srvFormat = toD3DTextureFormat(m_readViewFormat.format, m_readViewFormat.srgb ? sRGB : Flags());
5903 mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1);
5904 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, dxgiFormat);
5905 if (sampleDesc.Count > 1) {
5907 qWarning(
"Cubemap texture cannot be multisample");
5911 qWarning(
"3D texture cannot be multisample");
5915 qWarning(
"Multisample texture cannot have mipmaps");
5919 if (isDepth && hasMipMaps) {
5920 qWarning(
"Depth texture cannot have mipmaps");
5923 if (isCube && is3D) {
5924 qWarning(
"Texture cannot be both cube and 3D");
5927 if (isArray && is3D) {
5928 qWarning(
"Texture cannot be both array and 3D");
5931 if (isCube && is1D) {
5932 qWarning(
"Texture cannot be both cube and 1D");
5936 qWarning(
"Texture cannot be both 1D and 3D");
5939 if (m_depth > 1 && !is3D) {
5940 qWarning(
"Texture cannot have a depth of %d when it is not 3D", m_depth);
5943 if (m_arraySize > 0 && !isArray) {
5944 qWarning(
"Texture cannot have an array size of %d when it is not an array", m_arraySize);
5947 if (m_arraySize < 1 && isArray) {
5948 qWarning(
"Texture is an array but array size is %d", m_arraySize);
5952 if (!rhiD->textureFormatInfo(m_format, size,
nullptr,
nullptr,
nullptr))
5956 *adjustedSize = size;
5961bool QD3D12Texture::finishCreate()
5963 QRHI_RES_RHI(QRhiD3D12);
5964 const bool isCube = m_flags.testFlag(CubeMap);
5965 const bool is3D = m_flags.testFlag(ThreeDimensional);
5966 const bool isArray = m_flags.testFlag(TextureArray);
5967 const bool is1D = m_flags.testFlag(OneDimensional);
5969 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
5970 srvDesc.Format = srvFormat;
5971 srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
5974 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
5975 srvDesc.TextureCube.MipLevels = mipLevelCount;
5979 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
5980 srvDesc.Texture1DArray.MipLevels = mipLevelCount;
5981 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
5982 srvDesc.Texture1DArray.FirstArraySlice = UINT(m_arrayRangeStart);
5983 srvDesc.Texture1DArray.ArraySize = UINT(m_arrayRangeLength);
5985 srvDesc.Texture1DArray.FirstArraySlice = 0;
5986 srvDesc.Texture1DArray.ArraySize = UINT(qMax(0, m_arraySize));
5989 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
5990 srvDesc.Texture1D.MipLevels = mipLevelCount;
5992 }
else if (isArray) {
5993 if (sampleDesc.Count > 1) {
5994 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY;
5995 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
5996 srvDesc.Texture2DMSArray.FirstArraySlice = UINT(m_arrayRangeStart);
5997 srvDesc.Texture2DMSArray.ArraySize = UINT(m_arrayRangeLength);
5999 srvDesc.Texture2DMSArray.FirstArraySlice = 0;
6000 srvDesc.Texture2DMSArray.ArraySize = UINT(qMax(0, m_arraySize));
6003 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
6004 srvDesc.Texture2DArray.MipLevels = mipLevelCount;
6005 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
6006 srvDesc.Texture2DArray.FirstArraySlice = UINT(m_arrayRangeStart);
6007 srvDesc.Texture2DArray.ArraySize = UINT(m_arrayRangeLength);
6009 srvDesc.Texture2DArray.FirstArraySlice = 0;
6010 srvDesc.Texture2DArray.ArraySize = UINT(qMax(0, m_arraySize));
6014 if (sampleDesc.Count > 1) {
6015 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS;
6017 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
6018 srvDesc.Texture3D.MipLevels = mipLevelCount;
6020 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
6021 srvDesc.Texture2D.MipLevels = mipLevelCount;
6026 srv = rhiD->cbvSrvUavPool.allocate(1);
6030 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handle)) {
6031 rhiD->dev->CreateShaderResourceView(res->resource, &srvDesc, srv.cpuHandle);
6032 if (!m_objectName.isEmpty()) {
6033 const QString name = QString::fromUtf8(m_objectName);
6034 res->resource->SetName(
reinterpret_cast<LPCWSTR>(name.utf16()));
6044bool QD3D12Texture::create()
6047 if (!prepareCreate(&size))
6050 const bool isDepth = isDepthTextureFormat(m_format);
6051 const bool isCube = m_flags.testFlag(CubeMap);
6052 const bool is3D = m_flags.testFlag(ThreeDimensional);
6053 const bool isArray = m_flags.testFlag(TextureArray);
6054 const bool is1D = m_flags.testFlag(OneDimensional);
6056 QRHI_RES_RHI(QRhiD3D12);
6058 bool needsOptimizedClearValueSpecified =
false;
6059 UINT resourceFlags = 0;
6060 if (m_flags.testFlag(RenderTarget) || sampleDesc.Count > 1) {
6062 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
6064 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
6065 needsOptimizedClearValueSpecified =
true;
6067 if (m_flags.testFlag(UsedWithGenerateMips)) {
6069 qWarning(
"Depth texture cannot have mipmaps generated");
6072 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
6074 if (m_flags.testFlag(UsedWithLoadStore))
6075 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
6077 D3D12_RESOURCE_DESC resourceDesc = {};
6078 resourceDesc.Dimension = is1D ? D3D12_RESOURCE_DIMENSION_TEXTURE1D
6079 : (is3D ? D3D12_RESOURCE_DIMENSION_TEXTURE3D
6080 : D3D12_RESOURCE_DIMENSION_TEXTURE2D);
6081 resourceDesc.Width = UINT64(size.width());
6082 resourceDesc.Height = UINT(size.height());
6083 resourceDesc.DepthOrArraySize = isCube ? 6
6084 : (isArray ? UINT(qMax(0, m_arraySize))
6085 : (is3D ? qMax(1, m_depth)
6087 resourceDesc.MipLevels = mipLevelCount;
6088 resourceDesc.Format = dxgiFormat;
6089 resourceDesc.SampleDesc = sampleDesc;
6090 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
6091 resourceDesc.Flags = D3D12_RESOURCE_FLAGS(resourceFlags);
6092 D3D12_CLEAR_VALUE clearValue = {};
6093 clearValue.Format = dxgiFormat;
6095 clearValue.Format = toD3DDepthTextureDSVFormat(m_format);
6096 clearValue.DepthStencil.Depth = 1.0f;
6097 clearValue.DepthStencil.Stencil = 0;
6099 ID3D12Resource *resource =
nullptr;
6100 D3D12MA::Allocation *allocation =
nullptr;
6101 HRESULT hr = rhiD->vma.createResource(D3D12_HEAP_TYPE_DEFAULT,
6103 D3D12_RESOURCE_STATE_COMMON,
6104 needsOptimizedClearValueSpecified ? &clearValue :
nullptr,
6106 __uuidof(ID3D12Resource),
6107 reinterpret_cast<
void **>(&resource));
6109 qWarning(
"Failed to create texture: '%s'"
6110 " Dim was %d Size was %ux%u Depth/ArraySize was %u MipLevels was %u Format was %d Sample count was %d",
6111 qPrintable(QSystemError::windowsComString(hr)),
6112 int(resourceDesc.Dimension),
6113 uint(resourceDesc.Width),
6114 uint(resourceDesc.Height),
6115 uint(resourceDesc.DepthOrArraySize),
6116 uint(resourceDesc.MipLevels),
6117 int(resourceDesc.Format),
6118 int(resourceDesc.SampleDesc.Count));
6119 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
6120 rhiD->deviceLost =
true;
6124 handle = QD3D12Resource::addToPool(&rhiD->resourcePool, resource, D3D12_RESOURCE_STATE_COMMON, allocation);
6126 if (!finishCreate())
6129 rhiD->registerResource(
this);
6133bool QD3D12Texture::createFrom(QRhiTexture::NativeTexture src)
6138 if (!prepareCreate())
6141 ID3D12Resource *resource =
reinterpret_cast<ID3D12Resource *>(src.object);
6142 D3D12_RESOURCE_STATES state = D3D12_RESOURCE_STATES(src.layout);
6144 QRHI_RES_RHI(QRhiD3D12);
6145 handle = QD3D12Resource::addNonOwningToPool(&rhiD->resourcePool, resource, state);
6147 if (!finishCreate())
6150 rhiD->registerResource(
this);
6154QRhiTexture::NativeTexture QD3D12Texture::nativeTexture()
6156 QRHI_RES_RHI(QRhiD3D12);
6157 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handle))
6158 return { quint64(res->resource),
int(res->state) };
6163void QD3D12Texture::setNativeLayout(
int layout)
6165 QRHI_RES_RHI(QRhiD3D12);
6166 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handle))
6167 res->state = D3D12_RESOURCE_STATES(layout);
6170QD3D12Sampler::QD3D12Sampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode,
6171 AddressMode u, AddressMode v, AddressMode w)
6172 : QRhiSampler(rhi, magFilter, minFilter, mipmapMode, u, v, w)
6176QD3D12Sampler::~QD3D12Sampler()
6181void QD3D12Sampler::destroy()
6183 shaderVisibleDescriptor = {};
6185 QRHI_RES_RHI(QRhiD3D12);
6187 rhiD->unregisterResource(
this);
6190static inline D3D12_FILTER toD3DFilter(QRhiSampler::Filter minFilter, QRhiSampler::Filter magFilter, QRhiSampler::Filter mipFilter)
6192 if (minFilter == QRhiSampler::Nearest) {
6193 if (magFilter == QRhiSampler::Nearest) {
6194 if (mipFilter == QRhiSampler::Linear)
6195 return D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR;
6197 return D3D12_FILTER_MIN_MAG_MIP_POINT;
6199 if (mipFilter == QRhiSampler::Linear)
6200 return D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR;
6202 return D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
6205 if (magFilter == QRhiSampler::Nearest) {
6206 if (mipFilter == QRhiSampler::Linear)
6207 return D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
6209 return D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT;
6211 if (mipFilter == QRhiSampler::Linear)
6212 return D3D12_FILTER_MIN_MAG_MIP_LINEAR;
6214 return D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
6217 Q_UNREACHABLE_RETURN(D3D12_FILTER_MIN_MAG_MIP_LINEAR);
6220static inline D3D12_TEXTURE_ADDRESS_MODE toD3DAddressMode(QRhiSampler::AddressMode m)
6223 case QRhiSampler::Repeat:
6224 return D3D12_TEXTURE_ADDRESS_MODE_WRAP;
6225 case QRhiSampler::ClampToEdge:
6226 return D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
6227 case QRhiSampler::Mirror:
6228 return D3D12_TEXTURE_ADDRESS_MODE_MIRROR;
6230 Q_UNREACHABLE_RETURN(D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
6233static inline D3D12_COMPARISON_FUNC toD3DTextureComparisonFunc(QRhiSampler::CompareOp op)
6236 case QRhiSampler::Never:
6237 return D3D12_COMPARISON_FUNC_NEVER;
6238 case QRhiSampler::Less:
6239 return D3D12_COMPARISON_FUNC_LESS;
6240 case QRhiSampler::Equal:
6241 return D3D12_COMPARISON_FUNC_EQUAL;
6242 case QRhiSampler::LessOrEqual:
6243 return D3D12_COMPARISON_FUNC_LESS_EQUAL;
6244 case QRhiSampler::Greater:
6245 return D3D12_COMPARISON_FUNC_GREATER;
6246 case QRhiSampler::NotEqual:
6247 return D3D12_COMPARISON_FUNC_NOT_EQUAL;
6248 case QRhiSampler::GreaterOrEqual:
6249 return D3D12_COMPARISON_FUNC_GREATER_EQUAL;
6250 case QRhiSampler::Always:
6251 return D3D12_COMPARISON_FUNC_ALWAYS;
6253 Q_UNREACHABLE_RETURN(D3D12_COMPARISON_FUNC_NEVER);
6256bool QD3D12Sampler::create()
6259 desc.Filter = toD3DFilter(m_minFilter, m_magFilter, m_mipmapMode);
6260 if (m_compareOp != Never)
6261 desc.Filter = D3D12_FILTER(desc.Filter | 0x80);
6262 desc.AddressU = toD3DAddressMode(m_addressU);
6263 desc.AddressV = toD3DAddressMode(m_addressV);
6264 desc.AddressW = toD3DAddressMode(m_addressW);
6265 desc.MaxAnisotropy = 1.0f;
6266 desc.ComparisonFunc = toD3DTextureComparisonFunc(m_compareOp);
6267 desc.MaxLOD = m_mipmapMode == None ? 0.0f : 10000.0f;
6271 shaderVisibleDescriptor = {};
6275 QRHI_RES_RHI(QRhiD3D12);
6276 rhiD->registerResource(
this,
false);
6280QD3D12Descriptor QD3D12Sampler::lookupOrCreateShaderVisibleDescriptor()
6282 if (!shaderVisibleDescriptor.isValid()) {
6283 QRHI_RES_RHI(QRhiD3D12);
6284 shaderVisibleDescriptor = rhiD->samplerMgr.getShaderVisibleDescriptor(desc);
6286 return shaderVisibleDescriptor;
6289QD3D12ShadingRateMap::QD3D12ShadingRateMap(QRhiImplementation *rhi)
6290 : QRhiShadingRateMap(rhi)
6294QD3D12ShadingRateMap::~QD3D12ShadingRateMap()
6299void QD3D12ShadingRateMap::destroy()
6301 if (handle.isNull())
6307bool QD3D12ShadingRateMap::createFrom(QRhiTexture *src)
6309 if (!handle.isNull())
6312 handle = QRHI_RES(QD3D12Texture, src)->handle;
6317QD3D12TextureRenderTarget::QD3D12TextureRenderTarget(QRhiImplementation *rhi,
6318 const QRhiTextureRenderTargetDescription &desc,
6320 : QRhiTextureRenderTarget(rhi, desc, flags),
6325QD3D12TextureRenderTarget::~QD3D12TextureRenderTarget()
6330void QD3D12TextureRenderTarget::destroy()
6332 if (!rtv[0].isValid() && !dsv.isValid())
6335 QRHI_RES_RHI(QRhiD3D12);
6336 if (dsv.isValid()) {
6337 if (ownsDsv && rhiD)
6338 rhiD->releaseQueue.deferredReleaseViews(&rhiD->dsvPool, dsv, 1);
6342 for (
int i = 0; i < QD3D12RenderTargetData::MAX_COLOR_ATTACHMENTS; ++i) {
6343 if (rtv[i].isValid()) {
6344 if (ownsRtv[i] && rhiD)
6345 rhiD->releaseQueue.deferredReleaseViews(&rhiD->rtvPool, rtv[i], 1);
6351 rhiD->unregisterResource(
this);
6354QRhiRenderPassDescriptor *QD3D12TextureRenderTarget::newCompatibleRenderPassDescriptor()
6358 QD3D12RenderPassDescriptor *rpD =
new QD3D12RenderPassDescriptor(m_rhi);
6360 rpD->colorAttachmentCount = 0;
6361 for (
auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it) {
6362 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, it->texture());
6363 QD3D12RenderBuffer *rbD = QRHI_RES(QD3D12RenderBuffer, it->renderBuffer());
6365 rpD->colorFormat[rpD->colorAttachmentCount] = texD->rtFormat;
6367 rpD->colorFormat[rpD->colorAttachmentCount] = rbD->dxgiFormat;
6368 rpD->colorAttachmentCount += 1;
6371 rpD->hasDepthStencil =
false;
6372 if (m_desc.depthStencilBuffer()) {
6373 rpD->hasDepthStencil =
true;
6374 rpD->dsFormat = QD3D12RenderBuffer::DS_FORMAT;
6375 }
else if (m_desc.depthTexture()) {
6376 QD3D12Texture *depthTexD = QRHI_RES(QD3D12Texture, m_desc.depthTexture());
6377 rpD->hasDepthStencil =
true;
6378 rpD->dsFormat = toD3DDepthTextureDSVFormat(depthTexD->format());
6381 rpD->hasShadingRateMap = m_desc.shadingRateMap() !=
nullptr;
6383 rpD->updateSerializedFormat();
6385 QRHI_RES_RHI(QRhiD3D12);
6386 rhiD->registerResource(rpD);
6390bool QD3D12TextureRenderTarget::create()
6392 if (rtv[0].isValid() || dsv.isValid())
6395 QRHI_RES_RHI(QRhiD3D12);
6396 Q_ASSERT(m_desc.colorAttachmentCount() > 0 || m_desc.depthTexture());
6397 Q_ASSERT(!m_desc.depthStencilBuffer() || !m_desc.depthTexture());
6398 const bool hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
6399 d.colorAttCount = 0;
6402 for (
auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
6403 d.colorAttCount += 1;
6404 const QRhiColorAttachment &colorAtt(*it);
6405 QRhiTexture *texture = colorAtt.texture();
6406 QRhiRenderBuffer *rb = colorAtt.renderBuffer();
6407 Q_ASSERT(texture || rb);
6409 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, texture);
6410 QD3D12Resource *res = rhiD->resourcePool.lookupRef(texD->handle);
6412 qWarning(
"Could not look up texture handle for render target");
6415 const bool isMultiView = it->multiViewCount() >= 2;
6416 UINT layerCount = isMultiView ? UINT(it->multiViewCount()) : 1;
6417 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
6418 rtvDesc.Format = texD->rtFormat;
6419 if (texD->flags().testFlag(QRhiTexture::CubeMap)) {
6420 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
6421 rtvDesc.Texture2DArray.MipSlice = UINT(colorAtt.level());
6422 rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAtt.layer());
6423 rtvDesc.Texture2DArray.ArraySize = layerCount;
6424 }
else if (texD->flags().testFlag(QRhiTexture::OneDimensional)) {
6425 if (texD->flags().testFlag(QRhiTexture::TextureArray)) {
6426 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
6427 rtvDesc.Texture1DArray.MipSlice = UINT(colorAtt.level());
6428 rtvDesc.Texture1DArray.FirstArraySlice = UINT(colorAtt.layer());
6429 rtvDesc.Texture1DArray.ArraySize = layerCount;
6431 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D;
6432 rtvDesc.Texture1D.MipSlice = UINT(colorAtt.level());
6434 }
else if (texD->flags().testFlag(QRhiTexture::TextureArray)) {
6435 if (texD->sampleDesc.Count > 1) {
6436 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
6437 rtvDesc.Texture2DMSArray.FirstArraySlice = UINT(colorAtt.layer());
6438 rtvDesc.Texture2DMSArray.ArraySize = layerCount;
6440 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
6441 rtvDesc.Texture2DArray.MipSlice = UINT(colorAtt.level());
6442 rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAtt.layer());
6443 rtvDesc.Texture2DArray.ArraySize = layerCount;
6445 }
else if (texD->flags().testFlag(QRhiTexture::ThreeDimensional)) {
6446 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
6447 rtvDesc.Texture3D.MipSlice = UINT(colorAtt.level());
6448 rtvDesc.Texture3D.FirstWSlice = UINT(colorAtt.layer());
6449 rtvDesc.Texture3D.WSize = layerCount;
6451 if (texD->sampleDesc.Count > 1) {
6452 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
6454 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
6455 rtvDesc.Texture2D.MipSlice = UINT(colorAtt.level());
6458 rtv[attIndex] = rhiD->rtvPool.allocate(1);
6459 if (!rtv[attIndex].isValid()) {
6460 qWarning(
"Failed to allocate RTV for texture render target");
6463 rhiD->dev->CreateRenderTargetView(res->resource, &rtvDesc, rtv[attIndex].cpuHandle);
6464 ownsRtv[attIndex] =
true;
6465 if (attIndex == 0) {
6466 d.pixelSize = rhiD->q->sizeForMipLevel(colorAtt.level(), texD->pixelSize());
6467 d.sampleCount =
int(texD->sampleDesc.Count);
6470 QD3D12RenderBuffer *rbD = QRHI_RES(QD3D12RenderBuffer, rb);
6471 ownsRtv[attIndex] =
false;
6472 rtv[attIndex] = rbD->rtv;
6473 if (attIndex == 0) {
6474 d.pixelSize = rbD->pixelSize();
6475 d.sampleCount =
int(rbD->sampleDesc.Count);
6482 if (hasDepthStencil) {
6483 if (m_desc.depthTexture()) {
6485 QD3D12Texture *depthTexD = QRHI_RES(QD3D12Texture, m_desc.depthTexture());
6486 QD3D12Resource *res = rhiD->resourcePool.lookupRef(depthTexD->handle);
6488 qWarning(
"Could not look up depth texture handle");
6491 D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
6492 dsvDesc.Format = depthTexD->rtFormat;
6493 const bool isMultisample = depthTexD->sampleDesc.Count > 1;
6494 if (depthTexD->flags().testFlag(QRhiTexture::TextureArray)) {
6495 if (isMultisample) {
6496 dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
6497 if (m_desc.depthLayer() >= 0) {
6498 dsvDesc.Texture2DMSArray.FirstArraySlice = UINT(m_desc.depthLayer());
6499 dsvDesc.Texture2DMSArray.ArraySize = 1;
6500 }
else if (depthTexD->arrayRangeStart() >= 0 && depthTexD->arrayRangeLength() >= 0) {
6501 dsvDesc.Texture2DMSArray.FirstArraySlice = UINT(depthTexD->arrayRangeStart());
6502 dsvDesc.Texture2DMSArray.ArraySize = UINT(depthTexD->arrayRangeLength());
6504 dsvDesc.Texture2DMSArray.FirstArraySlice = 0;
6505 dsvDesc.Texture2DMSArray.ArraySize = UINT(qMax(0, depthTexD->arraySize()));
6508 dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
6509 if (m_desc.depthLayer() >= 0) {
6510 dsvDesc.Texture2DArray.FirstArraySlice = UINT(m_desc.depthLayer());
6511 dsvDesc.Texture2DArray.ArraySize = 1;
6512 }
else if (depthTexD->arrayRangeStart() >= 0 && depthTexD->arrayRangeLength() >= 0) {
6513 dsvDesc.Texture2DArray.FirstArraySlice = UINT(depthTexD->arrayRangeStart());
6514 dsvDesc.Texture2DArray.ArraySize = UINT(depthTexD->arrayRangeLength());
6516 dsvDesc.Texture2DArray.FirstArraySlice = 0;
6517 dsvDesc.Texture2DArray.ArraySize = UINT(qMax(0, depthTexD->arraySize()));
6522 dsvDesc.ViewDimension = isMultisample ? D3D12_DSV_DIMENSION_TEXTURE2DMS
6523 : D3D12_DSV_DIMENSION_TEXTURE2D;
6525 dsv = rhiD->dsvPool.allocate(1);
6526 if (!dsv.isValid()) {
6527 qWarning(
"Failed to allocate DSV for texture render target");
6530 rhiD->dev->CreateDepthStencilView(res->resource, &dsvDesc, dsv.cpuHandle);
6531 if (d.colorAttCount == 0) {
6532 d.pixelSize = depthTexD->pixelSize();
6533 d.sampleCount =
int(depthTexD->sampleDesc.Count);
6537 QD3D12RenderBuffer *depthRbD = QRHI_RES(QD3D12RenderBuffer, m_desc.depthStencilBuffer());
6538 dsv = depthRbD->dsv;
6539 if (d.colorAttCount == 0) {
6540 d.pixelSize = m_desc.depthStencilBuffer()->pixelSize();
6541 d.sampleCount =
int(depthRbD->sampleDesc.Count);
6549 D3D12_CPU_DESCRIPTOR_HANDLE nullDescHandle = { 0 };
6550 for (
int i = 0; i < QD3D12RenderTargetData::MAX_COLOR_ATTACHMENTS; ++i)
6551 d.rtv[i] = i < d.colorAttCount ? rtv[i].cpuHandle : nullDescHandle;
6552 d.dsv = dsv.cpuHandle;
6553 d.rp = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
6555 QRhiRenderTargetAttachmentTracker::updateResIdList<QD3D12Texture, QD3D12RenderBuffer>(m_desc, &d.currentResIdList);
6557 rhiD->registerResource(
this);
6561QSize QD3D12TextureRenderTarget::pixelSize()
const
6563 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QD3D12Texture, QD3D12RenderBuffer>(m_desc, d.currentResIdList))
6564 const_cast<QD3D12TextureRenderTarget *>(
this)->create();
6569float QD3D12TextureRenderTarget::devicePixelRatio()
const
6574int QD3D12TextureRenderTarget::sampleCount()
const
6576 return d.sampleCount;
6579QD3D12ShaderResourceBindings::QD3D12ShaderResourceBindings(QRhiImplementation *rhi)
6580 : QRhiShaderResourceBindings(rhi)
6584QD3D12ShaderResourceBindings::~QD3D12ShaderResourceBindings()
6589void QD3D12ShaderResourceBindings::destroy()
6591 bindingCache.reset();
6592 bindingCacheValid =
false;
6593 boundResourceData.clear();
6595 QRHI_RES_RHI(QRhiD3D12);
6597 rhiD->unregisterResource(
this);
6600bool QD3D12ShaderResourceBindings::create()
6602 QRHI_RES_RHI(QRhiD3D12);
6603 if (!rhiD->sanityCheckShaderResourceBindings(
this))
6606 rhiD->updateLayoutDesc(
this);
6608 boundResourceData.resize(m_bindings.count());
6609 for (BoundResourceData &bd : boundResourceData)
6612 bindingCache.reset();
6613 bindingCacheValid =
false;
6615 hasDynamicOffset =
false;
6616 for (
const QRhiShaderResourceBinding &b : std::as_const(m_bindings)) {
6617 const QRhiShaderResourceBinding::Data *bd = QRhiImplementation::shaderResourceBindingData(b);
6618 if (bd->type() == QRhiShaderResourceBinding::UniformBuffer && bd->ubuf().hasDynamicOffset) {
6619 hasDynamicOffset =
true;
6633 rhiD->registerResource(
this,
false);
6637void QD3D12ShaderResourceBindings::updateResources(UpdateFlags flags)
6641 Q_ASSERT(boundResourceData.count() == m_bindings.count());
6642 for (BoundResourceData &bd : boundResourceData)
6645 bindingCache.reset();
6646 bindingCacheValid =
false;
6656void QD3D12ShaderResourceBindings::visitUniformBuffer(QD3D12Stage s,
6657 const QRhiShaderResourceBinding::Data::UniformBufferData &,
6661 D3D12_ROOT_PARAMETER1 rootParam = {};
6662 rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
6663 rootParam.ShaderVisibility = qd3d12_stageToVisibility(s);
6664 rootParam.Descriptor.ShaderRegister = shaderRegister;
6665 rootParam.Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC;
6666 visitorData.cbParams[s].append(rootParam);
6669void QD3D12ShaderResourceBindings::visitTextures(QD3D12Stage s,
6670 const QRhiShaderResourceBinding::TextureAndSampler *,
6672 int baseShaderRegister)
6677 D3D12_DESCRIPTOR_RANGE1 range = {};
6678 range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
6679 range.NumDescriptors = UINT(count);
6680 range.BaseShaderRegister = baseShaderRegister;
6681 range.OffsetInDescriptorsFromTableStart = visitorData.currentSrvRangeOffset[s];
6682 visitorData.currentSrvRangeOffset[s] += UINT(count);
6683 visitorData.srvRanges[s].append(range);
6684 if (visitorData.srvRanges[s].count() == 1) {
6685 visitorData.srvTables[s].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
6686 visitorData.srvTables[s].ShaderVisibility = qd3d12_stageToVisibility(s);
6690void QD3D12ShaderResourceBindings::visitSamplers(QD3D12Stage s,
6691 const QRhiShaderResourceBinding::TextureAndSampler *,
6693 int baseShaderRegister)
6701 int &rangeStoreIdx(visitorData.samplerRangeHeads[s]);
6702 if (rangeStoreIdx == 16) {
6703 qWarning(
"Sampler binding count in QD3D12Stage %d exceeds the limit of 16, this is disallowed by QRhi", s);
6706 D3D12_DESCRIPTOR_RANGE1 range = {};
6707 range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
6708 range.NumDescriptors = UINT(count);
6709 range.BaseShaderRegister = baseShaderRegister;
6710 visitorData.samplerRanges[s][rangeStoreIdx] = range;
6711 D3D12_ROOT_PARAMETER1 param = {};
6712 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
6713 param.ShaderVisibility = qd3d12_stageToVisibility(s);
6714 param.DescriptorTable.NumDescriptorRanges = 1;
6715 param.DescriptorTable.pDescriptorRanges = &visitorData.samplerRanges[s][rangeStoreIdx];
6717 visitorData.samplerTables[s].append(param);
6720void QD3D12ShaderResourceBindings::visitStorageBuffer(QD3D12Stage s,
6721 const QRhiShaderResourceBinding::Data::StorageBufferData &,
6722 QD3D12ShaderResourceVisitor::StorageOp,
6725 D3D12_DESCRIPTOR_RANGE1 range = {};
6726 range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
6727 range.NumDescriptors = 1;
6728 range.BaseShaderRegister = shaderRegister;
6729 range.OffsetInDescriptorsFromTableStart = visitorData.currentUavRangeOffset[s];
6730 visitorData.currentUavRangeOffset[s] += 1;
6731 visitorData.uavRanges[s].append(range);
6732 if (visitorData.uavRanges[s].count() == 1) {
6733 visitorData.uavTables[s].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
6734 visitorData.uavTables[s].ShaderVisibility = qd3d12_stageToVisibility(s);
6738void QD3D12ShaderResourceBindings::visitStorageImage(QD3D12Stage s,
6739 const QRhiShaderResourceBinding::Data::StorageImageData &,
6740 QD3D12ShaderResourceVisitor::StorageOp,
6743 D3D12_DESCRIPTOR_RANGE1 range = {};
6744 range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
6745 range.NumDescriptors = 1;
6746 range.BaseShaderRegister = shaderRegister;
6747 range.OffsetInDescriptorsFromTableStart = visitorData.currentUavRangeOffset[s];
6748 visitorData.currentUavRangeOffset[s] += 1;
6749 visitorData.uavRanges[s].append(range);
6750 if (visitorData.uavRanges[s].count() == 1) {
6751 visitorData.uavTables[s].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
6752 visitorData.uavTables[s].ShaderVisibility = qd3d12_stageToVisibility(s);
6756static void qd3d12_setPushConstantInfo(QD3D12ShaderStageData *sd,
const QShader &shader,
const QShaderKey &key)
6758 const QList<QShaderDescription::PushConstantBlock> blocks = shader.description().pushConstantBlocks();
6759 if (blocks.isEmpty())
6761 sd->pushConstantRegister = shader.nativeShaderInfo(key).extraBufferBindings.value(
6762 QShaderPrivate::HlslPushConstantBufferBinding, -1);
6763 sd->pushConstantSize = quint32((blocks.first().size + 3) & ~3);
6766QD3D12ObjectHandle QD3D12ShaderResourceBindings::createRootSignature(
const QD3D12ShaderStageData *stageData,
6769 QRHI_RES_RHI(QRhiD3D12);
6783 QD3D12ShaderResourceVisitor visitor(
this, stageData, stageCount);
6787 using namespace std::placeholders;
6788 visitor.uniformBuffer = std::bind(&QD3D12ShaderResourceBindings::visitUniformBuffer,
this, _1, _2, _3, _4);
6789 visitor.textures = std::bind(&QD3D12ShaderResourceBindings::visitTextures,
this, _1, _2, _3, _4);
6790 visitor.samplers = std::bind(&QD3D12ShaderResourceBindings::visitSamplers,
this, _1, _2, _3, _4);
6791 visitor.storageBuffer = std::bind(&QD3D12ShaderResourceBindings::visitStorageBuffer,
this, _1, _2, _3, _4);
6792 visitor.storageImage = std::bind(&QD3D12ShaderResourceBindings::visitStorageImage,
this, _1, _2, _3, _4);
6816 QVarLengthArray<D3D12_ROOT_PARAMETER1, 4> rootParams;
6817 for (
int s = 0; s < 6; ++s) {
6818 if (!visitorData.cbParams[s].isEmpty())
6819 rootParams.append(visitorData.cbParams[s].constData(), visitorData.cbParams[s].count());
6821 for (
int s = 0; s < 6; ++s) {
6822 if (!visitorData.srvRanges[s].isEmpty()) {
6823 visitorData.srvTables[s].DescriptorTable.NumDescriptorRanges = visitorData.srvRanges[s].count();
6824 visitorData.srvTables[s].DescriptorTable.pDescriptorRanges = visitorData.srvRanges[s].constData();
6825 rootParams.append(visitorData.srvTables[s]);
6828 for (
int s = 0; s < 6; ++s) {
6829 if (!visitorData.samplerTables[s].isEmpty())
6830 rootParams.append(visitorData.samplerTables[s].constData(), visitorData.samplerTables[s].count());
6832 for (
int s = 0; s < 6; ++s) {
6833 if (!visitorData.uavRanges[s].isEmpty()) {
6834 visitorData.uavTables[s].DescriptorTable.NumDescriptorRanges = visitorData.uavRanges[s].count();
6835 visitorData.uavTables[s].DescriptorTable.pDescriptorRanges = visitorData.uavRanges[s].constData();
6836 rootParams.append(visitorData.uavTables[s]);
6842 pushConstantRootParamIndex = -1;
6843 UINT pushConstantReg = 0;
6844 quint32 pushConstantSize = 0;
6845 int pushConstantStages = 0;
6846 D3D12_SHADER_VISIBILITY pushConstantVis = D3D12_SHADER_VISIBILITY_ALL;
6847 for (
int stageIdx = 0; stageIdx < stageCount; ++stageIdx) {
6848 const QD3D12ShaderStageData &sd(stageData[stageIdx]);
6849 if (!sd.valid || !sd.pushConstantSize || sd.pushConstantRegister < 0)
6851 pushConstantReg = UINT(sd.pushConstantRegister);
6852 pushConstantSize = qMax(pushConstantSize, sd.pushConstantSize);
6853 pushConstantVis = qd3d12_stageToVisibility(sd.stage);
6854 ++pushConstantStages;
6856 if (pushConstantSize) {
6860 D3D12_ROOT_PARAMETER1 param = {};
6861 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
6862 param.ShaderVisibility = pushConstantStages > 1 ? D3D12_SHADER_VISIBILITY_ALL : pushConstantVis;
6863 param.Constants.ShaderRegister = pushConstantReg;
6864 param.Constants.Num32BitValues = pushConstantSize / 4;
6865 pushConstantRootParamIndex = rootParams.count();
6866 rootParams.append(param);
6869 D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsDesc = {};
6870 rsDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
6871 if (!rootParams.isEmpty()) {
6872 rsDesc.Desc_1_1.NumParameters = rootParams.count();
6873 rsDesc.Desc_1_1.pParameters = rootParams.constData();
6877 for (
int stageIdx = 0; stageIdx < stageCount; ++stageIdx) {
6878 if (stageData[stageIdx].valid && stageData[stageIdx].stage == VS)
6879 rsFlags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
6881 rsDesc.Desc_1_1.Flags = D3D12_ROOT_SIGNATURE_FLAGS(rsFlags);
6883 ID3DBlob *signature =
nullptr;
6884 HRESULT hr = D3D12SerializeVersionedRootSignature(&rsDesc, &signature,
nullptr);
6886 qWarning(
"Failed to serialize root signature: %s", qPrintable(QSystemError::windowsComString(hr)));
6889 ID3D12RootSignature *rootSig =
nullptr;
6890 hr = rhiD->dev->CreateRootSignature(0,
6891 signature->GetBufferPointer(),
6892 signature->GetBufferSize(),
6893 __uuidof(ID3D12RootSignature),
6894 reinterpret_cast<
void **>(&rootSig));
6895 signature->Release();
6897 qWarning(
"Failed to create root signature: %s", qPrintable(QSystemError::windowsComString(hr)));
6901 return QD3D12RootSignature::addToPool(&rhiD->rootSignaturePool, rootSig);
6913static inline void makeHlslTargetString(
char target[7],
const char stage[3],
int version)
6915 const int smMajor = version / 10;
6916 const int smMinor = version % 10;
6917 target[0] = stage[0];
6918 target[1] = stage[1];
6920 target[3] =
'0' + smMajor;
6922 target[5] =
'0' + smMinor;
6926enum class HlslCompileFlag
6928 WithDebugInfo = 0x01
6931static QByteArray legacyCompile(
const QShaderCode &hlslSource,
const char *target,
int flags, QString *error)
6933 static const pD3DCompile d3dCompile = QRhiD3D::resolveD3DCompile();
6935 qWarning(
"Unable to resolve function D3DCompile()");
6936 return QByteArray();
6939 ID3DBlob *bytecode =
nullptr;
6940 ID3DBlob *errors =
nullptr;
6941 UINT d3dCompileFlags = 0;
6942 if (flags &
int(HlslCompileFlag::WithDebugInfo))
6943 d3dCompileFlags |= D3DCOMPILE_DEBUG;
6945 HRESULT hr = d3dCompile(hlslSource.shader().constData(), SIZE_T(hlslSource.shader().size()),
6946 nullptr,
nullptr,
nullptr,
6947 hlslSource.entryPoint().constData(), target, d3dCompileFlags, 0, &bytecode, &errors);
6948 if (FAILED(hr) || !bytecode) {
6949 qWarning(
"HLSL shader compilation failed: 0x%x", uint(hr));
6951 *error = QString::fromUtf8(
static_cast<
const char *>(errors->GetBufferPointer()),
6952 int(errors->GetBufferSize()));
6955 return QByteArray();
6959 result.resize(
int(bytecode->GetBufferSize()));
6960 memcpy(result.data(), bytecode->GetBufferPointer(), size_t(result.size()));
6961 bytecode->Release();
6965#ifdef QRHI_D3D12_HAS_DXC
6968#define DXC_CP_UTF8 65001
6971#ifndef DXC_ARG_DEBUG
6972#define DXC_ARG_DEBUG L"-Zi"
6975static QByteArray dxcCompile(
const QShaderCode &hlslSource,
const char *target,
int flags, QString *error)
6977 static std::pair<IDxcCompiler *, IDxcLibrary *> dxc = QRhiD3D::createDxcCompiler();
6978 IDxcCompiler *compiler = dxc.first;
6980 qWarning(
"Unable to instantiate IDxcCompiler. Likely no dxcompiler.dll and dxil.dll present. "
6981 "Use windeployqt or try https://github.com/microsoft/DirectXShaderCompiler/releases");
6982 return QByteArray();
6984 IDxcLibrary *library = dxc.second;
6986 return QByteArray();
6988 IDxcBlobEncoding *sourceBlob =
nullptr;
6989 HRESULT hr = library->CreateBlobWithEncodingOnHeapCopy(hlslSource.shader().constData(),
6990 UINT32(hlslSource.shader().size()),
6994 qWarning(
"Failed to create source blob for dxc: 0x%x (%s)",
6996 qPrintable(QSystemError::windowsComString(hr)));
6997 return QByteArray();
7000 const QString entryPointStr = QString::fromLatin1(hlslSource.entryPoint());
7001 const QString targetStr = QString::fromLatin1(target);
7003 QVarLengthArray<LPCWSTR, 4> argPtrs;
7005 if (flags &
int(HlslCompileFlag::WithDebugInfo)) {
7006 debugArg = QString::fromUtf16(
reinterpret_cast<
const char16_t *>(DXC_ARG_DEBUG));
7007 argPtrs.append(
reinterpret_cast<LPCWSTR>(debugArg.utf16()));
7010 IDxcOperationResult *result =
nullptr;
7011 hr = compiler->Compile(sourceBlob,
7013 reinterpret_cast<LPCWSTR>(entryPointStr.utf16()),
7014 reinterpret_cast<LPCWSTR>(targetStr.utf16()),
7015 argPtrs.data(), argPtrs.count(),
7019 sourceBlob->Release();
7021 result->GetStatus(&hr);
7023 qWarning(
"HLSL shader compilation failed: 0x%x (%s)",
7025 qPrintable(QSystemError::windowsComString(hr)));
7027 IDxcBlobEncoding *errorsBlob =
nullptr;
7028 if (SUCCEEDED(result->GetErrorBuffer(&errorsBlob))) {
7030 *error = QString::fromUtf8(
static_cast<
const char *>(errorsBlob->GetBufferPointer()),
7031 int(errorsBlob->GetBufferSize()));
7032 errorsBlob->Release();
7036 return QByteArray();
7039 IDxcBlob *bytecode =
nullptr;
7040 if FAILED(result->GetResult(&bytecode)) {
7041 qWarning(
"No result from IDxcCompiler: 0x%x (%s)",
7043 qPrintable(QSystemError::windowsComString(hr)));
7044 return QByteArray();
7048 ba.resize(
int(bytecode->GetBufferSize()));
7049 memcpy(ba.data(), bytecode->GetBufferPointer(), size_t(ba.size()));
7050 bytecode->Release();
7056static QByteArray compileHlslShaderSource(
const QShader &shader,
7057 QShader::Variant shaderVariant,
7060 QShaderKey *usedShaderKey)
7063 const int shaderModelMax = 67;
7064 for (
int sm = shaderModelMax; sm >= 50; --sm) {
7065 for (QShader::Source type : { QShader::DxilShader, QShader::DxbcShader }) {
7066 QShaderKey key = { type, sm, shaderVariant };
7067 QShaderCode intermediateBytecodeShader = shader.shader(key);
7068 if (!intermediateBytecodeShader.shader().isEmpty()) {
7070 *usedShaderKey = key;
7071 return intermediateBytecodeShader.shader();
7076 QShaderCode hlslSource;
7078 for (
int sm = shaderModelMax; sm >= 50; --sm) {
7079 key = { QShader::HlslShader, sm, shaderVariant };
7080 hlslSource = shader.shader(key);
7081 if (!hlslSource.shader().isEmpty())
7085 if (hlslSource.shader().isEmpty()) {
7086 qWarning() <<
"No HLSL (shader model 6.7..5.0) code found in baked shader" << shader;
7087 return QByteArray();
7091 *usedShaderKey = key;
7094 switch (shader.stage()) {
7095 case QShader::VertexStage:
7096 makeHlslTargetString(target,
"vs", key.sourceVersion().version());
7098 case QShader::TessellationControlStage:
7099 makeHlslTargetString(target,
"hs", key.sourceVersion().version());
7101 case QShader::TessellationEvaluationStage:
7102 makeHlslTargetString(target,
"ds", key.sourceVersion().version());
7104 case QShader::GeometryStage:
7105 makeHlslTargetString(target,
"gs", key.sourceVersion().version());
7107 case QShader::FragmentStage:
7108 makeHlslTargetString(target,
"ps", key.sourceVersion().version());
7110 case QShader::ComputeStage:
7111 makeHlslTargetString(target,
"cs", key.sourceVersion().version());
7114 qWarning(
"compileHlslShaderSource: Unknown stage (%d)",
int(shader.stage()));
7115 return QByteArray();
7118 if (key.sourceVersion().version() >= 60) {
7119#ifdef QRHI_D3D12_HAS_DXC
7120 return dxcCompile(hlslSource, target, flags, error);
7122 qWarning(
"Attempted to runtime-compile HLSL source code for shader model >= 6.0 "
7123 "but the Qt build has no support for DXC. "
7124 "Rebuild Qt with a recent Windows SDK or switch to an MSVC build.");
7128 return legacyCompile(hlslSource, target, flags, error);
7131static inline UINT8 toD3DColorWriteMask(QRhiGraphicsPipeline::ColorMask c)
7134 if (c.testFlag(QRhiGraphicsPipeline::R))
7135 f |= D3D12_COLOR_WRITE_ENABLE_RED;
7136 if (c.testFlag(QRhiGraphicsPipeline::G))
7137 f |= D3D12_COLOR_WRITE_ENABLE_GREEN;
7138 if (c.testFlag(QRhiGraphicsPipeline::B))
7139 f |= D3D12_COLOR_WRITE_ENABLE_BLUE;
7140 if (c.testFlag(QRhiGraphicsPipeline::A))
7141 f |= D3D12_COLOR_WRITE_ENABLE_ALPHA;
7145static inline D3D12_BLEND toD3DBlendFactor(QRhiGraphicsPipeline::BlendFactor f,
bool rgb)
7154 case QRhiGraphicsPipeline::Zero:
7155 return D3D12_BLEND_ZERO;
7156 case QRhiGraphicsPipeline::One:
7157 return D3D12_BLEND_ONE;
7158 case QRhiGraphicsPipeline::SrcColor:
7159 return rgb ? D3D12_BLEND_SRC_COLOR : D3D12_BLEND_SRC_ALPHA;
7160 case QRhiGraphicsPipeline::OneMinusSrcColor:
7161 return rgb ? D3D12_BLEND_INV_SRC_COLOR : D3D12_BLEND_INV_SRC_ALPHA;
7162 case QRhiGraphicsPipeline::DstColor:
7163 return rgb ? D3D12_BLEND_DEST_COLOR : D3D12_BLEND_DEST_ALPHA;
7164 case QRhiGraphicsPipeline::OneMinusDstColor:
7165 return rgb ? D3D12_BLEND_INV_DEST_COLOR : D3D12_BLEND_INV_DEST_ALPHA;
7166 case QRhiGraphicsPipeline::SrcAlpha:
7167 return D3D12_BLEND_SRC_ALPHA;
7168 case QRhiGraphicsPipeline::OneMinusSrcAlpha:
7169 return D3D12_BLEND_INV_SRC_ALPHA;
7170 case QRhiGraphicsPipeline::DstAlpha:
7171 return D3D12_BLEND_DEST_ALPHA;
7172 case QRhiGraphicsPipeline::OneMinusDstAlpha:
7173 return D3D12_BLEND_INV_DEST_ALPHA;
7174 case QRhiGraphicsPipeline::ConstantColor:
7175 case QRhiGraphicsPipeline::ConstantAlpha:
7176 return D3D12_BLEND_BLEND_FACTOR;
7177 case QRhiGraphicsPipeline::OneMinusConstantColor:
7178 case QRhiGraphicsPipeline::OneMinusConstantAlpha:
7179 return D3D12_BLEND_INV_BLEND_FACTOR;
7180 case QRhiGraphicsPipeline::SrcAlphaSaturate:
7181 return D3D12_BLEND_SRC_ALPHA_SAT;
7182 case QRhiGraphicsPipeline::Src1Color:
7183 return rgb ? D3D12_BLEND_SRC1_COLOR : D3D12_BLEND_SRC1_ALPHA;
7184 case QRhiGraphicsPipeline::OneMinusSrc1Color:
7185 return rgb ? D3D12_BLEND_INV_SRC1_COLOR : D3D12_BLEND_INV_SRC1_ALPHA;
7186 case QRhiGraphicsPipeline::Src1Alpha:
7187 return D3D12_BLEND_SRC1_ALPHA;
7188 case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
7189 return D3D12_BLEND_INV_SRC1_ALPHA;
7191 Q_UNREACHABLE_RETURN(D3D12_BLEND_ZERO);
7194static inline D3D12_BLEND_OP toD3DBlendOp(QRhiGraphicsPipeline::BlendOp op)
7197 case QRhiGraphicsPipeline::Add:
7198 return D3D12_BLEND_OP_ADD;
7199 case QRhiGraphicsPipeline::Subtract:
7200 return D3D12_BLEND_OP_SUBTRACT;
7201 case QRhiGraphicsPipeline::ReverseSubtract:
7202 return D3D12_BLEND_OP_REV_SUBTRACT;
7203 case QRhiGraphicsPipeline::Min:
7204 return D3D12_BLEND_OP_MIN;
7205 case QRhiGraphicsPipeline::Max:
7206 return D3D12_BLEND_OP_MAX;
7208 Q_UNREACHABLE_RETURN(D3D12_BLEND_OP_ADD);
7211static inline D3D12_CULL_MODE toD3DCullMode(QRhiGraphicsPipeline::CullMode c)
7214 case QRhiGraphicsPipeline::None:
7215 return D3D12_CULL_MODE_NONE;
7216 case QRhiGraphicsPipeline::Front:
7217 return D3D12_CULL_MODE_FRONT;
7218 case QRhiGraphicsPipeline::Back:
7219 return D3D12_CULL_MODE_BACK;
7221 Q_UNREACHABLE_RETURN(D3D12_CULL_MODE_NONE);
7224static inline D3D12_FILL_MODE toD3DFillMode(QRhiGraphicsPipeline::PolygonMode mode)
7227 case QRhiGraphicsPipeline::Fill:
7228 return D3D12_FILL_MODE_SOLID;
7229 case QRhiGraphicsPipeline::Line:
7230 return D3D12_FILL_MODE_WIREFRAME;
7232 Q_UNREACHABLE_RETURN(D3D12_FILL_MODE_SOLID);
7235static inline D3D12_COMPARISON_FUNC toD3DCompareOp(QRhiGraphicsPipeline::CompareOp op)
7238 case QRhiGraphicsPipeline::Never:
7239 return D3D12_COMPARISON_FUNC_NEVER;
7240 case QRhiGraphicsPipeline::Less:
7241 return D3D12_COMPARISON_FUNC_LESS;
7242 case QRhiGraphicsPipeline::Equal:
7243 return D3D12_COMPARISON_FUNC_EQUAL;
7244 case QRhiGraphicsPipeline::LessOrEqual:
7245 return D3D12_COMPARISON_FUNC_LESS_EQUAL;
7246 case QRhiGraphicsPipeline::Greater:
7247 return D3D12_COMPARISON_FUNC_GREATER;
7248 case QRhiGraphicsPipeline::NotEqual:
7249 return D3D12_COMPARISON_FUNC_NOT_EQUAL;
7250 case QRhiGraphicsPipeline::GreaterOrEqual:
7251 return D3D12_COMPARISON_FUNC_GREATER_EQUAL;
7252 case QRhiGraphicsPipeline::Always:
7253 return D3D12_COMPARISON_FUNC_ALWAYS;
7255 Q_UNREACHABLE_RETURN(D3D12_COMPARISON_FUNC_ALWAYS);
7258static inline D3D12_STENCIL_OP toD3DStencilOp(QRhiGraphicsPipeline::StencilOp op)
7261 case QRhiGraphicsPipeline::StencilZero:
7262 return D3D12_STENCIL_OP_ZERO;
7263 case QRhiGraphicsPipeline::Keep:
7264 return D3D12_STENCIL_OP_KEEP;
7265 case QRhiGraphicsPipeline::Replace:
7266 return D3D12_STENCIL_OP_REPLACE;
7267 case QRhiGraphicsPipeline::IncrementAndClamp:
7268 return D3D12_STENCIL_OP_INCR_SAT;
7269 case QRhiGraphicsPipeline::DecrementAndClamp:
7270 return D3D12_STENCIL_OP_DECR_SAT;
7271 case QRhiGraphicsPipeline::Invert:
7272 return D3D12_STENCIL_OP_INVERT;
7273 case QRhiGraphicsPipeline::IncrementAndWrap:
7274 return D3D12_STENCIL_OP_INCR;
7275 case QRhiGraphicsPipeline::DecrementAndWrap:
7276 return D3D12_STENCIL_OP_DECR;
7278 Q_UNREACHABLE_RETURN(D3D12_STENCIL_OP_KEEP);
7281static inline D3D12_PRIMITIVE_TOPOLOGY toD3DTopology(QRhiGraphicsPipeline::Topology t,
int patchControlPointCount)
7284 case QRhiGraphicsPipeline::Triangles:
7285 return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
7286 case QRhiGraphicsPipeline::TriangleStrip:
7287 return D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
7288 case QRhiGraphicsPipeline::TriangleFan:
7289 qWarning(
"Triangle fans are not supported with D3D");
7290 return D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
7291 case QRhiGraphicsPipeline::Lines:
7292 return D3D_PRIMITIVE_TOPOLOGY_LINELIST;
7293 case QRhiGraphicsPipeline::LineStrip:
7294 return D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
7295 case QRhiGraphicsPipeline::Points:
7296 return D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
7297 case QRhiGraphicsPipeline::Patches:
7298 Q_ASSERT(patchControlPointCount >= 1 && patchControlPointCount <= 32);
7299 return D3D_PRIMITIVE_TOPOLOGY(D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST + (patchControlPointCount - 1));
7301 Q_UNREACHABLE_RETURN(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
7304static inline D3D12_PRIMITIVE_TOPOLOGY_TYPE toD3DTopologyType(QRhiGraphicsPipeline::Topology t)
7307 case QRhiGraphicsPipeline::Triangles:
7308 case QRhiGraphicsPipeline::TriangleStrip:
7309 case QRhiGraphicsPipeline::TriangleFan:
7310 return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
7311 case QRhiGraphicsPipeline::Lines:
7312 case QRhiGraphicsPipeline::LineStrip:
7313 return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
7314 case QRhiGraphicsPipeline::Points:
7315 return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
7316 case QRhiGraphicsPipeline::Patches:
7317 return D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH;
7319 Q_UNREACHABLE_RETURN(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
7322static inline DXGI_FORMAT toD3DAttributeFormat(QRhiVertexInputAttribute::Format format)
7325 case QRhiVertexInputAttribute::Float4:
7326 return DXGI_FORMAT_R32G32B32A32_FLOAT;
7327 case QRhiVertexInputAttribute::Float3:
7328 return DXGI_FORMAT_R32G32B32_FLOAT;
7329 case QRhiVertexInputAttribute::Float2:
7330 return DXGI_FORMAT_R32G32_FLOAT;
7331 case QRhiVertexInputAttribute::Float:
7332 return DXGI_FORMAT_R32_FLOAT;
7333 case QRhiVertexInputAttribute::UNormByte4:
7334 return DXGI_FORMAT_R8G8B8A8_UNORM;
7335 case QRhiVertexInputAttribute::UNormByte2:
7336 return DXGI_FORMAT_R8G8_UNORM;
7337 case QRhiVertexInputAttribute::UNormByte:
7338 return DXGI_FORMAT_R8_UNORM;
7339 case QRhiVertexInputAttribute::UInt4:
7340 return DXGI_FORMAT_R32G32B32A32_UINT;
7341 case QRhiVertexInputAttribute::UInt3:
7342 return DXGI_FORMAT_R32G32B32_UINT;
7343 case QRhiVertexInputAttribute::UInt2:
7344 return DXGI_FORMAT_R32G32_UINT;
7345 case QRhiVertexInputAttribute::UInt:
7346 return DXGI_FORMAT_R32_UINT;
7347 case QRhiVertexInputAttribute::SInt4:
7348 return DXGI_FORMAT_R32G32B32A32_SINT;
7349 case QRhiVertexInputAttribute::SInt3:
7350 return DXGI_FORMAT_R32G32B32_SINT;
7351 case QRhiVertexInputAttribute::SInt2:
7352 return DXGI_FORMAT_R32G32_SINT;
7353 case QRhiVertexInputAttribute::SInt:
7354 return DXGI_FORMAT_R32_SINT;
7355 case QRhiVertexInputAttribute::Half4:
7357 case QRhiVertexInputAttribute::Half3:
7358 return DXGI_FORMAT_R16G16B16A16_FLOAT;
7359 case QRhiVertexInputAttribute::Half2:
7360 return DXGI_FORMAT_R16G16_FLOAT;
7361 case QRhiVertexInputAttribute::Half:
7362 return DXGI_FORMAT_R16_FLOAT;
7363 case QRhiVertexInputAttribute::UShort4:
7365 case QRhiVertexInputAttribute::UShort3:
7366 return DXGI_FORMAT_R16G16B16A16_UINT;
7367 case QRhiVertexInputAttribute::UShort2:
7368 return DXGI_FORMAT_R16G16_UINT;
7369 case QRhiVertexInputAttribute::UShort:
7370 return DXGI_FORMAT_R16_UINT;
7371 case QRhiVertexInputAttribute::SShort4:
7373 case QRhiVertexInputAttribute::SShort3:
7374 return DXGI_FORMAT_R16G16B16A16_SINT;
7375 case QRhiVertexInputAttribute::SShort2:
7376 return DXGI_FORMAT_R16G16_SINT;
7377 case QRhiVertexInputAttribute::SShort:
7378 return DXGI_FORMAT_R16_SINT;
7380 Q_UNREACHABLE_RETURN(DXGI_FORMAT_R32G32B32A32_FLOAT);
7383QD3D12GraphicsPipeline::QD3D12GraphicsPipeline(QRhiImplementation *rhi)
7384 : QRhiGraphicsPipeline(rhi)
7388QD3D12GraphicsPipeline::~QD3D12GraphicsPipeline()
7393void QD3D12GraphicsPipeline::destroy()
7395 if (handle.isNull())
7398 QRHI_RES_RHI(QRhiD3D12);
7400 rhiD->releaseQueue.deferredReleasePipeline(handle);
7401 rhiD->releaseQueue.deferredReleaseRootSignature(rootSigHandle);
7408 rhiD->unregisterResource(
this);
7411bool QD3D12GraphicsPipeline::create()
7413 if (!handle.isNull())
7416 QRHI_RES_RHI(QRhiD3D12);
7417 if (!rhiD->sanityCheckGraphicsPipeline(
this))
7420 rhiD->pipelineCreationStart();
7422 QByteArray shaderBytecode[5];
7423 for (
const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
7424 const QD3D12Stage d3dStage = qd3d12_stage(shaderStage.type());
7425 stageData[d3dStage].valid =
true;
7426 stageData[d3dStage].stage = d3dStage;
7427 auto cacheIt = rhiD->shaderBytecodeCache.data.constFind(shaderStage);
7428 if (cacheIt != rhiD->shaderBytecodeCache.data.constEnd()) {
7429 shaderBytecode[d3dStage] = cacheIt->bytecode;
7430 stageData[d3dStage].nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
7431 stageData[d3dStage].pushConstantRegister = cacheIt->pushConstantRegister;
7432 stageData[d3dStage].pushConstantSize = cacheIt->pushConstantSize;
7435 QShaderKey shaderKey;
7436 int compileFlags = 0;
7437 if (m_flags.testFlag(CompileShadersWithDebugInfo))
7438 compileFlags |=
int(HlslCompileFlag::WithDebugInfo);
7439 const QByteArray bytecode = compileHlslShaderSource(shaderStage.shader(),
7440 shaderStage.shaderVariant(),
7444 if (bytecode.isEmpty()) {
7445 qWarning(
"HLSL graphics shader compilation failed: %s", qPrintable(error));
7449 shaderBytecode[d3dStage] = bytecode;
7450 stageData[d3dStage].nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
7451 qd3d12_setPushConstantInfo(&stageData[d3dStage], shaderStage.shader(), shaderKey);
7452 rhiD->shaderBytecodeCache.insertWithCapacityLimit(shaderStage,
7453 { bytecode, stageData[d3dStage].nativeResourceBindingMap,
7454 stageData[d3dStage].pushConstantRegister,
7455 stageData[d3dStage].pushConstantSize });
7459 QD3D12ShaderResourceBindings *srbD = QRHI_RES(QD3D12ShaderResourceBindings, m_shaderResourceBindings);
7461 rootSigHandle = srbD->createRootSignature(stageData.data(), 5);
7462 pushConstantRootParamIndex = srbD->pushConstantRootParamIndex;
7463 if (rootSigHandle.isNull()) {
7464 qWarning(
"Failed to create root signature");
7468 ID3D12RootSignature *rootSig =
nullptr;
7469 if (QD3D12RootSignature *rs = rhiD->rootSignaturePool.lookupRef(rootSigHandle))
7470 rootSig = rs->rootSig;
7472 qWarning(
"Cannot create graphics pipeline state without root signature");
7476 QD3D12RenderPassDescriptor *rpD = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
7477 DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
7478 if (rpD->colorAttachmentCount > 0) {
7479 format = DXGI_FORMAT(rpD->colorFormat[0]);
7480 }
else if (rpD->hasDepthStencil) {
7481 format = DXGI_FORMAT(rpD->dsFormat);
7483 qWarning(
"Cannot create graphics pipeline state without color or depthStencil format");
7486 const DXGI_SAMPLE_DESC sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, format);
7489 QD3D12PipelineStateSubObject<ID3D12RootSignature *, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE> rootSig;
7490 QD3D12PipelineStateSubObject<D3D12_INPUT_LAYOUT_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT> inputLayout;
7491 QD3D12PipelineStateSubObject<D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE> primitiveRestartValue;
7492 QD3D12PipelineStateSubObject<D3D12_PRIMITIVE_TOPOLOGY_TYPE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY> primitiveTopology;
7493 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS> VS;
7494 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS> HS;
7495 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS> DS;
7496 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS> GS;
7497 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS> PS;
7498 QD3D12PipelineStateSubObject<D3D12_RASTERIZER_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER> rasterizerState;
7499 QD3D12PipelineStateSubObject<D3D12_DEPTH_STENCIL_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL> depthStencilState;
7500 QD3D12PipelineStateSubObject<D3D12_BLEND_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND> blendState;
7501 QD3D12PipelineStateSubObject<D3D12_RT_FORMAT_ARRAY, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS> rtFormats;
7502 QD3D12PipelineStateSubObject<DXGI_FORMAT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT> dsFormat;
7503 QD3D12PipelineStateSubObject<DXGI_SAMPLE_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC> sampleDesc;
7504 QD3D12PipelineStateSubObject<UINT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK> sampleMask;
7505 QD3D12PipelineStateSubObject<D3D12_VIEW_INSTANCING_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING> viewInstancingDesc;
7508 stream.rootSig.object = rootSig;
7510 QVarLengthArray<D3D12_INPUT_ELEMENT_DESC, 4> inputDescs;
7511 QByteArrayList matrixSliceSemantics;
7512 if (!shaderBytecode[VS].isEmpty()) {
7513 for (
auto it = m_vertexInputLayout.cbeginAttributes(), itEnd = m_vertexInputLayout.cendAttributes();
7516 D3D12_INPUT_ELEMENT_DESC desc = {};
7521 const int matrixSlice = it->matrixSlice();
7522 if (matrixSlice < 0) {
7523 desc.SemanticName =
"TEXCOORD";
7524 desc.SemanticIndex = UINT(it->location());
7528 std::snprintf(sem.data(), sem.size(),
"TEXCOORD%d_", it->location() - matrixSlice);
7529 matrixSliceSemantics.append(sem);
7530 desc.SemanticName = matrixSliceSemantics.last().constData();
7531 desc.SemanticIndex = UINT(matrixSlice);
7533 desc.Format = toD3DAttributeFormat(it->format());
7534 desc.InputSlot = UINT(it->binding());
7535 desc.AlignedByteOffset = it->offset();
7536 const QRhiVertexInputBinding *inputBinding = m_vertexInputLayout.bindingAt(it->binding());
7537 if (inputBinding->classification() == QRhiVertexInputBinding::PerInstance) {
7538 desc.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA;
7539 desc.InstanceDataStepRate = inputBinding->instanceStepRate();
7541 desc.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
7543 inputDescs.append(desc);
7547 stream.inputLayout.object.NumElements = inputDescs.count();
7548 stream.inputLayout.object.pInputElementDescs = inputDescs.isEmpty() ?
nullptr : inputDescs.constData();
7550 stream.primitiveRestartValue.object = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF;
7552 stream.primitiveTopology.object = toD3DTopologyType(m_topology);
7553 topology = toD3DTopology(m_topology, m_patchControlPointCount);
7555 for (
const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
7556 const int d3dStage = qd3d12_stage(shaderStage.type());
7559 stream.VS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7560 stream.VS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7563 stream.HS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7564 stream.HS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7567 stream.DS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7568 stream.DS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7571 stream.GS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7572 stream.GS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7575 stream.PS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7576 stream.PS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7584 stream.rasterizerState.object.FillMode = toD3DFillMode(m_polygonMode);
7585 stream.rasterizerState.object.CullMode = toD3DCullMode(m_cullMode);
7586 stream.rasterizerState.object.FrontCounterClockwise = m_frontFace == CCW;
7587 stream.rasterizerState.object.DepthBias = m_depthBias;
7588 stream.rasterizerState.object.SlopeScaledDepthBias = m_slopeScaledDepthBias;
7589 stream.rasterizerState.object.DepthClipEnable = m_depthClamp ? FALSE : TRUE;
7590 stream.rasterizerState.object.MultisampleEnable = sampleDesc.Count > 1;
7592 stream.depthStencilState.object.DepthEnable = m_depthTest;
7593 stream.depthStencilState.object.DepthWriteMask = m_depthWrite ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
7594 stream.depthStencilState.object.DepthFunc = toD3DCompareOp(m_depthOp);
7595 stream.depthStencilState.object.StencilEnable = m_stencilTest;
7596 if (m_stencilTest) {
7597 stream.depthStencilState.object.StencilReadMask = UINT8(m_stencilReadMask);
7598 stream.depthStencilState.object.StencilWriteMask = UINT8(m_stencilWriteMask);
7599 stream.depthStencilState.object.FrontFace.StencilFailOp = toD3DStencilOp(m_stencilFront.failOp);
7600 stream.depthStencilState.object.FrontFace.StencilDepthFailOp = toD3DStencilOp(m_stencilFront.depthFailOp);
7601 stream.depthStencilState.object.FrontFace.StencilPassOp = toD3DStencilOp(m_stencilFront.passOp);
7602 stream.depthStencilState.object.FrontFace.StencilFunc = toD3DCompareOp(m_stencilFront.compareOp);
7603 stream.depthStencilState.object.BackFace.StencilFailOp = toD3DStencilOp(m_stencilBack.failOp);
7604 stream.depthStencilState.object.BackFace.StencilDepthFailOp = toD3DStencilOp(m_stencilBack.depthFailOp);
7605 stream.depthStencilState.object.BackFace.StencilPassOp = toD3DStencilOp(m_stencilBack.passOp);
7606 stream.depthStencilState.object.BackFace.StencilFunc = toD3DCompareOp(m_stencilBack.compareOp);
7609 stream.blendState.object.IndependentBlendEnable = m_targetBlends.count() > 1;
7610 for (
int i = 0, ie = m_targetBlends.count(); i != ie; ++i) {
7611 const QRhiGraphicsPipeline::TargetBlend &b(m_targetBlends[i]);
7612 D3D12_RENDER_TARGET_BLEND_DESC blend = {};
7613 blend.BlendEnable = b.enable;
7614 blend.SrcBlend = toD3DBlendFactor(b.srcColor,
true);
7615 blend.DestBlend = toD3DBlendFactor(b.dstColor,
true);
7616 blend.BlendOp = toD3DBlendOp(b.opColor);
7617 blend.SrcBlendAlpha = toD3DBlendFactor(b.srcAlpha,
false);
7618 blend.DestBlendAlpha = toD3DBlendFactor(b.dstAlpha,
false);
7619 blend.BlendOpAlpha = toD3DBlendOp(b.opAlpha);
7620 blend.RenderTargetWriteMask = toD3DColorWriteMask(b.colorWrite);
7621 stream.blendState.object.RenderTarget[i] = blend;
7623 if (m_targetBlends.isEmpty()) {
7624 D3D12_RENDER_TARGET_BLEND_DESC blend = {};
7625 blend.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
7626 stream.blendState.object.RenderTarget[0] = blend;
7629 stream.rtFormats.object.NumRenderTargets = rpD->colorAttachmentCount;
7630 for (
int i = 0; i < rpD->colorAttachmentCount; ++i)
7631 stream.rtFormats.object.RTFormats[i] = DXGI_FORMAT(rpD->colorFormat[i]);
7633 stream.dsFormat.object = rpD->hasDepthStencil ? DXGI_FORMAT(rpD->dsFormat) : DXGI_FORMAT_UNKNOWN;
7635 stream.sampleDesc.object = sampleDesc;
7637 stream.sampleMask.object = 0xFFFFFFFF;
7639 viewInstanceMask = 0;
7640 const bool isMultiView = m_multiViewCount >= 2;
7641 stream.viewInstancingDesc.object.ViewInstanceCount = isMultiView ? m_multiViewCount : 0;
7642 QVarLengthArray<D3D12_VIEW_INSTANCE_LOCATION, 4> viewInstanceLocations;
7644 for (
int i = 0; i < m_multiViewCount; ++i) {
7645 viewInstanceMask |= (1 << i);
7646 viewInstanceLocations.append({ 0, UINT(i) });
7648 stream.viewInstancingDesc.object.pViewInstanceLocations = viewInstanceLocations.constData();
7651 const D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {
sizeof(stream), &stream };
7653 QCryptographicHash keyHash(QCryptographicHash::Sha1);
7654 for (
const QByteArray &bytecode : shaderBytecode)
7655 addToKey(&keyHash, bytecode);
7656 for (
const D3D12_INPUT_ELEMENT_DESC &desc : inputDescs) {
7657 keyHash.addData(QByteArrayView(desc.SemanticName));
7658 addToKey(&keyHash, desc.SemanticIndex);
7659 addToKey(&keyHash, desc.Format);
7660 addToKey(&keyHash, desc.InputSlot);
7661 addToKey(&keyHash, desc.AlignedByteOffset);
7662 addToKey(&keyHash, desc.InputSlotClass);
7663 addToKey(&keyHash, desc.InstanceDataStepRate);
7665 addToKey(&keyHash, stream.primitiveRestartValue.object);
7666 addToKey(&keyHash, stream.primitiveTopology.object);
7667 addToKey(&keyHash, stream.rasterizerState.object);
7668 addToKey(&keyHash, stream.depthStencilState.object);
7669 addToKey(&keyHash, stream.blendState.object);
7670 addToKey(&keyHash, stream.rtFormats.object);
7671 addToKey(&keyHash, stream.dsFormat.object);
7672 addToKey(&keyHash, stream.sampleDesc.object);
7673 addToKey(&keyHash, stream.sampleMask.object);
7674 addToKey(&keyHash, stream.viewInstancingDesc.object.ViewInstanceCount);
7675 addToKey(&keyHash, stream.viewInstancingDesc.object.Flags);
7676 addToKey(&keyHash, viewInstanceLocations.constData(),
7677 viewInstanceLocations.count() *
sizeof(D3D12_VIEW_INSTANCE_LOCATION));
7680 addToKey(&keyHash, srbD->serializedLayoutDescription());
7682 ID3D12PipelineState *pso = rhiD->loadOrCreatePipelineState(&streamDesc, keyHash.result().toHex(),
"graphics");
7684 rhiD->rootSignaturePool.remove(rootSigHandle);
7689 handle = QD3D12Pipeline::addToPool(&rhiD->pipelinePool, QD3D12Pipeline::Graphics, pso);
7691 rhiD->pipelineCreationEnd();
7693 rhiD->registerResource(
this);
7697QD3D12ComputePipeline::QD3D12ComputePipeline(QRhiImplementation *rhi)
7698 : QRhiComputePipeline(rhi)
7702QD3D12ComputePipeline::~QD3D12ComputePipeline()
7707void QD3D12ComputePipeline::destroy()
7709 if (handle.isNull())
7712 QRHI_RES_RHI(QRhiD3D12);
7714 rhiD->releaseQueue.deferredReleasePipeline(handle);
7715 rhiD->releaseQueue.deferredReleaseRootSignature(rootSigHandle);
7722 rhiD->unregisterResource(
this);
7725bool QD3D12ComputePipeline::create()
7727 if (!handle.isNull())
7730 QRHI_RES_RHI(QRhiD3D12);
7731 rhiD->pipelineCreationStart();
7733 stageData.valid =
true;
7734 stageData.stage = CS;
7736 QByteArray shaderBytecode;
7737 auto cacheIt = rhiD->shaderBytecodeCache.data.constFind(m_shaderStage);
7738 if (cacheIt != rhiD->shaderBytecodeCache.data.constEnd()) {
7739 shaderBytecode = cacheIt->bytecode;
7740 stageData.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
7741 stageData.pushConstantRegister = cacheIt->pushConstantRegister;
7742 stageData.pushConstantSize = cacheIt->pushConstantSize;
7745 QShaderKey shaderKey;
7746 int compileFlags = 0;
7747 if (m_flags.testFlag(CompileShadersWithDebugInfo))
7748 compileFlags |=
int(HlslCompileFlag::WithDebugInfo);
7749 const QByteArray bytecode = compileHlslShaderSource(m_shaderStage.shader(),
7750 m_shaderStage.shaderVariant(),
7754 if (bytecode.isEmpty()) {
7755 qWarning(
"HLSL compute shader compilation failed: %s", qPrintable(error));
7759 shaderBytecode = bytecode;
7760 stageData.nativeResourceBindingMap = m_shaderStage.shader().nativeResourceBindingMap(shaderKey);
7761 qd3d12_setPushConstantInfo(&stageData, m_shaderStage.shader(), shaderKey);
7762 rhiD->shaderBytecodeCache.insertWithCapacityLimit(m_shaderStage, { bytecode,
7763 stageData.nativeResourceBindingMap,
7764 stageData.pushConstantRegister,
7765 stageData.pushConstantSize });
7768 QD3D12ShaderResourceBindings *srbD = QRHI_RES(QD3D12ShaderResourceBindings, m_shaderResourceBindings);
7770 rootSigHandle = srbD->createRootSignature(&stageData, 1);
7771 pushConstantRootParamIndex = srbD->pushConstantRootParamIndex;
7772 if (rootSigHandle.isNull()) {
7773 qWarning(
"Failed to create root signature");
7777 ID3D12RootSignature *rootSig =
nullptr;
7778 if (QD3D12RootSignature *rs = rhiD->rootSignaturePool.lookupRef(rootSigHandle))
7779 rootSig = rs->rootSig;
7781 qWarning(
"Cannot create compute pipeline state without root signature");
7786 QD3D12PipelineStateSubObject<ID3D12RootSignature *, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE> rootSig;
7787 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS> CS;
7789 stream.rootSig.object = rootSig;
7790 stream.CS.object.pShaderBytecode = shaderBytecode.constData();
7791 stream.CS.object.BytecodeLength = shaderBytecode.size();
7792 const D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {
sizeof(stream), &stream };
7794 QCryptographicHash keyHash(QCryptographicHash::Sha1);
7795 addToKey(&keyHash, shaderBytecode);
7796 addToKey(&keyHash, srbD->serializedLayoutDescription());
7798 ID3D12PipelineState *pso = rhiD->loadOrCreatePipelineState(&streamDesc, keyHash.result().toHex(),
"compute");
7800 rhiD->rootSignaturePool.remove(rootSigHandle);
7805 handle = QD3D12Pipeline::addToPool(&rhiD->pipelinePool, QD3D12Pipeline::Compute, pso);
7807 rhiD->pipelineCreationEnd();
7809 rhiD->registerResource(
this);
7816QD3D12RenderPassDescriptor::QD3D12RenderPassDescriptor(QRhiImplementation *rhi)
7817 : QRhiRenderPassDescriptor(rhi)
7819 serializedFormatData.reserve(16);
7822QD3D12RenderPassDescriptor::~QD3D12RenderPassDescriptor()
7827void QD3D12RenderPassDescriptor::destroy()
7829 QRHI_RES_RHI(QRhiD3D12);
7831 rhiD->unregisterResource(
this);
7834bool QD3D12RenderPassDescriptor::isCompatible(
const QRhiRenderPassDescriptor *other)
const
7839 const QD3D12RenderPassDescriptor *o = QRHI_RES(
const QD3D12RenderPassDescriptor, other);
7841 if (colorAttachmentCount != o->colorAttachmentCount)
7844 if (hasDepthStencil != o->hasDepthStencil)
7847 for (
int i = 0; i < colorAttachmentCount; ++i) {
7848 if (colorFormat[i] != o->colorFormat[i])
7852 if (hasDepthStencil) {
7853 if (dsFormat != o->dsFormat)
7857 if (hasShadingRateMap != o->hasShadingRateMap)
7863void QD3D12RenderPassDescriptor::updateSerializedFormat()
7865 serializedFormatData.clear();
7866 auto p = std::back_inserter(serializedFormatData);
7868 *p++ = colorAttachmentCount;
7869 *p++ = hasDepthStencil;
7870 for (
int i = 0; i < colorAttachmentCount; ++i)
7871 *p++ = colorFormat[i];
7872 *p++ = hasDepthStencil ? dsFormat : 0;
7875QRhiRenderPassDescriptor *QD3D12RenderPassDescriptor::newCompatibleRenderPassDescriptor()
const
7877 QD3D12RenderPassDescriptor *rpD =
new QD3D12RenderPassDescriptor(m_rhi);
7878 rpD->colorAttachmentCount = colorAttachmentCount;
7879 rpD->hasDepthStencil = hasDepthStencil;
7880 memcpy(rpD->colorFormat, colorFormat,
sizeof(colorFormat));
7881 rpD->dsFormat = dsFormat;
7882 rpD->hasShadingRateMap = hasShadingRateMap;
7884 rpD->updateSerializedFormat();
7886 QRHI_RES_RHI(QRhiD3D12);
7887 rhiD->registerResource(rpD);
7891QVector<quint32> QD3D12RenderPassDescriptor::serializedFormat()
const
7893 return serializedFormatData;
7896QD3D12CommandBuffer::QD3D12CommandBuffer(QRhiImplementation *rhi)
7897 : QRhiCommandBuffer(rhi)
7902QD3D12CommandBuffer::~QD3D12CommandBuffer()
7907void QD3D12CommandBuffer::destroy()
7912const QRhiNativeHandles *QD3D12CommandBuffer::nativeHandles()
7914 nativeHandlesStruct.commandList = cmdList;
7915 return &nativeHandlesStruct;
7918QD3D12SwapChainRenderTarget::QD3D12SwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
7919 : QRhiSwapChainRenderTarget(rhi, swapchain),
7924QD3D12SwapChainRenderTarget::~QD3D12SwapChainRenderTarget()
7929void QD3D12SwapChainRenderTarget::destroy()
7934QSize QD3D12SwapChainRenderTarget::pixelSize()
const
7939float QD3D12SwapChainRenderTarget::devicePixelRatio()
const
7944int QD3D12SwapChainRenderTarget::sampleCount()
const
7946 return d.sampleCount;
7949QD3D12SwapChain::QD3D12SwapChain(QRhiImplementation *rhi)
7950 : QRhiSwapChain(rhi),
7951 rtWrapper(rhi,
this),
7952 rtWrapperRight(rhi,
this),
7957QD3D12SwapChain::~QD3D12SwapChain()
7962void QD3D12SwapChain::destroy()
7965 dcompVisual->Release();
7966 dcompVisual =
nullptr;
7970 dcompTarget->Release();
7971 dcompTarget =
nullptr;
7979 swapChain->Release();
7980 swapChain =
nullptr;
7981 sourceSwapChain1->Release();
7982 sourceSwapChain1 =
nullptr;
7984 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
7985 FrameResources &fr(frameRes[i]);
7987 fr.fence->Release();
7989 CloseHandle(fr.fenceEvent);
7991 fr.cmdList->Release();
7995 if (frameLatencyWaitableObject) {
7996 CloseHandle(frameLatencyWaitableObject);
7997 frameLatencyWaitableObject =
nullptr;
8000 QDxgiVSyncService::instance()->unregisterWindow(window);
8002 QRHI_RES_RHI(QRhiD3D12);
8004 rhiD->swapchains.remove(
this);
8005 rhiD->unregisterResource(
this);
8009void QD3D12SwapChain::releaseBuffers()
8011 QRHI_RES_RHI(QRhiD3D12);
8013 for (UINT i = 0; i < BUFFER_COUNT; ++i) {
8014 rhiD->resourcePool.remove(colorBuffers[i]);
8015 rhiD->rtvPool.release(rtvs[i], 1);
8017 rhiD->rtvPool.release(rtvsRight[i], 1);
8019 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
8020 if (!msaaBuffers[i].isNull())
8021 rhiD->resourcePool.remove(msaaBuffers[i]);
8022 if (msaaRtvs[i].isValid())
8023 rhiD->rtvPool.release(msaaRtvs[i], 1);
8027void QD3D12SwapChain::waitCommandCompletionForFrameSlot(
int frameSlot)
8029 FrameResources &fr(frameRes[frameSlot]);
8030 if (fr.fence->GetCompletedValue() < fr.fenceCounter) {
8031 fr.fence->SetEventOnCompletion(fr.fenceCounter, fr.fenceEvent);
8032 WaitForSingleObject(fr.fenceEvent, INFINITE);
8036void QD3D12SwapChain::addCommandCompletionSignalForCurrentFrameSlot()
8038 QRHI_RES_RHI(QRhiD3D12);
8039 FrameResources &fr(frameRes[currentFrameSlot]);
8040 fr.fenceCounter += 1u;
8041 rhiD->cmdQueue->Signal(fr.fence, fr.fenceCounter);
8044QRhiCommandBuffer *QD3D12SwapChain::currentFrameCommandBuffer()
8049QRhiRenderTarget *QD3D12SwapChain::currentFrameRenderTarget()
8054QRhiRenderTarget *QD3D12SwapChain::currentFrameRenderTarget(StereoTargetBuffer targetBuffer)
8056 return !stereo || targetBuffer == StereoTargetBuffer::LeftBuffer ? &rtWrapper : &rtWrapperRight;
8059QSize QD3D12SwapChain::surfacePixelSize()
8062 return m_window->size() * m_window->devicePixelRatio();
8065bool QD3D12SwapChain::isFormatSupported(Format f)
8071 qWarning(
"Attempted to call isFormatSupported() without a window set");
8075 QRHI_RES_RHI(QRhiD3D12);
8076 if (QDxgiHdrInfo(rhiD->activeAdapter).isHdrCapable(m_window))
8077 return f == QRhiSwapChain::HDRExtendedSrgbLinear || f == QRhiSwapChain::HDR10;
8082QRhiSwapChainHdrInfo QD3D12SwapChain::hdrInfo()
8084 QRhiSwapChainHdrInfo info = QRhiSwapChain::hdrInfo();
8087 QRHI_RES_RHI(QRhiD3D12);
8088 info = QDxgiHdrInfo(rhiD->activeAdapter).queryHdrInfo(m_window);
8093QRhiRenderPassDescriptor *QD3D12SwapChain::newCompatibleRenderPassDescriptor()
8098 QD3D12RenderPassDescriptor *rpD =
new QD3D12RenderPassDescriptor(m_rhi);
8099 rpD->colorAttachmentCount = 1;
8100 rpD->hasDepthStencil = m_depthStencil !=
nullptr;
8101 rpD->colorFormat[0] =
int(srgbAdjustedColorFormat);
8102 rpD->dsFormat = QD3D12RenderBuffer::DS_FORMAT;
8104 rpD->hasShadingRateMap = m_shadingRateMap !=
nullptr;
8106 rpD->updateSerializedFormat();
8108 QRHI_RES_RHI(QRhiD3D12);
8109 rhiD->registerResource(rpD);
8113bool QRhiD3D12::ensureDirectCompositionDevice()
8118 qCDebug(QRHI_LOG_INFO,
"Creating Direct Composition device (needed for semi-transparent windows)");
8119 dcompDevice = QRhiD3D::createDirectCompositionDevice();
8120 return dcompDevice ?
true :
false;
8123static const DXGI_FORMAT DEFAULT_FORMAT = DXGI_FORMAT_R8G8B8A8_UNORM;
8124static const DXGI_FORMAT DEFAULT_SRGB_FORMAT = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
8126void QD3D12SwapChain::chooseFormats()
8128 colorFormat = DEFAULT_FORMAT;
8129 srgbAdjustedColorFormat = m_flags.testFlag(sRGB) ? DEFAULT_SRGB_FORMAT : DEFAULT_FORMAT;
8130 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
8131 QRHI_RES_RHI(QRhiD3D12);
8132 if (m_format != SDR) {
8133 if (QDxgiHdrInfo(rhiD->activeAdapter).isHdrCapable(m_window)) {
8136 case HDRExtendedSrgbLinear:
8137 colorFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;
8138 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
8139 srgbAdjustedColorFormat = colorFormat;
8142 colorFormat = DXGI_FORMAT_R10G10B10A2_UNORM;
8143 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
8144 srgbAdjustedColorFormat = colorFormat;
8153 qWarning(
"The output associated with the window is not HDR capable "
8154 "(or Use HDR is Off in the Display Settings), ignoring HDR format request");
8157 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, colorFormat);
8160bool QD3D12SwapChain::createOrResize()
8166 const bool needsRegistration = !window || window != m_window;
8169 if (window && window != m_window)
8173 pixelSize = surfacePixelSize();
8175 if (pixelSize.isEmpty())
8178 HWND hwnd =
reinterpret_cast<HWND>(window->winId());
8180 QRHI_RES_RHI(QRhiD3D12);
8181 stereo = m_window->format().stereo() && rhiD->dxgiFactory->IsWindowedStereoEnabled();
8183 if (m_flags.testFlag(SurfaceHasPreMulAlpha) || m_flags.testFlag(SurfaceHasNonPreMulAlpha)) {
8184 if (rhiD->ensureDirectCompositionDevice()) {
8186 hr = rhiD->dcompDevice->CreateTargetForHwnd(hwnd,
false, &dcompTarget);
8188 qWarning(
"Failed to create Direct Composition target for the window: %s",
8189 qPrintable(QSystemError::windowsComString(hr)));
8192 if (dcompTarget && !dcompVisual) {
8193 hr = rhiD->dcompDevice->CreateVisual(&dcompVisual);
8195 qWarning(
"Failed to create DirectComposition visual: %s",
8196 qPrintable(QSystemError::windowsComString(hr)));
8201 if (window->requestedFormat().alphaBufferSize() <= 0)
8202 qWarning(
"Swapchain says surface has alpha but the window has no alphaBufferSize set. "
8203 "This may lead to problems.");
8206 swapInterval = m_flags.testFlag(QRhiSwapChain::NoVSync) ? 0 : 1;
8208 if (swapInterval == 0 && rhiD->supportsAllowTearing)
8209 swapChainFlags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
8213 const bool useFrameLatencyWaitableObject = rhiD->maxFrameLatency != 0
8214 && swapInterval != 0
8215 && rhiD->driverInfoStruct.deviceType != QRhiDriverInfo::CpuDevice;
8216 if (useFrameLatencyWaitableObject)
8217 swapChainFlags |= DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
8222 DXGI_SWAP_CHAIN_DESC1 desc = {};
8223 desc.Width = UINT(pixelSize.width());
8224 desc.Height = UINT(pixelSize.height());
8225 desc.Format = colorFormat;
8226 desc.SampleDesc.Count = 1;
8227 desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
8228 desc.BufferCount = BUFFER_COUNT;
8229 desc.Flags = swapChainFlags;
8230 desc.Scaling = DXGI_SCALING_NONE;
8231 desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
8232 desc.Stereo = stereo;
8238 desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
8243 desc.Scaling = DXGI_SCALING_STRETCH;
8247 hr = rhiD->dxgiFactory->CreateSwapChainForComposition(rhiD->cmdQueue, &desc,
nullptr, &sourceSwapChain1);
8249 hr = rhiD->dxgiFactory->CreateSwapChainForHwnd(rhiD->cmdQueue, hwnd, &desc,
nullptr,
nullptr, &sourceSwapChain1);
8254 if (FAILED(hr) && m_format != SDR) {
8255 colorFormat = DEFAULT_FORMAT;
8256 desc.Format = DEFAULT_FORMAT;
8258 hr = rhiD->dxgiFactory->CreateSwapChainForComposition(rhiD->cmdQueue, &desc,
nullptr, &sourceSwapChain1);
8260 hr = rhiD->dxgiFactory->CreateSwapChainForHwnd(rhiD->cmdQueue, hwnd, &desc,
nullptr,
nullptr, &sourceSwapChain1);
8263 if (SUCCEEDED(hr)) {
8264 if (FAILED(sourceSwapChain1->QueryInterface(__uuidof(IDXGISwapChain3),
reinterpret_cast<
void **>(&swapChain)))) {
8265 qWarning(
"IDXGISwapChain3 not available");
8268 if (m_format != SDR) {
8269 hr = swapChain->SetColorSpace1(hdrColorSpace);
8271 qWarning(
"Failed to set color space on swapchain: %s",
8272 qPrintable(QSystemError::windowsComString(hr)));
8275 if (useFrameLatencyWaitableObject) {
8276 swapChain->SetMaximumFrameLatency(rhiD->maxFrameLatency);
8277 frameLatencyWaitableObject = swapChain->GetFrameLatencyWaitableObject();
8280 hr = dcompVisual->SetContent(swapChain);
8281 if (SUCCEEDED(hr)) {
8282 hr = dcompTarget->SetRoot(dcompVisual);
8284 qWarning(
"Failed to associate Direct Composition visual with the target: %s",
8285 qPrintable(QSystemError::windowsComString(hr)));
8288 qWarning(
"Failed to set content for Direct Composition visual: %s",
8289 qPrintable(QSystemError::windowsComString(hr)));
8293 rhiD->dxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES);
8296 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
8297 qWarning(
"Device loss detected during swapchain creation");
8298 rhiD->deviceLost =
true;
8300 }
else if (FAILED(hr)) {
8301 qWarning(
"Failed to create D3D12 swapchain: %s"
8302 " (Width=%u Height=%u Format=%u SampleCount=%u BufferCount=%u Scaling=%u SwapEffect=%u Stereo=%u)",
8303 qPrintable(QSystemError::windowsComString(hr)),
8304 desc.Width, desc.Height, UINT(desc.Format), desc.SampleDesc.Count,
8305 desc.BufferCount, UINT(desc.Scaling), UINT(desc.SwapEffect), UINT(desc.Stereo));
8309 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
8310 hr = rhiD->dev->CreateFence(0,
8311 D3D12_FENCE_FLAG_NONE,
8312 __uuidof(ID3D12Fence),
8313 reinterpret_cast<
void **>(&frameRes[i].fence));
8315 qWarning(
"Failed to create fence for swapchain: %s",
8316 qPrintable(QSystemError::windowsComString(hr)));
8319 frameRes[i].fenceEvent = CreateEvent(
nullptr, FALSE, FALSE,
nullptr);
8321 frameRes[i].fenceCounter = 0;
8325 hr = swapChain->ResizeBuffers(BUFFER_COUNT,
8326 UINT(pixelSize.width()),
8327 UINT(pixelSize.height()),
8330 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
8331 qWarning(
"Device loss detected in ResizeBuffers()");
8332 rhiD->deviceLost =
true;
8334 }
else if (FAILED(hr)) {
8335 qWarning(
"Failed to resize D3D12 swapchain: %s", qPrintable(QSystemError::windowsComString(hr)));
8340 for (UINT i = 0; i < BUFFER_COUNT; ++i) {
8341 ID3D12Resource *colorBuffer;
8342 hr = swapChain->GetBuffer(i, __uuidof(ID3D12Resource),
reinterpret_cast<
void **>(&colorBuffer));
8344 qWarning(
"Failed to get buffer %u for D3D12 swapchain: %s",
8345 i, qPrintable(QSystemError::windowsComString(hr)));
8348 colorBuffers[i] = QD3D12Resource::addToPool(&rhiD->resourcePool, colorBuffer, D3D12_RESOURCE_STATE_PRESENT);
8349 rtvs[i] = rhiD->rtvPool.allocate(1);
8350 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
8351 rtvDesc.Format = srgbAdjustedColorFormat;
8352 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
8353 rhiD->dev->CreateRenderTargetView(colorBuffer, &rtvDesc, rtvs[i].cpuHandle);
8356 rtvsRight[i] = rhiD->rtvPool.allocate(1);
8357 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
8358 rtvDesc.Format = srgbAdjustedColorFormat;
8359 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
8360 rtvDesc.Texture2DArray.ArraySize = 1;
8361 rtvDesc.Texture2DArray.FirstArraySlice = 1;
8362 rhiD->dev->CreateRenderTargetView(colorBuffer, &rtvDesc, rtvsRight[i].cpuHandle);
8366 if (m_depthStencil && m_depthStencil->sampleCount() != m_sampleCount) {
8367 qWarning(
"Depth-stencil buffer's sampleCount (%d) does not match color buffers' sample count (%d). Expect problems.",
8368 m_depthStencil->sampleCount(), m_sampleCount);
8370 if (m_depthStencil && m_depthStencil->pixelSize() != pixelSize) {
8371 if (m_depthStencil->flags().testFlag(QRhiRenderBuffer::UsedWithSwapChainOnly)) {
8372 m_depthStencil->setPixelSize(pixelSize);
8373 if (!m_depthStencil->create())
8374 qWarning(
"Failed to rebuild swapchain's associated depth-stencil buffer for size %dx%d",
8375 pixelSize.width(), pixelSize.height());
8377 qWarning(
"Depth-stencil buffer's size (%dx%d) does not match the surface size (%dx%d). Expect problems.",
8378 m_depthStencil->pixelSize().width(), m_depthStencil->pixelSize().height(),
8379 pixelSize.width(), pixelSize.height());
8383 ds = m_depthStencil ? QRHI_RES(QD3D12RenderBuffer, m_depthStencil) :
nullptr;
8385 if (sampleDesc.Count > 1) {
8386 for (
int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
8387 D3D12_RESOURCE_DESC resourceDesc = {};
8388 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
8389 resourceDesc.Width = UINT64(pixelSize.width());
8390 resourceDesc.Height = UINT(pixelSize.height());
8391 resourceDesc.DepthOrArraySize = 1;
8392 resourceDesc.MipLevels = 1;
8393 resourceDesc.Format = srgbAdjustedColorFormat;
8394 resourceDesc.SampleDesc = sampleDesc;
8395 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
8396 resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
8397 D3D12_CLEAR_VALUE clearValue = {};
8398 clearValue.Format = colorFormat;
8399 ID3D12Resource *resource =
nullptr;
8400 D3D12MA::Allocation *allocation =
nullptr;
8401 HRESULT hr = rhiD->vma.createResource(D3D12_HEAP_TYPE_DEFAULT,
8403 D3D12_RESOURCE_STATE_RENDER_TARGET,
8406 __uuidof(ID3D12Resource),
8407 reinterpret_cast<
void **>(&resource));
8409 qWarning(
"Failed to create MSAA color buffer: %s", qPrintable(QSystemError::windowsComString(hr)));
8412 msaaBuffers[i] = QD3D12Resource::addToPool(&rhiD->resourcePool, resource, D3D12_RESOURCE_STATE_RENDER_TARGET, allocation);
8413 msaaRtvs[i] = rhiD->rtvPool.allocate(1);
8414 if (!msaaRtvs[i].isValid())
8416 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
8417 rtvDesc.Format = srgbAdjustedColorFormat;
8418 rtvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D12_RTV_DIMENSION_TEXTURE2DMS
8419 : D3D12_RTV_DIMENSION_TEXTURE2D;
8420 rhiD->dev->CreateRenderTargetView(resource, &rtvDesc, msaaRtvs[i].cpuHandle);
8424 currentBackBufferIndex = swapChain->GetCurrentBackBufferIndex();
8425 currentFrameSlot = 0;
8426 lastFrameLatencyWaitSlot = -1;
8428 rtWrapper.setRenderPassDescriptor(m_renderPassDesc);
8429 QD3D12SwapChainRenderTarget *rtD = QRHI_RES(QD3D12SwapChainRenderTarget, &rtWrapper);
8430 rtD->d.rp = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
8431 rtD->d.pixelSize = pixelSize;
8432 rtD->d.dpr =
float(window->devicePixelRatio());
8433 rtD->d.sampleCount =
int(sampleDesc.Count);
8434 rtD->d.colorAttCount = 1;
8435 rtD->d.dsAttCount = m_depthStencil ? 1 : 0;
8437 rtWrapperRight.setRenderPassDescriptor(m_renderPassDesc);
8438 QD3D12SwapChainRenderTarget *rtDr = QRHI_RES(QD3D12SwapChainRenderTarget, &rtWrapperRight);
8439 rtDr->d.rp = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
8440 rtDr->d.pixelSize = pixelSize;
8441 rtDr->d.dpr =
float(window->devicePixelRatio());
8442 rtDr->d.sampleCount =
int(sampleDesc.Count);
8443 rtDr->d.colorAttCount = 1;
8444 rtDr->d.dsAttCount = m_depthStencil ? 1 : 0;
8446 QDxgiVSyncService::instance()->registerWindow(window);
8448 if (needsRegistration || !rhiD->swapchains.contains(
this))
8449 rhiD->swapchains.insert(
this);
8451 rhiD->registerResource(
this);
8453 m_currentPixelSize = pixelSize;