11#include <QtCore/qcryptographichash.h>
12#include <QtCore/qendian.h>
13#include <QtCore/private/qsystemerror_p.h>
20using namespace Qt::StringLiterals;
23
24
25
26
27
28
29
30
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
80
81
82
83
84
88
89
90
91
92
93
94
95
96
97
98
99
102
103
104
105
106
107
108
109
112
113
114
115
116
117
118
121
122
123
124
125
126
127
128
131
132
133
134
135
136
139
140
141
142
143
144
147#ifndef DXGI_ADAPTER_FLAG_SOFTWARE
148#define DXGI_ADAPTER_FLAG_SOFTWARE 2
151#ifndef D3D11_1_UAV_SLOT_COUNT
152#define D3D11_1_UAV_SLOT_COUNT 64
155#ifndef D3D11_VS_INPUT_REGISTER_COUNT
156#define D3D11_VS_INPUT_REGISTER_COUNT 32
165 if (importParams->dev && importParams->context) {
166 dev =
reinterpret_cast<ID3D11Device *>(importParams->dev);
167 ID3D11DeviceContext *ctx =
reinterpret_cast<ID3D11DeviceContext *>(importParams->context);
168 if (SUCCEEDED(ctx->QueryInterface(__uuidof(ID3D11DeviceContext1),
reinterpret_cast<
void **>(&context)))) {
173 qWarning(
"ID3D11DeviceContext1 not supported by context, cannot import");
176 featureLevel = D3D_FEATURE_LEVEL(importParams->featureLevel);
177 adapterLuid.LowPart = importParams->adapterLuidLow;
178 adapterLuid.HighPart = importParams->adapterLuidHigh;
185 return (v + byteAlign - 1) & ~(byteAlign - 1);
190 IDXGIFactory1 *result =
nullptr;
191 const HRESULT hr = CreateDXGIFactory2(0, __uuidof(IDXGIFactory2),
reinterpret_cast<
void **>(&result));
193 qWarning(
"CreateDXGIFactory2() failed to create DXGI factory: %s",
194 qPrintable(QSystemError::windowsComString(hr)));
206 devFlags |= D3D11_CREATE_DEVICE_DEBUG;
208 dxgiFactory = createDXGIFactory2();
216 IDXGIFactory5 *factory5 =
nullptr;
217 if (SUCCEEDED(dxgiFactory->QueryInterface(__uuidof(IDXGIFactory5),
reinterpret_cast<
void **>(&factory5)))) {
218 BOOL allowTearing =
false;
219 if (SUCCEEDED(factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing,
sizeof(allowTearing))))
224 if (qEnvironmentVariableIntValue(
"QT_D3D_FLIP_DISCARD"))
225 qWarning(
"The default swap effect is FLIP_DISCARD, QT_D3D_FLIP_DISCARD is now ignored");
233 if (qEnvironmentVariableIsSet(
"QT_D3D_MAX_FRAME_LATENCY"))
234 maxFrameLatency = UINT(qMax(0, qEnvironmentVariableIntValue(
"QT_D3D_MAX_FRAME_LATENCY")));
239 qCDebug(QRHI_LOG_INFO,
"FLIP_* swapchain supported = true, ALLOW_TEARING supported = %s, use legacy (non-FLIP) model = %s, max frame latency = %u",
243 if (maxFrameLatency == 0)
244 qCDebug(QRHI_LOG_INFO,
"Disabling FRAME_LATENCY_WAITABLE_OBJECT usage");
246 activeAdapter =
nullptr;
249 IDXGIAdapter1 *adapter;
250 int requestedAdapterIndex = -1;
251 if (qEnvironmentVariableIsSet(
"QT_D3D_ADAPTER_INDEX"))
252 requestedAdapterIndex = qEnvironmentVariableIntValue(
"QT_D3D_ADAPTER_INDEX");
254 if (requestedRhiAdapter)
255 adapterLuid =
static_cast<QD3D11Adapter *>(requestedRhiAdapter)->luid;
258 if (requestedAdapterIndex < 0 && (adapterLuid.LowPart || adapterLuid.HighPart)) {
259 for (
int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
260 DXGI_ADAPTER_DESC1 desc;
261 adapter->GetDesc1(&desc);
263 if (desc.AdapterLuid.LowPart == adapterLuid.LowPart
264 && desc.AdapterLuid.HighPart == adapterLuid.HighPart)
266 requestedAdapterIndex = adapterIndex;
272 if (requestedAdapterIndex < 0 && flags.testFlag(QRhi::PreferSoftwareRenderer)) {
273 for (
int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
274 DXGI_ADAPTER_DESC1 desc;
275 adapter->GetDesc1(&desc);
278 requestedAdapterIndex = adapterIndex;
284 for (
int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
285 DXGI_ADAPTER_DESC1 desc;
286 adapter->GetDesc1(&desc);
287 const QString name = QString::fromUtf16(
reinterpret_cast<
char16_t *>(desc.Description));
288 qCDebug(QRHI_LOG_INFO,
"Adapter %d: '%s' (vendor 0x%X device 0x%X flags 0x%X)",
294 if (!activeAdapter && (requestedAdapterIndex < 0 || requestedAdapterIndex == adapterIndex)) {
295 activeAdapter = adapter;
296 adapterLuid = desc.AdapterLuid;
298 qCDebug(QRHI_LOG_INFO,
" using this adapter");
303 if (!activeAdapter) {
304 qWarning(
"No adapter");
310 QVarLengthArray<D3D_FEATURE_LEVEL, 4> requestedFeatureLevels;
311 bool requestFeatureLevels =
false;
313 requestFeatureLevels =
true;
314 requestedFeatureLevels.append(featureLevel);
317 ID3D11DeviceContext *ctx =
nullptr;
318 HRESULT hr = D3D11CreateDevice(activeAdapter, D3D_DRIVER_TYPE_UNKNOWN,
nullptr, devFlags,
319 requestFeatureLevels ? requestedFeatureLevels.constData() :
nullptr,
320 requestFeatureLevels ? requestedFeatureLevels.count() : 0,
322 &dev, &featureLevel, &ctx);
324 if (hr == DXGI_ERROR_SDK_COMPONENT_MISSING && debugLayer) {
325 qCDebug(QRHI_LOG_INFO,
"Debug layer was requested but is not available. "
326 "Attempting to create D3D11 device without it.");
327 devFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
328 hr = D3D11CreateDevice(activeAdapter, D3D_DRIVER_TYPE_UNKNOWN,
nullptr, devFlags,
329 requestFeatureLevels ? requestedFeatureLevels.constData() :
nullptr,
330 requestFeatureLevels ? requestedFeatureLevels.count() : 0,
332 &dev, &featureLevel, &ctx);
335 qWarning(
"Failed to create D3D11 device and context: %s",
336 qPrintable(QSystemError::windowsComString(hr)));
340 const bool supports11_1 = SUCCEEDED(ctx->QueryInterface(__uuidof(ID3D11DeviceContext1),
reinterpret_cast<
void **>(&context)));
343 qWarning(
"ID3D11DeviceContext1 not supported");
349 ID3D11VertexShader *testShader =
nullptr;
350 if (SUCCEEDED(dev->CreateVertexShader(g_testVertexShader,
sizeof(g_testVertexShader),
nullptr, &testShader))) {
351 testShader->Release();
353 static const char *msg =
"D3D11 smoke test: Failed to create vertex shader";
354 if (flags.testFlag(QRhi::SuppressSmokeTestWarnings))
355 qCDebug(QRHI_LOG_INFO,
"%s", msg);
361 D3D11_FEATURE_DATA_D3D11_OPTIONS features = {};
362 if (SUCCEEDED(dev->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &features,
sizeof(features)))) {
366 if (!features.ConstantBufferOffsetting) {
367 static const char *msg =
"D3D11 smoke test: Constant buffer offsetting is not supported by the driver";
368 if (flags.testFlag(QRhi::SuppressSmokeTestWarnings))
369 qCDebug(QRHI_LOG_INFO,
"%s", msg);
375 static const char *msg =
"D3D11 smoke test: Failed to query D3D11_FEATURE_D3D11_OPTIONS";
376 if (flags.testFlag(QRhi::SuppressSmokeTestWarnings))
377 qCDebug(QRHI_LOG_INFO,
"%s", msg);
383 Q_ASSERT(dev && context);
384 featureLevel = dev->GetFeatureLevel();
385 IDXGIDevice *dxgiDev =
nullptr;
386 if (SUCCEEDED(dev->QueryInterface(__uuidof(IDXGIDevice),
reinterpret_cast<
void **>(&dxgiDev)))) {
387 IDXGIAdapter *adapter =
nullptr;
388 if (SUCCEEDED(dxgiDev->GetAdapter(&adapter))) {
389 IDXGIAdapter1 *adapter1 =
nullptr;
390 if (SUCCEEDED(adapter->QueryInterface(__uuidof(IDXGIAdapter1),
reinterpret_cast<
void **>(&adapter1)))) {
391 DXGI_ADAPTER_DESC1 desc;
392 adapter1->GetDesc1(&desc);
393 adapterLuid = desc.AdapterLuid;
395 activeAdapter = adapter1;
401 if (!activeAdapter) {
402 qWarning(
"Failed to query adapter from imported device");
405 qCDebug(QRHI_LOG_INFO,
"Using imported device %p", dev);
408 QDxgiVSyncService::instance()->refAdapter(adapterLuid);
410 if (FAILED(context->QueryInterface(__uuidof(ID3DUserDefinedAnnotation),
reinterpret_cast<
void **>(&annotations))))
411 annotations =
nullptr;
415 nativeHandlesStruct.dev = dev;
416 nativeHandlesStruct.context = context;
417 nativeHandlesStruct.featureLevel = featureLevel;
418 nativeHandlesStruct.adapterLuidLow = adapterLuid.LowPart;
419 nativeHandlesStruct.adapterLuidHigh = adapterLuid.HighPart;
426 for (
const Shader &s : std::as_const(m_shaderCache))
429 m_shaderCache.clear();
438 if (pushConstantBuffer) {
439 pushConstantBuffer->Release();
440 pushConstantBuffer =
nullptr;
443 if (ofr.tsDisjointQuery) {
444 ofr.tsDisjointQuery->Release();
445 ofr.tsDisjointQuery =
nullptr;
447 for (
int i = 0; i < 2; ++i) {
448 if (ofr.tsQueries[i]) {
449 ofr.tsQueries[i]->Release();
450 ofr.tsQueries[i] =
nullptr;
455 annotations->Release();
456 annotations =
nullptr;
471 dcompDevice->Release();
472 dcompDevice =
nullptr;
476 activeAdapter->Release();
477 activeAdapter =
nullptr;
481 dxgiFactory->Release();
482 dxgiFactory =
nullptr;
485 QDxgiVSyncService::instance()->derefAdapter(adapterLuid);
495 if (SUCCEEDED(device->QueryInterface(__uuidof(ID3D11Debug),
reinterpret_cast<
void **>(&debug)))) {
496 debug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
501QRhi::AdapterList
QRhiD3D11::enumerateAdaptersBeforeCreate(QRhiNativeHandles *nativeHandles)
const
503 LUID requestedLuid = {};
505 QRhiD3D11NativeHandles *h =
static_cast<QRhiD3D11NativeHandles *>(nativeHandles);
506 const LUID adapterLuid = { h->adapterLuidLow, h->adapterLuidHigh };
507 if (adapterLuid.LowPart || adapterLuid.HighPart)
508 requestedLuid = adapterLuid;
511 IDXGIFactory1 *dxgi = createDXGIFactory2();
515 QRhi::AdapterList list;
516 IDXGIAdapter1 *adapter;
517 for (
int adapterIndex = 0; dxgi->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
518 DXGI_ADAPTER_DESC1 desc;
519 adapter->GetDesc1(&desc);
521 if (requestedLuid.LowPart || requestedLuid.HighPart) {
522 if (desc.AdapterLuid.LowPart != requestedLuid.LowPart
523 || desc.AdapterLuid.HighPart != requestedLuid.HighPart)
528 QD3D11Adapter *a =
new QD3D11Adapter;
529 a->luid = desc.AdapterLuid;
530 QRhiD3D::fillDriverInfo(&a->adapterInfo, desc);
545 return { 1, 2, 4, 8 };
550 Q_UNUSED(sampleCount);
551 return { QSize(1, 1) };
556 DXGI_SAMPLE_DESC desc;
560 const int s = effectiveSampleCount(sampleCount);
562 desc.Count = UINT(s);
564 desc.Quality = UINT(D3D11_STANDARD_MULTISAMPLE_PATTERN);
573 return new QD3D11SwapChain(
this);
576QRhiBuffer *
QRhiD3D11::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
578 return new QD3D11Buffer(
this, type, usage, size);
606 static constexpr QMatrix4x4 m(1.0f, 0.0f, 0.0f, 0.0f,
607 0.0f, 1.0f, 0.0f, 0.0f,
608 0.0f, 0.0f, 0.5f, 0.5f,
609 0.0f, 0.0f, 0.0f, 1.0f);
617 if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ASTC_12x12)
626 case QRhi::MultisampleTexture:
628 case QRhi::MultisampleRenderBuffer:
630 case QRhi::DebugMarkers:
631 return annotations !=
nullptr;
632 case QRhi::Timestamps:
634 case QRhi::Instancing:
636 case QRhi::CustomInstanceStepRate:
638 case QRhi::PrimitiveRestart:
640 case QRhi::NonDynamicUniformBuffers:
642 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
644 case QRhi::NPOTTextureRepeat:
646 case QRhi::RedOrAlpha8IsRed:
648 case QRhi::ElementIndexUint:
653 return featureLevel >= D3D_FEATURE_LEVEL_11_0;
654 case QRhi::FragmentStoresAndAtomics:
655 return featureLevel >= D3D_FEATURE_LEVEL_11_0;
656 case QRhi::WideLines:
658 case QRhi::VertexShaderPointSize:
660 case QRhi::BaseVertex:
662 case QRhi::BaseInstance:
664 case QRhi::TriangleFanTopology:
666 case QRhi::ReadBackNonUniformBuffer:
668 case QRhi::ReadBackNonBaseMipLevel:
670 case QRhi::TexelFetch:
672 case QRhi::RenderToNonBaseMipLevel:
674 case QRhi::IntAttributes:
676 case QRhi::ScreenSpaceDerivatives:
678 case QRhi::ReadBackAnyTextureFormat:
680 case QRhi::PipelineCacheDataLoadSave:
682 case QRhi::ImageDataStride:
684 case QRhi::RenderBufferImport:
686 case QRhi::ThreeDimensionalTextures:
688 case QRhi::RenderTo3DTextureSlice:
690 case QRhi::TextureArrays:
692 case QRhi::Tessellation:
694 case QRhi::GeometryShader:
696 case QRhi::TextureArrayRange:
698 case QRhi::NonFillPolygonMode:
700 case QRhi::OneDimensionalTextures:
702 case QRhi::OneDimensionalTextureMipmaps:
704 case QRhi::HalfAttributes:
706 case QRhi::RenderToOneDimensionalTexture:
708 case QRhi::ThreeDimensionalTextureMipmaps:
710 case QRhi::MultiView:
712 case QRhi::TextureViewFormat:
714 case QRhi::ResolveDepthStencil:
716 case QRhi::VariableRateShading:
718 case QRhi::VariableRateShadingMap:
719 case QRhi::VariableRateShadingMapWithTexture:
721 case QRhi::DualSourceBlend:
722 return featureLevel >= D3D_FEATURE_LEVEL_10_0;
723 case QRhi::PerRenderTargetBlending:
724 case QRhi::SampleVariables:
726 case QRhi::InstanceIndexIncludesBaseInstance:
728 case QRhi::DepthClamp:
730 case QRhi::DrawIndirect:
731 case QRhi::BaseInstanceIndirect:
732 return featureLevel >= D3D_FEATURE_LEVEL_11_0;
733 case QRhi::DrawIndirectMulti:
734 case QRhi::ShaderDrawParameters:
736 case QRhi::PushConstants:
738 case QRhi::DrawIndirectCount:
740 case QRhi::DispatchIndirect:
741 return featureLevel >= D3D_FEATURE_LEVEL_11_0;
742 case QRhi::BufferToBufferCopy:
744 case QRhi::StaticBuffersOnGpuTimeline:
755 case QRhi::TextureSizeMin:
757 case QRhi::TextureSizeMax:
758 return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
759 case QRhi::MaxColorAttachments:
761 case QRhi::FramesInFlight:
767 case QRhi::MaxAsyncReadbackFrames:
769 case QRhi::MaxThreadGroupsPerDimension:
770 return D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
771 case QRhi::MaxThreadsPerThreadGroup:
772 return D3D11_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP;
773 case QRhi::MaxThreadGroupX:
774 return D3D11_CS_THREAD_GROUP_MAX_X;
775 case QRhi::MaxThreadGroupY:
776 return D3D11_CS_THREAD_GROUP_MAX_Y;
777 case QRhi::MaxThreadGroupZ:
778 return D3D11_CS_THREAD_GROUP_MAX_Z;
779 case QRhi::TextureArraySizeMax:
780 return D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION;
781 case QRhi::MaxUniformBufferRange:
783 case QRhi::MaxVertexInputs:
785 case QRhi::MaxVertexOutputs:
786 return D3D11_VS_OUTPUT_REGISTER_COUNT;
787 case QRhi::MaxVertexStorageBuffers:
789 case QRhi::MaxPushConstantsSize:
791 return int(MAX_PUSH_CONSTANTS_SIZE);
792 case QRhi::MaxFragmentStorageBuffers:
793 return featureLevel >= D3D_FEATURE_LEVEL_11_1
795 case QRhi::MaxStorageBufferBindings:
796 case QRhi::MaxStorageImageBindings:
798 case QRhi::ShadingRateImageTileSize:
808 return &nativeHandlesStruct;
813 return driverInfoStruct;
819 result.totalPipelineCreationTime = totalPipelineCreationTime();
829void QRhiD3D11::setQueueSubmitParams(QRhiNativeHandles *)
837 m_bytecodeCache.clear();
857 if (m_bytecodeCache.data.isEmpty())
861 memset(&header, 0,
sizeof(header));
862 header.rhiId = pipelineCacheRhiId();
863 header.arch = quint32(
sizeof(
void*));
864 header.count = m_bytecodeCache.data.count();
866 const size_t dataOffset =
sizeof(header);
868 for (
auto it = m_bytecodeCache.data.cbegin(), end = m_bytecodeCache.data.cend(); it != end; ++it) {
870 QByteArray bytecode = it.value();
872 sizeof(quint32) + key.sourceHash.size()
873 +
sizeof(quint32) + key.target.size()
874 +
sizeof(quint32) + key.entryPoint.size()
876 +
sizeof(quint32) + bytecode.size();
879 QByteArray buf(dataOffset + dataSize, Qt::Uninitialized);
880 char *p = buf.data() + dataOffset;
881 for (
auto it = m_bytecodeCache.data.cbegin(), end = m_bytecodeCache.data.cend(); it != end; ++it) {
883 QByteArray bytecode = it.value();
885 quint32 i = key.sourceHash.size();
888 memcpy(p, key.sourceHash.constData(), key.sourceHash.size());
889 p += key.sourceHash.size();
891 i = key.target.size();
894 memcpy(p, key.target.constData(), key.target.size());
895 p += key.target.size();
897 i = key.entryPoint.size();
900 memcpy(p, key.entryPoint.constData(), key.entryPoint.size());
901 p += key.entryPoint.size();
910 memcpy(p, bytecode.constData(), bytecode.size());
911 p += bytecode.size();
913 Q_ASSERT(p == buf.data() + dataOffset + dataSize);
915 header.dataSize = quint32(dataSize);
916 memcpy(buf.data(), &header,
sizeof(header));
927 if (data.size() < qsizetype(headerSize)) {
928 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob size (header incomplete)");
931 const size_t dataOffset = headerSize;
933 memcpy(&header, data.constData(), headerSize);
935 const quint32 rhiId = pipelineCacheRhiId();
936 if (header.rhiId != rhiId) {
937 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: The data is for a different QRhi version or backend (%u, %u)",
938 rhiId, header.rhiId);
941 const quint32 arch = quint32(
sizeof(
void*));
942 if (header.arch != arch) {
943 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Architecture does not match (%u, %u)",
947 if (header.count == 0)
950 if (quint64(data.size()) < quint64(dataOffset) + header.dataSize) {
951 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob size (data incomplete)");
955 m_bytecodeCache.clear();
958 for (quint32 i = 0; i < header.count; ++i) {
962 if (!reader.readByteArray(&cacheKey.sourceHash)
963 || !reader.readByteArray(&cacheKey.target)
964 || !reader.readByteArray(&cacheKey.entryPoint)
965 || !reader.readUInt32(&flags)
966 || !reader.readByteArray(&bytecode))
968 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob (truncated or corrupt bytecode data)");
969 m_bytecodeCache.clear();
974 m_bytecodeCache.insertWithCapacityLimit(cacheKey, bytecode);
977 qCDebug(QRHI_LOG_INFO,
"Seeded bytecode cache with %d shaders",
int(m_bytecodeCache.data.count()));
980QRhiRenderBuffer *
QRhiD3D11::createRenderBuffer(QRhiRenderBuffer::Type type,
const QSize &pixelSize,
981 int sampleCount, QRhiRenderBuffer::Flags flags,
982 QRhiTexture::Format backingFormatHint)
984 return new QD3D11RenderBuffer(
this, type, pixelSize, sampleCount, flags, backingFormatHint);
988 const QSize &pixelSize,
int depth,
int arraySize,
989 int sampleCount, QRhiTexture::Flags flags)
991 return new QD3D11Texture(
this, format, pixelSize, depth, arraySize, sampleCount, flags);
995 QRhiSampler::Filter mipmapMode,
996 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
998 return new QD3D11Sampler(
this, magFilter, minFilter, mipmapMode, u, v, w);
1002 QRhiTextureRenderTarget::Flags flags)
1014 return new QD3D11GraphicsPipeline(
this);
1019 return new QD3D11ComputePipeline(
this);
1024 return new QD3D11ShaderResourceBindings(
this);
1034 if (pipelineChanged) {
1035 cbD->currentGraphicsPipeline = ps;
1036 cbD->currentComputePipeline =
nullptr;
1041 cmd.args.bindGraphicsPipeline.topology = psD->d3dTopology;
1042 cmd.args.bindGraphicsPipeline.inputLayout = psD->inputLayout;
1043 cmd.args.bindGraphicsPipeline.dsState = psD->dsState;
1044 cmd.args.bindGraphicsPipeline.stencilRef = psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)
1045 ? cbD->currentStencilRef : 0;
1046 cmd.args.bindGraphicsPipeline.blendState = psD->blendState;
1047 cmd.args.bindGraphicsPipeline.rastState = psD->rastState;
1048 cmd.args.bindGraphicsPipeline.vs = psD->vs.shader;
1049 cmd.args.bindGraphicsPipeline.hs = psD->hs.shader;
1050 cmd.args.bindGraphicsPipeline.ds = psD->ds.shader;
1051 cmd.args.bindGraphicsPipeline.gs = psD->gs.shader;
1052 cmd.args.bindGraphicsPipeline.fs = psD->fs.shader;
1067 case QRhiShaderStage::Vertex:
1069 case QRhiShaderStage::TessellationControl:
1071 case QRhiShaderStage::TessellationEvaluation:
1073 case QRhiShaderStage::Geometry:
1074 return RBM_GEOMETRY;
1075 case QRhiShaderStage::Fragment:
1076 return RBM_FRAGMENT;
1077 case QRhiShaderStage::Compute:
1088 const QList<QShaderDescription::PushConstantBlock> blocks = shader.description().pushConstantBlocks();
1089 if (blocks.isEmpty())
1091 *reg = shader.nativeShaderInfo(key).extraBufferBindings.value(QShaderPrivate::HlslPushConstantBufferBinding, -1);
1092 *size = quint32((blocks.first().size + 3) & ~3);
1096 int dynamicOffsetCount,
1097 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
1106 srb = gfxPsD->m_shaderResourceBindings;
1108 srb = compPsD->m_shaderResourceBindings;
1113 bool pipelineChanged =
false;
1122 bool srbUpdate =
false;
1123 for (
int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
1124 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings.at(i));
1126 switch (b->type()) {
1127 case QRhiShaderResourceBinding::UniformBuffer:
1131 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic && bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
1132 sanityCheckResourceOwnership(bufD);
1136 if (bufD
->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
1138 bd.ubuf.id = bufD->m_id;
1143 case QRhiShaderResourceBinding::SampledTexture:
1144 case QRhiShaderResourceBinding::Texture:
1145 case QRhiShaderResourceBinding::Sampler:
1147 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
1148 if (bd.stex.d.size() != data->count()) {
1149 bd.stex.d.resize(data->count());
1152 for (
int elem = 0; elem < data->count(); ++elem) {
1158 Q_ASSERT(texD || samplerD);
1159 sanityCheckResourceOwnership(texD);
1160 sanityCheckResourceOwnership(samplerD);
1161 const quint64 texId = texD ? texD->m_id : 0;
1163 const quint64 samplerId = samplerD ? samplerD->m_id : 0;
1164 const uint samplerGen = samplerD ? samplerD
->generation : 0;
1165 if (texGen != bd.stex.d[elem].texGeneration
1166 || texId != bd.stex.d[elem].texId
1167 || samplerGen != bd.stex.d[elem].samplerGeneration
1168 || samplerId != bd.stex.d[elem].samplerId)
1171 bd.stex.d[elem].texId = texId;
1172 bd.stex.d[elem].texGeneration = texGen;
1173 bd.stex.d[elem].samplerId = samplerId;
1174 bd.stex.d[elem].samplerGeneration = samplerGen;
1179 case QRhiShaderResourceBinding::ImageLoad:
1180 case QRhiShaderResourceBinding::ImageStore:
1181 case QRhiShaderResourceBinding::ImageLoadStore:
1184 sanityCheckResourceOwnership(texD);
1185 if (texD
->generation != bd.simage.generation || texD->m_id != bd.simage.id) {
1187 bd.simage.id = texD->m_id;
1192 case QRhiShaderResourceBinding::BufferLoad:
1193 case QRhiShaderResourceBinding::BufferStore:
1194 case QRhiShaderResourceBinding::BufferLoadStore:
1197 sanityCheckResourceOwnership(bufD);
1198 if (bufD
->generation != bd.sbuf.generation || bufD->m_id != bd.sbuf.id) {
1200 bd.sbuf.id = bufD->m_id;
1211 if (srbUpdate || pipelineChanged) {
1213 memset(resBindMaps, 0,
sizeof(resBindMaps));
1214 uint pushConstantStages = 0;
1216 resBindMaps[
RBM_VERTEX] = &gfxPsD->vs.nativeResourceBindingMap;
1217 resBindMaps[
RBM_HULL] = &gfxPsD->hs.nativeResourceBindingMap;
1218 resBindMaps[
RBM_DOMAIN] = &gfxPsD->ds.nativeResourceBindingMap;
1219 resBindMaps[
RBM_GEOMETRY] = &gfxPsD->gs.nativeResourceBindingMap;
1220 resBindMaps[
RBM_FRAGMENT] = &gfxPsD->fs.nativeResourceBindingMap;
1221 pushConstantStages = gfxPsD->pushConstants.stages;
1223 resBindMaps[
RBM_COMPUTE] = &compPsD->cs.nativeResourceBindingMap;
1224 if (compPsD->pushConstants.reg >= 0 && compPsD->pushConstants.size)
1227 updateShaderResourceBindings(srbD, resBindMaps, pushConstantStages);
1230 const bool srbChanged = gfxPsD ? (cbD->currentGraphicsSrb != srb) : (cbD->currentComputeSrb != srb);
1233 if (pipelineChanged || srbChanged || srbRebuilt || srbUpdate || srbD
->hasDynamicOffset) {
1235 cbD->currentGraphicsSrb = srb;
1236 cbD->currentComputeSrb =
nullptr;
1238 cbD->currentGraphicsSrb =
nullptr;
1239 cbD->currentComputeSrb = srb;
1250 cmd.args.bindShaderResources.offsetOnlyChange = !pipelineChanged && !srbChanged
1252 cmd.args.bindShaderResources.dynamicOffsetCount = 0;
1255 cmd.args.bindShaderResources.dynamicOffsetCount = dynamicOffsetCount;
1256 uint *p = cmd.args.bindShaderResources.dynamicOffsetPairs;
1257 for (
int i = 0; i < dynamicOffsetCount; ++i) {
1258 const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]);
1259 const uint binding = uint(dynOfs.first);
1260 Q_ASSERT(aligned(dynOfs.second, 256u) == dynOfs.second);
1261 const quint32 offsetInConstants = dynOfs.second / 16;
1263 *p++ = offsetInConstants;
1266 qWarning(
"Too many dynamic offsets (%d, max is %d)",
1274 int startBinding,
int bindingCount,
const QRhiCommandBuffer::VertexInput *bindings,
1275 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
1281 if (bindingCount > maxBindings)
1282 qWarning(
"Too many vertex buffer bindings (%d, max is %d)", bindingCount, maxBindings);
1285 const QRhiVertexInputLayout *inputLayout = psD ? &psD->m_vertexInputLayout :
nullptr;
1286 const int inputBindingCount = inputLayout
1287 ? inputLayout->cendBindings() - inputLayout->cbeginBindings() : 0;
1288 const int vertexBindingCount = qMin(qMin(bindingCount, maxBindings),
1289 inputBindingCount - startBinding);
1293 bool needsBindVBuf =
false;
1294 for (
int i = 0; i < vertexBindingCount; ++i) {
1295 const int inputSlot = startBinding + i;
1297 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
1298 if (bufD->m_type == QRhiBuffer::Dynamic)
1301 const quint32 offset = bindings[i].second;
1302 const quint32 stride = inputLayout->bindingAt(inputSlot)->stride();
1303 if (cbD->currentVertexBuffers[inputSlot] != bufD->buffer
1304 || cbD->currentVertexOffsets[inputSlot] != offset
1305 || cbD->currentVertexStrides[inputSlot] != stride)
1307 needsBindVBuf =
true;
1308 cbD->currentVertexBuffers[inputSlot] = bufD->buffer;
1309 cbD->currentVertexOffsets[inputSlot] = offset;
1310 cbD->currentVertexStrides[inputSlot] = stride;
1314 if (needsBindVBuf) {
1317 cmd.args.bindVertexBuffers.startSlot = startBinding;
1318 cmd.args.bindVertexBuffers.slotCount = vertexBindingCount;
1319 for (
int i = 0; i < vertexBindingCount; ++i) {
1320 const int inputSlot = startBinding + i;
1321 cmd.args.bindVertexBuffers.buffers[i] = cbD->currentVertexBuffers[inputSlot];
1322 cmd.args.bindVertexBuffers.offsets[i] = cbD->currentVertexOffsets[inputSlot];
1323 cmd.args.bindVertexBuffers.strides[i] = cbD->currentVertexStrides[inputSlot];
1329 Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
1330 if (ibufD->m_type == QRhiBuffer::Dynamic)
1333 const DXGI_FORMAT dxgiFormat = indexFormat == QRhiCommandBuffer::IndexUInt16 ? DXGI_FORMAT_R16_UINT
1334 : DXGI_FORMAT_R32_UINT;
1335 if (cbD->currentIndexBuffer != ibufD->buffer
1336 || cbD->currentIndexOffset != indexOffset
1337 || cbD->currentIndexFormat != dxgiFormat)
1339 cbD->currentIndexBuffer = ibufD->buffer;
1340 cbD->currentIndexOffset = indexOffset;
1341 cbD->currentIndexFormat = dxgiFormat;
1345 cmd.args.bindIndexBuffer.buffer = ibufD->buffer;
1346 cmd.args.bindIndexBuffer.offset = indexOffset;
1347 cmd.args.bindIndexBuffer.format = dxgiFormat;
1356 Q_ASSERT(cbD->currentTarget);
1357 const QSize outputSize = cbD->currentTarget->pixelSize();
1361 if (!qrhi_toTopLeftRenderTargetRect<
UnBounded>(outputSize, viewport.viewport(), &x, &y, &w, &h))
1366 cmd.args.viewport.x = x;
1367 cmd.args.viewport.y = y;
1368 cmd.args.viewport.w = w;
1369 cmd.args.viewport.h = h;
1370 cmd.args.viewport.d0 = viewport.minDepth();
1371 cmd.args.viewport.d1 = viewport.maxDepth();
1378 Q_ASSERT(cbD->currentTarget);
1379 const QSize outputSize = cbD->currentTarget->pixelSize();
1383 if (!qrhi_toTopLeftRenderTargetRect<
Bounded>(outputSize, scissor.scissor(), &x, &y, &w, &h))
1388 cmd.args.scissor.x = x;
1389 cmd.args.scissor.y = y;
1390 cmd.args.scissor.w = w;
1391 cmd.args.scissor.h = h;
1402 cmd.args.blendConstants.c[0] =
float(c.redF());
1403 cmd.args.blendConstants.c[1] =
float(c.greenF());
1404 cmd.args.blendConstants.c[2] =
float(c.blueF());
1405 cmd.args.blendConstants.c[3] =
float(c.alphaF());
1416 cmd.args.stencilRef.ref = refValue;
1417 cbD->currentStencilRef = refValue;
1426 quint32 blockSize = 0;
1432 reg = psD->pushConstants.reg;
1433 blockSize = psD->pushConstants.size;
1439 reg = psD->pushConstants.reg;
1440 blockSize = psD->pushConstants.size;
1441 stages = psD->pushConstants.stages;
1443 if (reg < 0 || !blockSize || !stages) {
1444 qWarning(
"No pipeline with a push constant block is active; setPushConstants ignored");
1448 if (offset + size > MAX_PUSH_CONSTANTS_SIZE) {
1449 qWarning(
"Push constant data of %u bytes at offset %u exceeds the %u byte maximum; "
1450 "setPushConstants ignored", size, offset, MAX_PUSH_CONSTANTS_SIZE);
1459 const quint32 total = qMin(qMax(blockSize, offset + size), MAX_PUSH_CONSTANTS_SIZE);
1460 if (quint32(cbD->pushConstantData.size()) < total)
1461 cbD->pushConstantData.resize(
int(total), 0);
1462 memcpy(cbD->pushConstantData.data() + offset, data, size);
1464 const quint32 dataOffset = quint32(cbD->pushConstantPool.size());
1465 cbD->pushConstantPool.append(cbD->pushConstantData.constData(), total);
1469 cmd.args.setPushConstants.buffer = pushConstantBuffer;
1470 cmd.args.setPushConstants.dataOffset = dataOffset;
1471 cmd.args.setPushConstants.size = total;
1472 cmd.args.setPushConstants.startSlot = uint(reg);
1473 cmd.args.setPushConstants.stages = stages;
1478 if (pushConstantBuffer)
1481 D3D11_BUFFER_DESC desc = {};
1482 desc.ByteWidth = aligned(MAX_PUSH_CONSTANTS_SIZE, 256u);
1483 desc.Usage = D3D11_USAGE_DYNAMIC;
1484 desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1485 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
1486 HRESULT hr = dev->CreateBuffer(&desc,
nullptr, &pushConstantBuffer);
1488 qWarning(
"Failed to create push constant buffer: %s",
1489 qPrintable(QSystemError::windowsComString(hr)));
1490 pushConstantBuffer =
nullptr;
1499 Q_UNUSED(coarsePixelSize);
1503 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
1510 cmd.args.draw.vertexCount = vertexCount;
1511 cmd.args.draw.instanceCount = instanceCount;
1512 cmd.args.draw.firstVertex = firstVertex;
1513 cmd.args.draw.firstInstance = firstInstance;
1517 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
1524 cmd.args.drawIndexed.indexCount = indexCount;
1525 cmd.args.drawIndexed.instanceCount = instanceCount;
1526 cmd.args.drawIndexed.firstIndex = firstIndex;
1527 cmd.args.drawIndexed.vertexOffset = vertexOffset;
1528 cmd.args.drawIndexed.firstInstance = firstInstance;
1532 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
1539 cmd.args.drawIndirect.indirectBuffer =
QRHI_RES(QD3D11Buffer, indirectBuffer)->buffer;
1540 cmd.args.drawIndirect.indirectBufferOffset = indirectBufferOffset;
1541 cmd.args.drawIndirect.drawCount = drawCount;
1542 cmd.args.drawIndirect.stride = stride;
1547 switch (rt->resourceType()) {
1548 case QRhiResource::SwapChainRenderTarget:
1549 return &
QRHI_RES(QD3D11SwapChainRenderTarget, rt)->d;
1550 case QRhiResource::TextureRenderTarget:
1551 return &
QRHI_RES(QD3D11TextureRenderTarget, rt)->d;
1559 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
1566 cmd.args.drawIndexedIndirect.indirectBuffer =
QRHI_RES(QD3D11Buffer, indirectBuffer)->buffer;
1567 cmd.args.drawIndexedIndirect.indirectBufferOffset = indirectBufferOffset;
1568 cmd.args.drawIndexedIndirect.drawCount = drawCount;
1569 cmd.args.drawIndexedIndirect.stride = stride;
1574 if (!debugMarkers || !annotations)
1580 qstrncpy(cmd.args.debugMark.s, name.constData(),
sizeof(cmd.args.debugMark.s));
1585 if (!debugMarkers || !annotations)
1595 if (!debugMarkers || !annotations)
1601 qstrncpy(cmd.args.debugMark.s, msg.constData(),
sizeof(cmd.args.debugMark.s));
1620 Q_ASSERT(cbD->commands.isEmpty());
1622 if (cbD->currentTarget) {
1626 fbCmd.args.setRenderTarget.rtViews = rtD->views;
1641 return QRhi::FrameOpDeviceLost;
1644 contextState.currentSwapChain = swapChainD;
1648 if (swapChainD->frameLatencyWaitableObject) {
1651 WaitForSingleObjectEx(swapChainD->frameLatencyWaitableObject, 1000,
true);
1656 swapChainD->cb.resetState();
1658 swapChainD->rt.d.views.setFrom(1,
1659 swapChainD->sampleDesc.Count > 1 ? &swapChainD->msaaRtv[currentFrameSlot] : &swapChainD->backBufferRtv,
1660 swapChainD
->ds ? swapChainD
->ds->dsv :
nullptr);
1665 double elapsedSec = 0;
1667 swapChainD->cb.lastGpuTime = elapsedSec;
1676 cmd.args.beginFrame.tsQuery = recordTimestamps ? tsStart :
nullptr;
1677 cmd.args.beginFrame.tsDisjointQuery = recordTimestamps ? tsDisjoint :
nullptr;
1678 cmd.args.beginFrame.swapchainRtv = swapChainD->rt.d.views.rtv[0];
1679 cmd.args.beginFrame.swapchainDsv = swapChainD->rt.d.views.dsv;
1681 QDxgiVSyncService::instance()->beginFrame(adapterLuid);
1683 return QRhi::FrameOpSuccess;
1689 Q_ASSERT(contextState.currentSwapChain = swapChainD);
1694 cmd.args.endFrame.tsQuery =
nullptr;
1695 cmd.args.endFrame.tsDisjointQuery =
nullptr;
1700 if (swapChainD->sampleDesc.Count > 1) {
1701 context->ResolveSubresource(swapChainD->backBufferTex, 0,
1702 swapChainD->msaaTex[currentFrameSlot], 0,
1703 swapChainD->colorFormat);
1710 if (recordTimestamps) {
1711 context->End(tsEnd);
1712 context->End(tsDisjoint);
1717 if (!flags.testFlag(QRhi::SkipPresent)) {
1718 UINT presentFlags = 0;
1719 if (swapChainD->swapInterval == 0 && (swapChainD->swapChainFlags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING))
1720 presentFlags |= DXGI_PRESENT_ALLOW_TEARING;
1721 if (!swapChainD->swapChain) {
1722 qWarning(
"Failed to present: IDXGISwapChain is unavailable");
1723 return QRhi::FrameOpError;
1725 HRESULT hr = swapChainD->swapChain->Present(swapChainD->swapInterval, presentFlags);
1726 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
1727 qWarning(
"Device loss detected in Present()");
1729 return QRhi::FrameOpDeviceLost;
1730 }
else if (FAILED(hr)) {
1731 qWarning(
"Failed to present: %s",
1732 qPrintable(QSystemError::windowsComString(hr)));
1733 return QRhi::FrameOpError;
1736 if (dcompDevice && swapChainD->dcompTarget && swapChainD->dcompVisual)
1737 dcompDevice->Commit();
1746 contextState.currentSwapChain =
nullptr;
1748 return QRhi::FrameOpSuccess;
1756 ofr.cbWrapper.resetState();
1757 *cb = &ofr.cbWrapper;
1759 if (rhiFlags.testFlag(QRhi::EnableTimestamps)) {
1760 D3D11_QUERY_DESC queryDesc = {};
1761 if (!ofr.tsDisjointQuery) {
1762 queryDesc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
1763 HRESULT hr = dev->CreateQuery(&queryDesc, &ofr.tsDisjointQuery);
1765 qWarning(
"Failed to create timestamp disjoint query: %s",
1766 qPrintable(QSystemError::windowsComString(hr)));
1767 return QRhi::FrameOpError;
1770 queryDesc.Query = D3D11_QUERY_TIMESTAMP;
1771 for (
int i = 0; i < 2; ++i) {
1772 if (!ofr.tsQueries[i]) {
1773 HRESULT hr = dev->CreateQuery(&queryDesc, &ofr.tsQueries[i]);
1775 qWarning(
"Failed to create timestamp query: %s",
1776 qPrintable(QSystemError::windowsComString(hr)));
1777 return QRhi::FrameOpError;
1785 cmd.args.beginFrame.tsQuery = ofr.tsQueries[0] ? ofr.tsQueries[0] :
nullptr;
1786 cmd.args.beginFrame.tsDisjointQuery = ofr.tsDisjointQuery ? ofr.tsDisjointQuery :
nullptr;
1787 cmd.args.beginFrame.swapchainRtv =
nullptr;
1788 cmd.args.beginFrame.swapchainDsv =
nullptr;
1790 return QRhi::FrameOpSuccess;
1800 cmd.args.endFrame.tsQuery = ofr.tsQueries[1] ? ofr.tsQueries[1] :
nullptr;
1801 cmd.args.endFrame.tsDisjointQuery = ofr.tsDisjointQuery ? ofr.tsDisjointQuery :
nullptr;
1808 if (ofr.tsQueries[0]) {
1809 quint64 timestamps[2];
1810 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT dj;
1814 hr = context->GetData(ofr.tsDisjointQuery, &dj,
sizeof(dj), 0);
1815 }
while (hr == S_FALSE);
1818 hr = context->GetData(ofr.tsQueries[1], ×tamps[1],
sizeof(quint64), 0);
1819 }
while (hr == S_FALSE);
1822 hr = context->GetData(ofr.tsQueries[0], ×tamps[0],
sizeof(quint64), 0);
1823 }
while (hr == S_FALSE);
1826 if (!dj.Disjoint && dj.Frequency) {
1827 const float elapsedMs = (timestamps[1] - timestamps[0]) /
float(dj.Frequency) * 1000.0f;
1828 ofr.cbWrapper.lastGpuTime = elapsedMs / 1000.0;
1833 return QRhi::FrameOpSuccess;
1838 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
1840 case QRhiTexture::RGBA8:
1841 return srgb ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
1842 case QRhiTexture::BGRA8:
1843 return srgb ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : DXGI_FORMAT_B8G8R8A8_UNORM;
1844 case QRhiTexture::R8:
1845 return DXGI_FORMAT_R8_UNORM;
1846 case QRhiTexture::R8SI:
1847 return DXGI_FORMAT_R8_SINT;
1848 case QRhiTexture::R8UI:
1849 return DXGI_FORMAT_R8_UINT;
1850 case QRhiTexture::RG8:
1851 return DXGI_FORMAT_R8G8_UNORM;
1852 case QRhiTexture::R16:
1853 return DXGI_FORMAT_R16_UNORM;
1854 case QRhiTexture::RG16:
1855 return DXGI_FORMAT_R16G16_UNORM;
1856 case QRhiTexture::RED_OR_ALPHA8:
1857 return DXGI_FORMAT_R8_UNORM;
1859 case QRhiTexture::RGBA16F:
1860 return DXGI_FORMAT_R16G16B16A16_FLOAT;
1861 case QRhiTexture::RGBA32F:
1862 return DXGI_FORMAT_R32G32B32A32_FLOAT;
1863 case QRhiTexture::R16F:
1864 return DXGI_FORMAT_R16_FLOAT;
1865 case QRhiTexture::R32F:
1866 return DXGI_FORMAT_R32_FLOAT;
1868 case QRhiTexture::RGB10A2:
1869 return DXGI_FORMAT_R10G10B10A2_UNORM;
1871 case QRhiTexture::R32SI:
1872 return DXGI_FORMAT_R32_SINT;
1873 case QRhiTexture::R32UI:
1874 return DXGI_FORMAT_R32_UINT;
1875 case QRhiTexture::RG32SI:
1876 return DXGI_FORMAT_R32G32_SINT;
1877 case QRhiTexture::RG32UI:
1878 return DXGI_FORMAT_R32G32_UINT;
1879 case QRhiTexture::RGBA32SI:
1880 return DXGI_FORMAT_R32G32B32A32_SINT;
1881 case QRhiTexture::RGBA32UI:
1882 return DXGI_FORMAT_R32G32B32A32_UINT;
1884 case QRhiTexture::D16:
1885 return DXGI_FORMAT_R16_TYPELESS;
1886 case QRhiTexture::D24:
1887 return DXGI_FORMAT_R24G8_TYPELESS;
1888 case QRhiTexture::D24S8:
1889 return DXGI_FORMAT_R24G8_TYPELESS;
1890 case QRhiTexture::D32F:
1891 return DXGI_FORMAT_R32_TYPELESS;
1892 case QRhiTexture::D32FS8:
1893 return DXGI_FORMAT_R32G8X24_TYPELESS;
1895 case QRhiTexture::BC1:
1896 return srgb ? DXGI_FORMAT_BC1_UNORM_SRGB : DXGI_FORMAT_BC1_UNORM;
1897 case QRhiTexture::BC2:
1898 return srgb ? DXGI_FORMAT_BC2_UNORM_SRGB : DXGI_FORMAT_BC2_UNORM;
1899 case QRhiTexture::BC3:
1900 return srgb ? DXGI_FORMAT_BC3_UNORM_SRGB : DXGI_FORMAT_BC3_UNORM;
1901 case QRhiTexture::BC4:
1902 return DXGI_FORMAT_BC4_UNORM;
1903 case QRhiTexture::BC5:
1904 return DXGI_FORMAT_BC5_UNORM;
1905 case QRhiTexture::BC6H:
1906 return DXGI_FORMAT_BC6H_UF16;
1907 case QRhiTexture::BC7:
1908 return srgb ? DXGI_FORMAT_BC7_UNORM_SRGB : DXGI_FORMAT_BC7_UNORM;
1910 case QRhiTexture::ETC2_RGB8:
1911 case QRhiTexture::ETC2_RGB8A1:
1912 case QRhiTexture::ETC2_RGBA8:
1913 qWarning(
"QRhiD3D11 does not support ETC2 textures");
1914 return DXGI_FORMAT_R8G8B8A8_UNORM;
1916 case QRhiTexture::ASTC_4x4:
1917 case QRhiTexture::ASTC_5x4:
1918 case QRhiTexture::ASTC_5x5:
1919 case QRhiTexture::ASTC_6x5:
1920 case QRhiTexture::ASTC_6x6:
1921 case QRhiTexture::ASTC_8x5:
1922 case QRhiTexture::ASTC_8x6:
1923 case QRhiTexture::ASTC_8x8:
1924 case QRhiTexture::ASTC_10x5:
1925 case QRhiTexture::ASTC_10x6:
1926 case QRhiTexture::ASTC_10x8:
1927 case QRhiTexture::ASTC_10x10:
1928 case QRhiTexture::ASTC_12x10:
1929 case QRhiTexture::ASTC_12x12:
1930 qWarning(
"QRhiD3D11 does not support ASTC textures");
1931 return DXGI_FORMAT_R8G8B8A8_UNORM;
1935 return DXGI_FORMAT_R8G8B8A8_UNORM;
1942 case DXGI_FORMAT_R8G8B8A8_UNORM:
1943 return QRhiTexture::RGBA8;
1944 case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
1946 (*flags) |= QRhiTexture::sRGB;
1947 return QRhiTexture::RGBA8;
1948 case DXGI_FORMAT_B8G8R8A8_UNORM:
1949 return QRhiTexture::BGRA8;
1950 case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
1952 (*flags) |= QRhiTexture::sRGB;
1953 return QRhiTexture::BGRA8;
1954 case DXGI_FORMAT_R16G16B16A16_FLOAT:
1955 return QRhiTexture::RGBA16F;
1956 case DXGI_FORMAT_R32G32B32A32_FLOAT:
1957 return QRhiTexture::RGBA32F;
1958 case DXGI_FORMAT_R10G10B10A2_UNORM:
1959 return QRhiTexture::RGB10A2;
1961 qWarning(
"DXGI_FORMAT %d cannot be read back", format);
1964 return QRhiTexture::UnknownFormat;
1970 case QRhiTexture::Format::D16:
1971 case QRhiTexture::Format::D24:
1972 case QRhiTexture::Format::D24S8:
1973 case QRhiTexture::Format::D32F:
1974 case QRhiTexture::Format::D32FS8:
1986 Q_ASSERT(!contextState.currentSwapChain);
1987 Q_ASSERT(ofr.cbWrapper.recordingPass == QD3D11CommandBuffer::NoPass);
1989 ofr.cbWrapper.resetCommands();
1991 Q_ASSERT(contextState.currentSwapChain);
1994 contextState.currentSwapChain->cb.resetCommands();
2000 return QRhi::FrameOpSuccess;
2004 int layer,
int level,
const QRhiTextureSubresourceUploadDescription &subresDesc)
2006 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
2007 UINT subres = D3D11CalcSubresource(UINT(level), is3D ? 0u : UINT(layer), texD
->mipLevelCount);
2009 box.front = is3D ? UINT(layer) : 0u;
2011 box.back = box.front + 1;
2014 cmd.args.updateSubRes.dst = texD->textureResource();
2015 cmd.args.updateSubRes.dstSubRes = subres;
2017 const QPoint dp = subresDesc.destinationTopLeft();
2018 if (!subresDesc.image().isNull()) {
2019 QImage img = subresDesc.image();
2020 QSize size = img.size();
2021 int bpl = img.bytesPerLine();
2022 if (!subresDesc.sourceSize().isEmpty() || !subresDesc.sourceTopLeft().isNull()) {
2023 const QPoint sp = subresDesc.sourceTopLeft();
2024 if (!subresDesc.sourceSize().isEmpty())
2025 size = subresDesc.sourceSize();
2026 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
2027 if (img.depth() == 32) {
2028 const int offset = sp.y() * img.bytesPerLine() + sp.x() * 4;
2029 cmd.args.updateSubRes.src = cbD->retainImage(img) + offset;
2031 img = img.copy(sp.x(), sp.y(), size.width(), size.height());
2032 bpl = img.bytesPerLine();
2033 cmd.args.updateSubRes.src = cbD->retainImage(img);
2036 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
2037 cmd.args.updateSubRes.src = cbD->retainImage(img);
2039 box.left = UINT(dp.x());
2040 box.top = UINT(dp.y());
2041 box.right = UINT(dp.x() + size.width());
2042 box.bottom = UINT(dp.y() + size.height());
2043 cmd.args.updateSubRes.hasDstBox =
true;
2044 cmd.args.updateSubRes.dstBox = box;
2045 cmd.args.updateSubRes.srcRowPitch = UINT(bpl);
2046 }
else if (!subresDesc.data().isEmpty() && isCompressedFormat(texD->m_format)) {
2047 QSize size = subresDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
2048 : subresDesc.sourceSize();
2049 size = clampedCompressedSubResourceUploadSizeForSourceData(texD->m_format, size,
2050 subresDesc.data().size());
2051 if (size.height() == 0) {
2052 cbD->commands.unget();
2057 compressedFormatInfo(texD->m_format, size, &bpl,
nullptr, &blockDim);
2061 box.left = UINT(aligned(dp.x(), blockDim.width()));
2062 box.top = UINT(aligned(dp.y(), blockDim.height()));
2063 box.right = UINT(aligned(dp.x() + size.width(), blockDim.width()));
2064 box.bottom = UINT(aligned(dp.y() + size.height(), blockDim.height()));
2065 cmd.args.updateSubRes.hasDstBox =
true;
2066 cmd.args.updateSubRes.dstBox = box;
2067 cmd.args.updateSubRes.src = cbD->retainData(subresDesc.data());
2068 cmd.args.updateSubRes.srcRowPitch = bpl;
2069 }
else if (!subresDesc.data().isEmpty()) {
2070 QSize size = subresDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
2071 : subresDesc.sourceSize();
2072 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
2073 quint32 bytesPerPixel = 0;
2074 textureFormatInfo(texD->m_format, size,
nullptr,
nullptr, &bytesPerPixel);
2075 size = clampedSubResourceUploadSizeForSourceData(size, subresDesc.dataStride(),
2076 bytesPerPixel, subresDesc.data().size());
2077 if (size.isEmpty()) {
2078 cbD->commands.unget();
2082 if (subresDesc.dataStride())
2083 bpl = subresDesc.dataStride();
2085 textureFormatInfo(texD->m_format, size, &bpl,
nullptr,
nullptr);
2086 box.left = UINT(dp.x());
2087 box.top = UINT(dp.y());
2088 box.right = UINT(dp.x() + size.width());
2089 box.bottom = UINT(dp.y() + size.height());
2090 cmd.args.updateSubRes.hasDstBox =
true;
2091 cmd.args.updateSubRes.dstBox = box;
2092 cmd.args.updateSubRes.src = cbD->retainData(subresDesc.data());
2093 cmd.args.updateSubRes.srcRowPitch = bpl;
2095 qWarning(
"Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
2096 cbD->commands.unget();
2109 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
2110 memcpy(bufD
->dynBuf + u.offset, u.data.constData(), size_t(u.data.size()));
2114 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
2115 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
2118 cmd.args.updateSubRes.dst = bufD->buffer;
2119 cmd.args.updateSubRes.dstSubRes = 0;
2120 cmd.args.updateSubRes.src = cbD->retainBufferData(u.data);
2121 cmd.args.updateSubRes.srcRowPitch = 0;
2126 box.left = u.offset;
2127 box.top = box.front = 0;
2128 box.back = box.bottom = 1;
2129 box.right = u.offset + u.data.size();
2130 cmd.args.updateSubRes.hasDstBox =
true;
2131 cmd.args.updateSubRes.dstBox = box;
2134 if (bufD->m_type == QRhiBuffer::Dynamic) {
2135 u.result->data.resize(u.readSize);
2136 memcpy(u.result->data.data(), bufD
->dynBuf + u.offset, size_t(u.readSize));
2137 if (u.result->completed)
2138 u.result->completed();
2141 readback.result = u.result;
2142 readback.byteSize = u.readSize;
2144 D3D11_BUFFER_DESC desc = {};
2145 desc.ByteWidth = readback.byteSize;
2146 desc.Usage = D3D11_USAGE_STAGING;
2147 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
2148 HRESULT hr = dev->CreateBuffer(&desc,
nullptr, &readback.stagingBuf);
2150 qWarning(
"Failed to create buffer: %s",
2151 qPrintable(QSystemError::windowsComString(hr)));
2157 cmd.args.copySubRes.dst = readback.stagingBuf;
2158 cmd.args.copySubRes.dstSubRes = 0;
2159 cmd.args.copySubRes.dstX = 0;
2160 cmd.args.copySubRes.dstY = 0;
2161 cmd.args.copySubRes.dstZ = 0;
2162 cmd.args.copySubRes.src = bufD->buffer;
2163 cmd.args.copySubRes.srcSubRes = 0;
2164 cmd.args.copySubRes.hasSrcBox =
true;
2166 box.left = u.offset;
2167 box.top = box.front = 0;
2168 box.back = box.bottom = 1;
2169 box.right = u.offset + u.readSize;
2170 cmd.args.copySubRes.srcBox = box;
2172 activeBufferReadbacks.append(readback);
2177 Q_ASSERT(dstD->m_type != QRhiBuffer::Dynamic && srcD->m_type != QRhiBuffer::Dynamic);
2181 cmd.args.copySubRes.dst = dstD->buffer;
2182 cmd.args.copySubRes.dstSubRes = 0;
2183 cmd.args.copySubRes.dstX = u.offset;
2184 cmd.args.copySubRes.dstY = 0;
2185 cmd.args.copySubRes.dstZ = 0;
2186 cmd.args.copySubRes.src = srcD->buffer;
2187 cmd.args.copySubRes.srcSubRes = 0;
2188 cmd.args.copySubRes.hasSrcBox =
true;
2190 box.left = u.srcOffset;
2191 box.top = box.front = 0;
2192 box.back = box.bottom = 1;
2193 box.right = u.srcOffset + u.readSize;
2194 cmd.args.copySubRes.srcBox = box;
2197 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
2199 ID3D11UnorderedAccessView *uav = bufD->createClearUnorderedAccessView(u.offset, u.readSize);
2202 cbD->ownedUavs.append(uav);
2206 cmd.args.clearUav.uav = uav;
2207 for (UINT &v : cmd.args.clearUav.values)
2208 v = u.fillValue32();
2215 for (
const auto &subres : u.subresDesc)
2216 enqueueSubresUpload(texD, cbD, subres.layer, subres.level, subres.desc);
2221 const bool srcIs3D = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
2222 const bool dstIs3D = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
2223 UINT srcSubRes = D3D11CalcSubresource(UINT(u.desc.sourceLevel()), srcIs3D ? 0u : UINT(u.desc.sourceLayer()), srcD
->mipLevelCount);
2224 UINT dstSubRes = D3D11CalcSubresource(UINT(u.desc.destinationLevel()), dstIs3D ? 0u : UINT(u.desc.destinationLayer()), dstD
->mipLevelCount);
2225 const QPoint dp = u.desc.destinationTopLeft();
2226 const QSize mipSize = q->sizeForMipLevel(u.desc.sourceLevel(), srcD->m_pixelSize);
2227 const QSize copySize = u.desc.pixelSize().isEmpty() ? mipSize : u.desc.pixelSize();
2228 const QPoint sp = u.desc.sourceTopLeft();
2230 srcBox.left = UINT(sp.x());
2231 srcBox.top = UINT(sp.y());
2232 srcBox.front = srcIs3D ? UINT(u.desc.sourceLayer()) : 0u;
2234 srcBox.right = srcBox.left + UINT(copySize.width());
2235 srcBox.bottom = srcBox.top + UINT(copySize.height());
2236 srcBox.back = srcBox.front + 1;
2239 cmd.args.copySubRes.dst = dstD->textureResource();
2240 cmd.args.copySubRes.dstSubRes = dstSubRes;
2241 cmd.args.copySubRes.dstX = UINT(dp.x());
2242 cmd.args.copySubRes.dstY = UINT(dp.y());
2243 cmd.args.copySubRes.dstZ = dstIs3D ? UINT(u.desc.destinationLayer()) : 0u;
2244 cmd.args.copySubRes.src = srcD->textureResource();
2245 cmd.args.copySubRes.srcSubRes = srcSubRes;
2246 cmd.args.copySubRes.hasSrcBox =
true;
2247 cmd.args.copySubRes.srcBox = srcBox;
2250 readback.desc = u.rb;
2251 readback.result = u.result;
2253 ID3D11Resource *src;
2254 DXGI_FORMAT dxgiFormat;
2258 QRhiTexture::Format format;
2265 if (texD->sampleDesc.Count > 1) {
2266 qWarning(
"Multisample texture cannot be read back");
2269 src = texD->textureResource();
2270 dxgiFormat = texD->dxgiFormat;
2271 format = texD->m_format;
2272 const QRect levelRect(QPoint(0, 0), q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize));
2273 rect = u.rb.rect().isValid() ? u.rb.rect() : levelRect;
2275 if (isDepthTextureFormat(format)) {
2282 rect = rect.intersected(levelRect);
2283 copyRect = levelRect;
2284 cropOrigin = rect.topLeft();
2286 is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
2287 subres = D3D11CalcSubresource(UINT(u.rb.level()), UINT(is3D ? 0 : u.rb.layer()), texD
->mipLevelCount);
2289 Q_ASSERT(contextState.currentSwapChain);
2291 if (swapChainD->sampleDesc.Count > 1) {
2296 rcmd.args.resolveSubRes.dst = swapChainD->backBufferTex;
2297 rcmd.args.resolveSubRes.dstSubRes = 0;
2299 rcmd.args.resolveSubRes.srcSubRes = 0;
2300 rcmd.args.resolveSubRes.format = swapChainD->colorFormat;
2302 src = swapChainD->backBufferTex;
2303 dxgiFormat = swapChainD->colorFormat;
2304 if (u.rb.rect().isValid())
2307 rect = QRect({0, 0}, swapChainD->pixelSize);
2309 format = swapchainReadbackTextureFormat(dxgiFormat,
nullptr);
2310 if (format == QRhiTexture::UnknownFormat)
2313 quint32 byteSize = 0;
2315 quint32 bytesPerPixel = 0;
2316 textureFormatInfo(format, rect.size(), &bpl, &byteSize, &bytesPerPixel);
2318 D3D11_TEXTURE2D_DESC desc = {};
2319 desc.Width = UINT(copyRect.width());
2320 desc.Height = UINT(copyRect.height());
2323 desc.Format = dxgiFormat;
2324 desc.SampleDesc.Count = 1;
2325 desc.Usage = D3D11_USAGE_STAGING;
2326 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
2327 ID3D11Texture2D *stagingTex;
2328 HRESULT hr = dev->CreateTexture2D(&desc,
nullptr, &stagingTex);
2330 qWarning(
"Failed to create readback staging texture: %s",
2331 qPrintable(QSystemError::windowsComString(hr)));
2337 cmd.args.copySubRes.dst = stagingTex;
2338 cmd.args.copySubRes.dstSubRes = 0;
2339 cmd.args.copySubRes.dstX = 0;
2340 cmd.args.copySubRes.dstY = 0;
2341 cmd.args.copySubRes.dstZ = 0;
2342 cmd.args.copySubRes.src = src;
2343 cmd.args.copySubRes.srcSubRes = subres;
2345 D3D11_BOX srcBox = {};
2346 srcBox.left = UINT(copyRect.left());
2347 srcBox.top = UINT(copyRect.top());
2348 srcBox.front = is3D ? UINT(u.rb.layer()) : 0u;
2350 srcBox.right = srcBox.left + desc.Width;
2351 srcBox.bottom = srcBox.top + desc.Height;
2352 srcBox.back = srcBox.front + 1;
2354 cmd.args.copySubRes.hasSrcBox = !isDepthTextureFormat(format);
2355 cmd.args.copySubRes.srcBox = srcBox;
2357 readback.stagingTex = stagingTex;
2358 readback.byteSize = byteSize;
2360 readback.pixelSize = rect.size();
2361 readback.format = format;
2362 readback.cropOrigin = cropOrigin;
2363 readback.bytesPerPixel = bytesPerPixel;
2365 activeTextureReadbacks.append(readback);
2367 Q_ASSERT(u
.dst->flags().testFlag(QRhiTexture::UsedWithGenerateMips));
2370 cmd.args.genMip.srv =
QRHI_RES(QD3D11Texture, u.dst)->srv;
2379 QVarLengthArray<std::function<
void()>, 4> completedCallbacks;
2381 for (
int i = activeTextureReadbacks.count() - 1; i >= 0; --i) {
2383 readback.result->format = readback.format;
2384 readback.result->pixelSize = readback.pixelSize;
2386 D3D11_MAPPED_SUBRESOURCE mp;
2387 HRESULT hr = context->Map(readback.stagingTex, 0, D3D11_MAP_READ, 0, &mp);
2388 if (SUCCEEDED(hr)) {
2389 readback.result->data.resize(
int(readback.byteSize));
2392 char *dst = readback.result->data.data();
2393 char *src =
static_cast<
char *>(mp.pData)
2394 + readback.cropOrigin.y() * mp.RowPitch
2395 + readback.cropOrigin.x() * readback.bytesPerPixel;
2396 for (
int y = 0, h = readback.pixelSize.height(); y != h; ++y) {
2397 memcpy(dst, src, readback.bpl);
2398 dst += readback.bpl;
2401 context->Unmap(readback.stagingTex, 0);
2410 char *p = readback.result->data.data();
2411 if (readback.format == QRhiTexture::D24 || readback.format == QRhiTexture::D24S8) {
2412 const bool hasStencil = readback.format == QRhiTexture::D24S8;
2413 for (qsizetype px = 0, count = readback.result->data.size() / 4; px < count; ++px) {
2414 const quint32 texel = qFromUnaligned<quint32>(p + px * 4);
2415 const quint32 stencil = hasStencil ? texel >> 24 : 0;
2416 qToUnaligned(((texel & 0x00FFFFFFu) << 8) | stencil, p + px * 4);
2418 }
else if (readback.format == QRhiTexture::D32FS8) {
2419 for (qsizetype px = 1, count = readback.result->data.size() / 4; px < count; px += 2)
2420 qToUnaligned(qFromUnaligned<quint32>(p + px * 4) & 0xFFu, p + px * 4);
2423 qWarning(
"Failed to map readback staging texture: %s",
2424 qPrintable(QSystemError::windowsComString(hr)));
2427 readback.stagingTex->Release();
2429 if (readback.result->completed)
2430 completedCallbacks.append(readback.result->completed);
2432 activeTextureReadbacks.removeLast();
2435 for (
int i = activeBufferReadbacks.count() - 1; i >= 0; --i) {
2438 D3D11_MAPPED_SUBRESOURCE mp;
2439 HRESULT hr = context->Map(readback.stagingBuf, 0, D3D11_MAP_READ, 0, &mp);
2440 if (SUCCEEDED(hr)) {
2441 readback.result->data.resize(
int(readback.byteSize));
2442 memcpy(readback.result->data.data(), mp.pData, readback.byteSize);
2443 context->Unmap(readback.stagingBuf, 0);
2445 qWarning(
"Failed to map readback staging texture: %s",
2446 qPrintable(QSystemError::windowsComString(hr)));
2449 readback.stagingBuf->Release();
2451 if (readback.result->completed)
2452 completedCallbacks.append(readback.result->completed);
2454 activeBufferReadbacks.removeLast();
2457 for (
auto f : completedCallbacks)
2463 Q_ASSERT(
QRHI_RES(QD3D11CommandBuffer, cb)->recordingPass == QD3D11CommandBuffer::NoPass);
2469 QRhiRenderTarget *rt,
2470 const QColor &colorClearValue,
2471 const QRhiDepthStencilClearValue &depthStencilClearValue,
2472 QRhiResourceUpdateBatch *resourceUpdates,
2478 if (resourceUpdates)
2481 bool wantsColorClear =
true;
2482 bool wantsDsClear =
true;
2484 if (rt->resourceType() == QRhiRenderTarget::TextureRenderTarget) {
2486 wantsColorClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
2487 wantsDsClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
2488 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QD3D11Texture, QD3D11RenderBuffer>(rtTex->description(), rtD->currentResIdList))
2496 fbCmd.args.setRenderTarget.rtViews = rtD->views;
2500 clearCmd.args.clear.rtViews = rtD->views;
2501 clearCmd.args.clear.mask = 0;
2502 if (rtD->views.colorAttCount && wantsColorClear)
2504 if (rtD->views.dsv && wantsDsClear)
2507 clearCmd.args.clear.c[0] = colorClearValue.redF();
2508 clearCmd.args.clear.c[1] = colorClearValue.greenF();
2509 clearCmd.args.clear.c[2] = colorClearValue.blueF();
2510 clearCmd.args.clear.c[3] = colorClearValue.alphaF();
2511 clearCmd.args.clear.d = depthStencilClearValue.depthClearValue();
2512 clearCmd.args.clear.s = depthStencilClearValue.stencilClearValue();
2515 cbD->currentTarget = rt;
2525 if (cbD->currentTarget->resourceType() == QRhiResource::TextureRenderTarget) {
2527 for (
auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments();
2530 const QRhiColorAttachment &colorAtt(*it);
2531 if (!colorAtt.resolveTexture())
2537 Q_ASSERT(srcTexD || srcRbD);
2540 cmd.args.resolveSubRes.dst = dstTexD->textureResource();
2541 cmd.args.resolveSubRes.dstSubRes = D3D11CalcSubresource(UINT(colorAtt.resolveLevel()),
2542 UINT(colorAtt.resolveLayer()),
2545 cmd.args.resolveSubRes.src = srcTexD->textureResource();
2546 if (srcTexD->dxgiFormat != dstTexD->dxgiFormat) {
2547 qWarning(
"Resolve source (%d) and destination (%d) formats do not match",
2548 int(srcTexD->dxgiFormat),
int(dstTexD->dxgiFormat));
2549 cbD->commands.unget();
2552 if (srcTexD->sampleDesc.Count <= 1) {
2553 qWarning(
"Cannot resolve a non-multisample texture");
2554 cbD->commands.unget();
2557 if (srcTexD->m_pixelSize != dstTexD->m_pixelSize) {
2558 qWarning(
"Resolve source and destination sizes do not match");
2559 cbD->commands.unget();
2563 cmd.args.resolveSubRes.src = srcRbD->tex;
2564 if (srcRbD->dxgiFormat != dstTexD->dxgiFormat) {
2565 qWarning(
"Resolve source (%d) and destination (%d) formats do not match",
2566 int(srcRbD->dxgiFormat),
int(dstTexD->dxgiFormat));
2567 cbD->commands.unget();
2570 if (srcRbD->m_pixelSize != dstTexD->m_pixelSize) {
2571 qWarning(
"Resolve source and destination sizes do not match");
2572 cbD->commands.unget();
2576 cmd.args.resolveSubRes.srcSubRes = D3D11CalcSubresource(0, UINT(colorAtt.layer()), 1);
2577 cmd.args.resolveSubRes.format = dstTexD->dxgiFormat;
2579 if (rtTex->m_desc.depthResolveTexture())
2580 qWarning(
"Resolving multisample depth-stencil buffers is not supported with D3D");
2584 cbD->currentTarget =
nullptr;
2586 if (resourceUpdates)
2591 QRhiResourceUpdateBatch *resourceUpdates,
2597 if (resourceUpdates)
2605 fbCmd.args.setRenderTarget.rtViews.reset();
2622 if (resourceUpdates)
2633 if (pipelineChanged) {
2634 cbD->currentGraphicsPipeline =
nullptr;
2635 cbD->currentComputePipeline = psD;
2640 cmd.args.bindComputePipeline.cs = psD->cs.shader;
2651 cmd.args.dispatch.x = UINT(x);
2652 cmd.args.dispatch.y = UINT(y);
2653 cmd.args.dispatch.z = UINT(z);
2657 quint32 indirectBufferOffset)
2664 cmd.args.dispatchIndirect.indirectBuffer =
QRHI_RES(QD3D11Buffer, indirectBuffer)->buffer;
2665 cmd.args.dispatchIndirect.indirectBufferOffset = indirectBufferOffset;
2669 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
2670 QRhiBuffer *countBuffer, quint32 countBufferOffset,
2671 quint32 maxDrawCount, quint32 stride)
2674 Q_UNUSED(indirectBuffer);
2675 Q_UNUSED(indirectBufferOffset);
2676 Q_UNUSED(countBuffer);
2677 Q_UNUSED(countBufferOffset);
2678 Q_UNUSED(maxDrawCount);
2680 qWarning(
"drawIndirectCount is not supported by the D3D11 backend");
2684 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
2685 QRhiBuffer *countBuffer, quint32 countBufferOffset,
2686 quint32 maxDrawCount, quint32 stride)
2689 Q_UNUSED(indirectBuffer);
2690 Q_UNUSED(indirectBufferOffset);
2691 Q_UNUSED(countBuffer);
2692 Q_UNUSED(countBufferOffset);
2693 Q_UNUSED(maxDrawCount);
2695 qWarning(
"drawIndexedIndirectCount is not supported by the D3D11 backend");
2700 const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[],
2701 uint pushConstantStages)
2703 const QShader::NativeResourceBindingMap *map = nativeResourceBindingMaps[stageIndex];
2704 if (!map || map->isEmpty()) {
2712 if (pushConstantStages & (1u << uint(stageIndex)))
2714 return { binding, binding };
2717 auto it = map->constFind(binding);
2718 if (it != map->cend())
2728 const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[],
2729 uint pushConstantStages)
2736 if (!srbD->resourceBatches || srbD->resourceBatches.use_count() > 1)
2739 srbD->resourceBatches->clear();
2747 ID3D11Buffer *buffer;
2748 uint offsetInConstants;
2749 uint sizeInConstants;
2753 ID3D11ShaderResourceView *srv;
2757 ID3D11SamplerState *sampler;
2761 ID3D11UnorderedAccessView *uav;
2763 QVarLengthArray<Buffer, 8> buffers;
2764 QVarLengthArray<Texture, 8> textures;
2765 QVarLengthArray<Sampler, 8> samplers;
2766 QVarLengthArray<Uav, 8> uavs;
2769 for (
const Buffer &buf : buffers) {
2770 batches.ubufs.feed(buf.breg, buf.buffer);
2771 batches.ubuforigbindings.feed(buf.breg, UINT(buf.binding));
2772 batches.ubufoffsets.feed(buf.breg, buf.offsetInConstants);
2773 batches.ubufsizes.feed(buf.breg, buf.sizeInConstants);
2779 for (
const Texture &t : textures)
2780 batches.shaderresources.feed(t.treg, t.srv);
2781 for (
const Sampler &s : samplers)
2782 batches.samplers.feed(s.sreg, s.sampler);
2787 for (
const Stage::Uav &u : uavs)
2788 batches.uavs.feed(u.ureg, u.uav);
2793 for (
int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
2794 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings.at(i));
2796 switch (b->type()) {
2797 case QRhiShaderResourceBinding::UniformBuffer:
2800 Q_ASSERT(aligned(b->ubuf().offset, 256u) == b->ubuf().offset);
2801 bd.ubuf.id = bufD->m_id;
2809 const quint32 offsetInConstants = b->ubuf().offset / 16;
2813 const quint32 sizeInConstants = aligned(b->ubuf().maybeSize ? b->ubuf().maybeSize : bufD->m_size, 256u) / 16;
2814 if (b->stage.testFlag(QRhiShaderResourceBinding::VertexStage)) {
2815 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_VERTEX, nativeResourceBindingMaps, pushConstantStages);
2816 if (nativeBinding.first >= 0)
2817 res[
RBM_VERTEX].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2819 if (b->stage.testFlag(QRhiShaderResourceBinding::TessellationControlStage)) {
2820 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_HULL, nativeResourceBindingMaps, pushConstantStages);
2821 if (nativeBinding.first >= 0)
2822 res[
RBM_HULL].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2824 if (b->stage.testFlag(QRhiShaderResourceBinding::TessellationEvaluationStage)) {
2825 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_DOMAIN, nativeResourceBindingMaps, pushConstantStages);
2826 if (nativeBinding.first >= 0)
2827 res[
RBM_DOMAIN].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2829 if (b->stage.testFlag(QRhiShaderResourceBinding::GeometryStage)) {
2830 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_GEOMETRY, nativeResourceBindingMaps, pushConstantStages);
2831 if (nativeBinding.first >= 0)
2832 res[
RBM_GEOMETRY].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2834 if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
2835 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_FRAGMENT, nativeResourceBindingMaps, pushConstantStages);
2836 if (nativeBinding.first >= 0)
2837 res[
RBM_FRAGMENT].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2839 if (b->stage.testFlag(QRhiShaderResourceBinding::ComputeStage)) {
2840 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_COMPUTE, nativeResourceBindingMaps, pushConstantStages);
2841 if (nativeBinding.first >= 0)
2842 res[
RBM_COMPUTE].buffers.append({ b->binding, nativeBinding.first, bufD->buffer, offsetInConstants, sizeInConstants });
2846 case QRhiShaderResourceBinding::SampledTexture:
2847 case QRhiShaderResourceBinding::Texture:
2848 case QRhiShaderResourceBinding::Sampler:
2850 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
2851 bd.stex.d.resize(data->count());
2852 const std::pair<
int,
int> nativeBindingVert = mapBinding(b->binding, RBM_VERTEX, nativeResourceBindingMaps, pushConstantStages);
2853 const std::pair<
int,
int> nativeBindingHull = mapBinding(b->binding, RBM_HULL, nativeResourceBindingMaps, pushConstantStages);
2854 const std::pair<
int,
int> nativeBindingDomain = mapBinding(b->binding, RBM_DOMAIN, nativeResourceBindingMaps, pushConstantStages);
2855 const std::pair<
int,
int> nativeBindingGeom = mapBinding(b->binding, RBM_GEOMETRY, nativeResourceBindingMaps, pushConstantStages);
2856 const std::pair<
int,
int> nativeBindingFrag = mapBinding(b->binding, RBM_FRAGMENT, nativeResourceBindingMaps, pushConstantStages);
2857 const std::pair<
int,
int> nativeBindingComp = mapBinding(b->binding, RBM_COMPUTE, nativeResourceBindingMaps, pushConstantStages);
2861 for (
int elem = 0; elem < data->count(); ++elem) {
2864 bd.stex.d[elem].texId = texD ? texD->m_id : 0;
2865 bd.stex.d[elem].texGeneration = texD ? texD
->generation : 0;
2866 bd.stex.d[elem].samplerId = samplerD ? samplerD->m_id : 0;
2867 bd.stex.d[elem].samplerGeneration = samplerD ? samplerD
->generation : 0;
2872 if (b->stage.testFlag(QRhiShaderResourceBinding::VertexStage)) {
2873 const int samplerBinding = texD && samplerD ? nativeBindingVert.second
2874 : (samplerD ? nativeBindingVert.first : -1);
2875 if (nativeBindingVert.first >= 0 && texD)
2876 res[
RBM_VERTEX].textures.append({ nativeBindingVert.first + elem, texD->srv });
2877 if (samplerBinding >= 0)
2878 res[
RBM_VERTEX].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2880 if (b->stage.testFlag(QRhiShaderResourceBinding::TessellationControlStage)) {
2881 const int samplerBinding = texD && samplerD ? nativeBindingHull.second
2882 : (samplerD ? nativeBindingHull.first : -1);
2883 if (nativeBindingHull.first >= 0 && texD)
2884 res[
RBM_HULL].textures.append({ nativeBindingHull.first + elem, texD->srv });
2885 if (samplerBinding >= 0)
2886 res[
RBM_HULL].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2888 if (b->stage.testFlag(QRhiShaderResourceBinding::TessellationEvaluationStage)) {
2889 const int samplerBinding = texD && samplerD ? nativeBindingDomain.second
2890 : (samplerD ? nativeBindingDomain.first : -1);
2891 if (nativeBindingDomain.first >= 0 && texD)
2892 res[
RBM_DOMAIN].textures.append({ nativeBindingDomain.first + elem, texD->srv });
2893 if (samplerBinding >= 0)
2894 res[
RBM_DOMAIN].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2896 if (b->stage.testFlag(QRhiShaderResourceBinding::GeometryStage)) {
2897 const int samplerBinding = texD && samplerD ? nativeBindingGeom.second
2898 : (samplerD ? nativeBindingGeom.first : -1);
2899 if (nativeBindingGeom.first >= 0 && texD)
2900 res[
RBM_GEOMETRY].textures.append({ nativeBindingGeom.first + elem, texD->srv });
2901 if (samplerBinding >= 0)
2902 res[
RBM_GEOMETRY].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2904 if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
2905 const int samplerBinding = texD && samplerD ? nativeBindingFrag.second
2906 : (samplerD ? nativeBindingFrag.first : -1);
2907 if (nativeBindingFrag.first >= 0 && texD)
2908 res[
RBM_FRAGMENT].textures.append({ nativeBindingFrag.first + elem, texD->srv });
2909 if (samplerBinding >= 0)
2910 res[
RBM_FRAGMENT].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2912 if (b->stage.testFlag(QRhiShaderResourceBinding::ComputeStage)) {
2913 const int samplerBinding = texD && samplerD ? nativeBindingComp.second
2914 : (samplerD ? nativeBindingComp.first : -1);
2915 if (nativeBindingComp.first >= 0 && texD)
2916 res[
RBM_COMPUTE].textures.append({ nativeBindingComp.first + elem, texD->srv });
2917 if (samplerBinding >= 0)
2918 res[
RBM_COMPUTE].samplers.append({ samplerBinding + elem, samplerD->samplerState });
2923 case QRhiShaderResourceBinding::ImageLoad:
2924 case QRhiShaderResourceBinding::ImageStore:
2925 case QRhiShaderResourceBinding::ImageLoadStore:
2928 bd.simage.id = texD->m_id;
2930 bool validStage =
false;
2931 if (b->stage.testFlag(QRhiShaderResourceBinding::ComputeStage)) {
2932 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_COMPUTE, nativeResourceBindingMaps, pushConstantStages);
2933 if (nativeBinding.first >= 0) {
2934 ID3D11UnorderedAccessView *uav = texD->unorderedAccessViewForLevel(b->simage().level);
2936 res[
RBM_COMPUTE].uavs.append({ nativeBinding.first, uav });
2940 if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
2941 QPair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_FRAGMENT, nativeResourceBindingMaps, pushConstantStages);
2942 if (nativeBinding.first >= 0) {
2943 ID3D11UnorderedAccessView *uav = texD->unorderedAccessViewForLevel(b->simage().level);
2945 res[
RBM_FRAGMENT].uavs.append({ nativeBinding.first, uav });
2950 qWarning(
"Unordered access only supported at fragment/compute stage");
2953 case QRhiShaderResourceBinding::BufferLoad:
2954 case QRhiShaderResourceBinding::BufferStore:
2955 case QRhiShaderResourceBinding::BufferLoadStore:
2958 bd.sbuf.id = bufD->m_id;
2960 bool validStage =
false;
2961 if (b->stage.testFlag(QRhiShaderResourceBinding::ComputeStage)) {
2962 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_COMPUTE, nativeResourceBindingMaps, pushConstantStages);
2963 if (nativeBinding.first >= 0) {
2964 ID3D11UnorderedAccessView *uav = bufD->unorderedAccessView(b->sbuf().offset);
2966 res[
RBM_COMPUTE].uavs.append({ nativeBinding.first, uav });
2970 if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
2971 std::pair<
int,
int> nativeBinding = mapBinding(b->binding, RBM_FRAGMENT, nativeResourceBindingMaps, pushConstantStages);
2972 if (nativeBinding.first >= 0) {
2973 ID3D11UnorderedAccessView *uav = bufD->unorderedAccessView(b->sbuf().offset);
2975 res[
RBM_FRAGMENT].uavs.append({ nativeBinding.first, uav });
2980 qWarning(
"Unordered access only supported at fragment/compute stage");
2994 std::sort(res[stage].buffers.begin(), res[stage].buffers.end(), [](
const Stage::Buffer &a,
const Stage::Buffer &b) {
2995 return a.breg < b.breg;
2997 std::sort(res[stage].textures.begin(), res[stage].textures.end(), [](
const Stage::Texture &a,
const Stage::Texture &b) {
2998 return a.treg < b.treg;
3000 std::sort(res[stage].samplers.begin(), res[stage].samplers.end(), [](
const Stage::Sampler &a,
const Stage::Sampler &b) {
3001 return a.sreg < b.sreg;
3003 std::sort(res[stage].uavs.begin(), res[stage].uavs.end(), [](
const Stage::Uav &a,
const Stage::Uav &b) {
3004 return a.ureg < b.ureg;
3008 res[
RBM_VERTEX].buildBufferBatches(batches.vsUniformBufferBatches);
3009 res[
RBM_HULL].buildBufferBatches(batches.hsUniformBufferBatches);
3010 res[
RBM_DOMAIN].buildBufferBatches(batches.dsUniformBufferBatches);
3011 res[
RBM_GEOMETRY].buildBufferBatches(batches.gsUniformBufferBatches);
3012 res[
RBM_FRAGMENT].buildBufferBatches(batches.fsUniformBufferBatches);
3013 res[
RBM_COMPUTE].buildBufferBatches(batches.csUniformBufferBatches);
3015 res[
RBM_VERTEX].buildSamplerBatches(batches.vsSamplerBatches);
3016 res[
RBM_HULL].buildSamplerBatches(batches.hsSamplerBatches);
3017 res[
RBM_DOMAIN].buildSamplerBatches(batches.dsSamplerBatches);
3018 res[
RBM_GEOMETRY].buildSamplerBatches(batches.gsSamplerBatches);
3019 res[
RBM_FRAGMENT].buildSamplerBatches(batches.fsSamplerBatches);
3020 res[
RBM_COMPUTE].buildSamplerBatches(batches.csSamplerBatches);
3022 res[
RBM_FRAGMENT].buildUavBatches(batches.fsUavBatches);
3023 res[
RBM_COMPUTE].buildUavBatches(batches.csUavBatches);
3031 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
3033 D3D11_MAPPED_SUBRESOURCE mp;
3034 HRESULT hr = context->Map(bufD->buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
3035 if (SUCCEEDED(hr)) {
3036 memcpy(mp.pData, bufD
->dynBuf, bufD->m_size);
3037 context->Unmap(bufD->buffer, 0);
3039 qWarning(
"Failed to map buffer: %s",
3040 qPrintable(QSystemError::windowsComString(hr)));
3046 const QRhiBatchedBindings<UINT> *originalBindings,
3047 const QRhiBatchedBindings<UINT> *staticOffsets,
3048 const uint *dynOfsPairs,
int dynOfsPairCount)
3050 const int count = staticOffsets->batches[batchIndex].resources.count();
3053 for (
int b = 0; b < count; ++b) {
3054 offsets[b] = staticOffsets->batches[batchIndex].resources[b];
3055 for (
int di = 0; di < dynOfsPairCount; ++di) {
3056 const uint binding = dynOfsPairs[2 * di];
3059 if (binding == originalBindings->batches[batchIndex].resources[b]) {
3060 const uint offsetInConstants = dynOfsPairs[2 * di + 1];
3061 offsets[b] = offsetInConstants;
3070 if (startSlot + countSlots > maxSlots) {
3071 qWarning(
"Not enough D3D11 %s slots to bind %d resources starting at slot %d, max slots is %d",
3072 resType, countSlots, startSlot, maxSlots);
3073 countSlots = maxSlots > startSlot ? maxSlots - startSlot : 0;
3078#define SETUBUFBATCH(stagePrefixL, stagePrefixU)
3079 if (allResourceBatches.stagePrefixL##UniformBufferBatches.present) {
3080 const QD3D11ShaderResourceBindings::StageUniformBufferBatches &batches(allResourceBatches.stagePrefixL##UniformBufferBatches);
3081 for (int i = 0
, ie = batches.ubufs.batches.count(); i != ie; ++i) {
3082 const uint count = clampedResourceCount(batches.ubufs.batches[i].startBinding,
3083 batches.ubufs.batches[i].resources.count(),
3084 D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT,
3085 #stagePrefixU " cbuf");
3087 if (!dynOfsPairCount) {
3088 context->stagePrefixU##SetConstantBuffers1(batches.ubufs.batches[i].startBinding,
3090 batches.ubufs.batches[i].resources.constData(),
3091 batches.ubufoffsets.batches[i].resources.constData(),
3092 batches.ubufsizes.batches[i].resources.constData());
3094 applyDynamicOffsets(offsets, i,
3095 &batches.ubuforigbindings, &batches.ubufoffsets,
3096 dynOfsPairs, dynOfsPairCount);
3097 context->stagePrefixU##SetConstantBuffers1(batches.ubufs.batches[i].startBinding,
3099 batches.ubufs.batches[i].resources.constData(),
3101 batches.ubufsizes.batches[i].resources.constData());
3107#define SETSAMPLERBATCH(stagePrefixL, stagePrefixU)
3108 if (allResourceBatches.stagePrefixL##SamplerBatches.present) {
3109 for (const auto &batch : allResourceBatches.stagePrefixL##SamplerBatches.samplers.batches) {
3110 const uint count = clampedResourceCount(batch.startBinding, batch.resources.count(),
3111 D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, #stagePrefixU " sampler");
3113 context->stagePrefixU##SetSamplers(batch.startBinding, count, batch.resources.constData());
3115 for (const auto &batch : allResourceBatches.stagePrefixL##SamplerBatches.shaderresources.batches) {
3116 const uint count = clampedResourceCount(batch.startBinding, batch.resources.count(),
3117 D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, #stagePrefixU " SRV");
3119 context->stagePrefixU##SetShaderResources(batch.startBinding, count, batch.resources.constData());
3120 contextState.stagePrefixL##HighestActiveSrvBinding = qMax(contextState.stagePrefixL##HighestActiveSrvBinding,
3121 int(batch.startBinding + count) - 1
);
3126#define SETUAVBATCH(stagePrefixL, stagePrefixU)
3127 if (allResourceBatches.stagePrefixL##UavBatches.present) {
3128 for (const auto &batch : allResourceBatches.stagePrefixL##UavBatches.uavs.batches) {
3129 const uint count = clampedResourceCount(batch.startBinding, batch.resources.count(),
3132 context->stagePrefixU##SetUnorderedAccessViews(batch.startBinding,
3134 batch.resources.constData(),
3136 contextState.stagePrefixL##HighestActiveUavBinding = qMax(contextState.stagePrefixL##HighestActiveUavBinding,
3137 int(batch.startBinding + count) - 1
);
3144 const uint *dynOfsPairs,
int dynOfsPairCount,
3145 bool offsetOnlyChange,
3157 if (!offsetOnlyChange) {
3167 if (allResourceBatches.fsUavBatches.present) {
3168 for (
const auto &batch : allResourceBatches.fsUavBatches.uavs.batches) {
3169 const uint count = qMin(clampedResourceCount(batch.startBinding, batch.resources.count(),
3171 uint(QD3D11RenderTargetData::MAX_COLOR_ATTACHMENTS));
3173 if (rtUavState->update(cbD->currentRenderTargetViews, batch.resources.constData(), count)) {
3174 context->OMSetRenderTargetsAndUnorderedAccessViews(
3175 UINT(rtUavState->rtViews.colorAttCount),
3176 rtUavState->rtViews.colorAttCount ? rtUavState->rtViews.rtv :
nullptr,
3177 rtUavState->rtViews.dsv,
3178 UINT(batch.startBinding),
3180 batch.resources.constData(),
3183 contextState.fsHighestActiveUavBinding = qMax(contextState.fsHighestActiveUavBinding,
3184 int(batch.startBinding + count) - 1);
3196 if (contextState.vsHasIndexBufferBound) {
3197 context->IASetIndexBuffer(
nullptr, DXGI_FORMAT_R16_UINT, 0);
3198 contextState.vsHasIndexBufferBound =
false;
3201 if (contextState.vsHighestActiveVertexBufferBinding >= 0) {
3202 const int count = contextState.vsHighestActiveVertexBufferBinding + 1;
3203 QVarLengthArray<ID3D11Buffer *, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> nullbufs(count);
3204 for (
int i = 0; i < count; ++i)
3205 nullbufs[i] =
nullptr;
3206 QVarLengthArray<UINT, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> nullstrides(count);
3207 for (
int i = 0; i < count; ++i)
3209 QVarLengthArray<UINT, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> nulloffsets(count);
3210 for (
int i = 0; i < count; ++i)
3212 context->IASetVertexBuffers(0, UINT(count), nullbufs.constData(), nullstrides.constData(), nulloffsets.constData());
3213 contextState.vsHighestActiveVertexBufferBinding = -1;
3216 int nullsrvCount = qMax(contextState.vsHighestActiveSrvBinding, contextState.fsHighestActiveSrvBinding);
3217 nullsrvCount = qMax(nullsrvCount, contextState.hsHighestActiveSrvBinding);
3218 nullsrvCount = qMax(nullsrvCount, contextState.dsHighestActiveSrvBinding);
3219 nullsrvCount = qMax(nullsrvCount, contextState.gsHighestActiveSrvBinding);
3220 nullsrvCount = qMax(nullsrvCount, contextState.csHighestActiveSrvBinding);
3222 if (nullsrvCount > 0) {
3223 QVarLengthArray<ID3D11ShaderResourceView *,
3224 D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT> nullsrvs(nullsrvCount);
3225 for (
int i = 0; i < nullsrvs.count(); ++i)
3226 nullsrvs[i] =
nullptr;
3227 if (contextState.vsHighestActiveSrvBinding >= 0) {
3228 context->VSSetShaderResources(0, UINT(contextState.vsHighestActiveSrvBinding + 1), nullsrvs.constData());
3229 contextState.vsHighestActiveSrvBinding = -1;
3231 if (contextState.hsHighestActiveSrvBinding >= 0) {
3232 context->HSSetShaderResources(0, UINT(contextState.hsHighestActiveSrvBinding + 1), nullsrvs.constData());
3233 contextState.hsHighestActiveSrvBinding = -1;
3235 if (contextState.dsHighestActiveSrvBinding >= 0) {
3236 context->DSSetShaderResources(0, UINT(contextState.dsHighestActiveSrvBinding + 1), nullsrvs.constData());
3237 contextState.dsHighestActiveSrvBinding = -1;
3239 if (contextState.gsHighestActiveSrvBinding >= 0) {
3240 context->GSSetShaderResources(0, UINT(contextState.gsHighestActiveSrvBinding + 1), nullsrvs.constData());
3241 contextState.gsHighestActiveSrvBinding = -1;
3243 if (contextState.fsHighestActiveSrvBinding >= 0) {
3244 context->PSSetShaderResources(0, UINT(contextState.fsHighestActiveSrvBinding + 1), nullsrvs.constData());
3245 contextState.fsHighestActiveSrvBinding = -1;
3247 if (contextState.csHighestActiveSrvBinding >= 0) {
3248 context->CSSetShaderResources(0, UINT(contextState.csHighestActiveSrvBinding + 1), nullsrvs.constData());
3249 contextState.csHighestActiveSrvBinding = -1;
3253 if (contextState.fsHighestActiveUavBinding >= 0) {
3254 rtUavState->update(cbD->currentRenderTargetViews);
3255 context->OMSetRenderTargetsAndUnorderedAccessViews(
3256 UINT(cbD->currentRenderTargetViews.colorAttCount),
3257 cbD->currentRenderTargetViews.colorAttCount ? cbD->currentRenderTargetViews.rtv :
nullptr,
3258 cbD->currentRenderTargetViews.dsv,
3259 0, 0,
nullptr,
nullptr);
3260 contextState.fsHighestActiveUavBinding = -1;
3262 if (contextState.csHighestActiveUavBinding >= 0) {
3263 const int nulluavCount = contextState.csHighestActiveUavBinding + 1;
3264 QVarLengthArray<ID3D11UnorderedAccessView *,
3265 D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT> nulluavs(nulluavCount);
3266 for (
int i = 0; i < nulluavCount; ++i)
3267 nulluavs[i] =
nullptr;
3268 context->CSSetUnorderedAccessViews(0, UINT(nulluavCount), nulluavs.constData(),
nullptr);
3269 contextState.csHighestActiveUavBinding = -1;
3273#define SETSHADER(StageL, StageU)
3274 if (cmd.args.bindGraphicsPipeline.StageL) {
3275 context->StageU##SetShader(cmd.args.bindGraphicsPipeline.StageL, nullptr, 0
);
3276 currentShaderMask |= StageU##MaskBit;
3277 } else if (currentShaderMask & StageU##MaskBit) {
3278 context->StageU##SetShader(nullptr, nullptr, 0
);
3279 currentShaderMask &= ~StageU##MaskBit;
3284 float blendConstants[] = { 1, 1, 1, 1 };
3285 enum ActiveShaderMask {
3292 int currentShaderMask = 0xFF;
3298 for (
auto it = cbD->commands.cbegin(), end = cbD->commands.cend(); it != end; ++it) {
3301 case QD3D11CommandBuffer::Command::BeginFrame:
3302 if (cmd.args.beginFrame.tsDisjointQuery)
3303 context->Begin(cmd.args.beginFrame.tsDisjointQuery);
3304 if (cmd.args.beginFrame.tsQuery) {
3305 if (cmd.args.beginFrame.swapchainRtv) {
3310 cbD->currentRenderTargetViews.setFrom(1, &cmd.args.beginFrame.swapchainRtv, cmd.args.beginFrame.swapchainDsv);
3311 rtUavState.update(cbD->currentRenderTargetViews);
3312 context->OMSetRenderTargets(1, &cmd.args.beginFrame.swapchainRtv, cmd.args.beginFrame.swapchainDsv);
3314 context->End(cmd.args.beginFrame.tsQuery);
3317 case QD3D11CommandBuffer::Command::EndFrame:
3318 if (cmd.args.endFrame.tsQuery)
3319 context->End(cmd.args.endFrame.tsQuery);
3320 if (cmd.args.endFrame.tsDisjointQuery)
3321 context->End(cmd.args.endFrame.tsDisjointQuery);
3328 cbD->currentRenderTargetViews = cmd.args.setRenderTarget.rtViews;
3329 if (rtUavState.update(cbD->currentRenderTargetViews)) {
3330 const UINT colorAttCount = UINT(cmd.args.setRenderTarget.rtViews.colorAttCount);
3331 context->OMSetRenderTargets(colorAttCount,
3332 colorAttCount ? cmd.args.setRenderTarget.rtViews.rtv :
nullptr,
3333 cmd.args.setRenderTarget.rtViews.dsv);
3340 for (
int i = 0; i < cmd.args.clear.rtViews.colorAttCount; ++i)
3341 context->ClearRenderTargetView(cmd.args.clear.rtViews.rtv[i], cmd.args.clear.c);
3345 ds |= D3D11_CLEAR_DEPTH;
3347 ds |= D3D11_CLEAR_STENCIL;
3348 if (ds && cmd.args.clear.rtViews.dsv)
3349 context->ClearDepthStencilView(cmd.args.clear.rtViews.dsv, ds, cmd.args.clear.d, UINT8(cmd.args.clear.s));
3355 v.TopLeftX = cmd.args.viewport.x;
3356 v.TopLeftY = cmd.args.viewport.y;
3357 v.Width = cmd.args.viewport.w;
3358 v.Height = cmd.args.viewport.h;
3359 v.MinDepth = cmd.args.viewport.d0;
3360 v.MaxDepth = cmd.args.viewport.d1;
3361 context->RSSetViewports(1, &v);
3367 r.left = cmd.args.scissor.x;
3368 r.top = cmd.args.scissor.y;
3370 r.right = cmd.args.scissor.x + cmd.args.scissor.w;
3371 r.bottom = cmd.args.scissor.y + cmd.args.scissor.h;
3372 context->RSSetScissorRects(1, &r);
3376 contextState.vsHighestActiveVertexBufferBinding = qMax<
int>(
3377 contextState.vsHighestActiveVertexBufferBinding,
3378 cmd.args.bindVertexBuffers.startSlot + cmd.args.bindVertexBuffers.slotCount - 1);
3379 context->IASetVertexBuffers(UINT(cmd.args.bindVertexBuffers.startSlot),
3380 UINT(cmd.args.bindVertexBuffers.slotCount),
3381 cmd.args.bindVertexBuffers.buffers,
3382 cmd.args.bindVertexBuffers.strides,
3383 cmd.args.bindVertexBuffers.offsets);
3386 contextState.vsHasIndexBufferBound =
true;
3387 context->IASetIndexBuffer(cmd.args.bindIndexBuffer.buffer,
3388 cmd.args.bindIndexBuffer.format,
3389 cmd.args.bindIndexBuffer.offset);
3398 context->IASetPrimitiveTopology(cmd.args.bindGraphicsPipeline.topology);
3399 context->IASetInputLayout(cmd.args.bindGraphicsPipeline.inputLayout);
3400 context->OMSetDepthStencilState(cmd.args.bindGraphicsPipeline.dsState, cmd.args.bindGraphicsPipeline.stencilRef);
3401 context->OMSetBlendState(cmd.args.bindGraphicsPipeline.blendState, blendConstants, 0xffffffff);
3402 context->RSSetState(cmd.args.bindGraphicsPipeline.rastState);
3407 *cbD->resourceBatchRetainPool[cmd.args.bindShaderResources.resourceBatchesIndex]
,
3408 cmd.args.bindShaderResources.dynamicOffsetPairs
,
3409 cmd.args.bindShaderResources.dynamicOffsetCount
,
3410 cmd.args.bindShaderResources.offsetOnlyChange
,
3418 ID3D11Buffer *buf = cmd.args.setPushConstants.buffer;
3419 D3D11_MAPPED_SUBRESOURCE mp;
3420 HRESULT hr = context->Map(buf, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
3421 if (SUCCEEDED(hr)) {
3422 memcpy(mp.pData, cbD->pushConstantPool.constData() + cmd.args.setPushConstants.dataOffset,
3423 cmd.args.setPushConstants.size);
3424 context->Unmap(buf, 0);
3426 qWarning(
"Failed to map push constant buffer: %s",
3427 qPrintable(QSystemError::windowsComString(hr)));
3430 const UINT startSlot = cmd.args.setPushConstants.startSlot;
3431 const uint stages = cmd.args.setPushConstants.stages;
3435 if (stages & (1u << uint(RBM_VERTEX)))
3436 context->VSSetConstantBuffers(startSlot, 1, &buf);
3437 if (stages & (1u << uint(RBM_HULL)))
3438 context->HSSetConstantBuffers(startSlot, 1, &buf);
3439 if (stages & (1u << uint(RBM_DOMAIN)))
3440 context->DSSetConstantBuffers(startSlot, 1, &buf);
3441 if (stages & (1u << uint(RBM_GEOMETRY)))
3442 context->GSSetConstantBuffers(startSlot, 1, &buf);
3443 if (stages & (1u << uint(RBM_FRAGMENT)))
3444 context->PSSetConstantBuffers(startSlot, 1, &buf);
3445 if (stages & (1u << uint(RBM_COMPUTE)))
3446 context->CSSetConstantBuffers(startSlot, 1, &buf);
3449 case QD3D11CommandBuffer::Command::StencilRef:
3450 context->OMSetDepthStencilState(cmd.args.stencilRef.dsState, cmd.args.stencilRef.ref);
3453 memcpy(blendConstants, cmd.args.blendConstants.c, 4 *
sizeof(
float));
3454 context->OMSetBlendState(cmd.args.blendConstants.blendState, blendConstants, 0xffffffff);
3456 case QD3D11CommandBuffer::Command::Draw:
3457 if (cmd.args.draw.instanceCount == 1 && cmd.args.draw.firstInstance == 0)
3458 context->Draw(cmd.args.draw.vertexCount, cmd.args.draw.firstVertex);
3460 context->DrawInstanced(cmd.args.draw.vertexCount, cmd.args.draw.instanceCount,
3461 cmd.args.draw.firstVertex, cmd.args.draw.firstInstance);
3463 case QD3D11CommandBuffer::Command::DrawIndexed:
3464 if (cmd.args.drawIndexed.instanceCount == 1 && cmd.args.drawIndexed.firstInstance == 0)
3465 context->DrawIndexed(cmd.args.drawIndexed.indexCount, cmd.args.drawIndexed.firstIndex,
3466 cmd.args.drawIndexed.vertexOffset);
3468 context->DrawIndexedInstanced(cmd.args.drawIndexed.indexCount, cmd.args.drawIndexed.instanceCount,
3469 cmd.args.drawIndexed.firstIndex, cmd.args.drawIndexed.vertexOffset,
3470 cmd.args.drawIndexed.firstInstance);
3474 UINT alignedByteOffsetForArgs = cmd.args.drawIndirect.indirectBufferOffset;
3475 const UINT stride = cmd.args.drawIndirect.stride;
3476 for (quint32 i = 0; i < cmd.args.drawIndirect.drawCount; ++i) {
3477 context->DrawInstancedIndirect(cmd.args.drawIndirect.indirectBuffer, alignedByteOffsetForArgs);
3478 alignedByteOffsetForArgs += stride;
3484 UINT alignedByteOffsetForArgs = cmd.args.drawIndexedIndirect.indirectBufferOffset;
3485 const UINT stride = cmd.args.drawIndexedIndirect.stride;
3486 for (quint32 i = 0; i < cmd.args.drawIndexedIndirect.drawCount; ++i) {
3487 context->DrawIndexedInstancedIndirect(cmd.args.drawIndexedIndirect.indirectBuffer, alignedByteOffsetForArgs);
3488 alignedByteOffsetForArgs += stride;
3494 if (cmd.args.updateSubRes.dst) {
3495 context->UpdateSubresource(cmd.args.updateSubRes.dst, cmd.args.updateSubRes.dstSubRes,
3496 cmd.args.updateSubRes.hasDstBox ? &cmd.args.updateSubRes.dstBox :
nullptr,
3497 cmd.args.updateSubRes.src, cmd.args.updateSubRes.srcRowPitch, 0);
3500 case QD3D11CommandBuffer::Command::CopySubRes:
3501 context->CopySubresourceRegion(cmd.args.copySubRes.dst, cmd.args.copySubRes.dstSubRes,
3502 cmd.args.copySubRes.dstX, cmd.args.copySubRes.dstY, cmd.args.copySubRes.dstZ,
3503 cmd.args.copySubRes.src, cmd.args.copySubRes.srcSubRes,
3504 cmd.args.copySubRes.hasSrcBox ? &cmd.args.copySubRes.srcBox :
nullptr);
3506 case QD3D11CommandBuffer::Command::ClearUav:
3507 context->ClearUnorderedAccessViewUint(cmd.args.clearUav.uav, cmd.args.clearUav.values);
3509 case QD3D11CommandBuffer::Command::ResolveSubRes:
3510 context->ResolveSubresource(cmd.args.resolveSubRes.dst, cmd.args.resolveSubRes.dstSubRes,
3511 cmd.args.resolveSubRes.src, cmd.args.resolveSubRes.srcSubRes,
3512 cmd.args.resolveSubRes.format);
3514 case QD3D11CommandBuffer::Command::GenMip:
3515 context->GenerateMips(cmd.args.genMip.srv);
3517 case QD3D11CommandBuffer::Command::DebugMarkBegin:
3518 annotations->BeginEvent(
reinterpret_cast<LPCWSTR>(QString::fromLatin1(cmd.args.debugMark.s).utf16()));
3520 case QD3D11CommandBuffer::Command::DebugMarkEnd:
3521 annotations->EndEvent();
3523 case QD3D11CommandBuffer::Command::DebugMarkMsg:
3524 annotations->SetMarker(
reinterpret_cast<LPCWSTR>(QString::fromLatin1(cmd.args.debugMark.s).utf16()));
3526 case QD3D11CommandBuffer::Command::BindComputePipeline:
3527 context->CSSetShader(cmd.args.bindComputePipeline.cs,
nullptr, 0);
3529 case QD3D11CommandBuffer::Command::Dispatch:
3530 context->Dispatch(cmd.args.dispatch.x, cmd.args.dispatch.y, cmd.args.dispatch.z);
3532 case QD3D11CommandBuffer::Command::DispatchIndirect:
3533 context->DispatchIndirect(cmd.args.dispatchIndirect.indirectBuffer,
3534 cmd.args.dispatchIndirect.indirectBufferOffset);
3563 for (
auto it = uavs.begin(), end = uavs.end(); it != end; ++it)
3564 it.value()->Release();
3569 rhiD->unregisterResource(
this);
3575 if (usage.testFlag(QRhiBuffer::VertexBuffer))
3576 u |= D3D11_BIND_VERTEX_BUFFER;
3577 if (usage.testFlag(QRhiBuffer::IndexBuffer))
3578 u |= D3D11_BIND_INDEX_BUFFER;
3579 if (usage.testFlag(QRhiBuffer::UniformBuffer))
3580 u |= D3D11_BIND_CONSTANT_BUFFER;
3581 if (usage.testFlag(QRhiBuffer::StorageBuffer))
3582 u |= D3D11_BIND_UNORDERED_ACCESS;
3591 if (m_usage.testFlag(QRhiBuffer::UniformBuffer) && m_type != Dynamic) {
3592 qWarning(
"UniformBuffer must always be combined with Dynamic on D3D11");
3596 if (m_usage.testFlag(QRhiBuffer::StorageBuffer) && m_type == Dynamic) {
3597 qWarning(
"StorageBuffer cannot be combined with Dynamic");
3601 if (m_usage.testFlag(QRhiBuffer::IndirectBuffer) && m_type == Dynamic) {
3602 qWarning(
"IndirectBuffer cannot be combined with Dynamic on D3D11");
3606 const quint32 nonZeroSize = m_size <= 0 ? 256 : m_size;
3611 const quint32 minSize = m_usage.testFlag(QRhiBuffer::IndirectBuffer) ? 12u : 1u;
3612 const quint32 roundedSize = aligned(qMax(nonZeroSize, minSize),
3613 m_usage.testFlag(QRhiBuffer::UniformBuffer) ? 256u : 4u);
3615 D3D11_BUFFER_DESC desc = {};
3616 desc.ByteWidth = roundedSize;
3617 desc.Usage = m_type == Dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
3618 desc.BindFlags = toD3DBufferUsage(m_usage);
3619 desc.CPUAccessFlags = m_type == Dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
3620 desc.MiscFlags = m_usage.testFlag(QRhiBuffer::StorageBuffer) ? D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS : 0;
3621 if (m_usage.testFlag(QRhiBuffer::IndirectBuffer))
3622 desc.MiscFlags |= D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS;
3625 HRESULT hr = rhiD->dev->CreateBuffer(&desc,
nullptr, &buffer);
3627 qWarning(
"Failed to create buffer: %s",
3628 qPrintable(QSystemError::windowsComString(hr)));
3632 if (m_type == Dynamic) {
3633 dynBuf =
new char[nonZeroSize];
3637 if (!m_objectName.isEmpty())
3638 buffer->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData());
3641 rhiD->registerResource(
this);
3647 if (m_type == Dynamic) {
3651 return { { &buffer }, 1 };
3662 Q_ASSERT(m_type == Dynamic);
3663 D3D11_MAPPED_SUBRESOURCE mp;
3665 HRESULT hr = rhiD->context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
3667 qWarning(
"Failed to map buffer: %s",
3668 qPrintable(QSystemError::windowsComString(hr)));
3671 return static_cast<
char *>(mp.pData);
3677 rhiD->context->Unmap(buffer, 0);
3682 auto it = uavs.find(offset);
3683 if (it != uavs.end())
3687 D3D11_UNORDERED_ACCESS_VIEW_DESC desc = {};
3688 desc.Format = DXGI_FORMAT_R32_TYPELESS;
3689 desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
3690 desc.Buffer.FirstElement = offset / 4u;
3691 desc.Buffer.NumElements = aligned(m_size - offset, 4u) / 4u;
3692 desc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW;
3695 ID3D11UnorderedAccessView *uav =
nullptr;
3696 HRESULT hr = rhiD->dev->CreateUnorderedAccessView(buffer, &desc, &uav);
3698 qWarning(
"Failed to create UAV: %s",
3699 qPrintable(QSystemError::windowsComString(hr)));
3712 D3D11_UNORDERED_ACCESS_VIEW_DESC desc = {};
3713 desc.Format = DXGI_FORMAT_R32_UINT;
3714 desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
3715 desc.Buffer.FirstElement = offset / 4u;
3716 desc.Buffer.NumElements = size / 4u;
3719 ID3D11UnorderedAccessView *uav =
nullptr;
3720 HRESULT hr = rhiD->dev->CreateUnorderedAccessView(buffer, &desc, &uav);
3722 qWarning(
"Failed to create UAV: %s",
3723 qPrintable(QSystemError::windowsComString(hr)));
3731 int sampleCount, QRhiRenderBuffer::Flags flags,
3732 QRhiTexture::Format backingFormatHint)
3762 rhiD->unregisterResource(
this);
3770 if (m_pixelSize.isEmpty())
3774 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount);
3776 D3D11_TEXTURE2D_DESC desc = {};
3777 desc.Width = UINT(m_pixelSize.width());
3778 desc.Height = UINT(m_pixelSize.height());
3781 desc.SampleDesc = sampleDesc;
3782 desc.Usage = D3D11_USAGE_DEFAULT;
3784 if (m_type == Color) {
3785 dxgiFormat = m_backingFormatHint == QRhiTexture::UnknownFormat ? DXGI_FORMAT_R8G8B8A8_UNORM
3786 : toD3DTextureFormat(m_backingFormatHint, {});
3787 desc.Format = dxgiFormat;
3788 desc.BindFlags = D3D11_BIND_RENDER_TARGET;
3789 HRESULT hr = rhiD->dev->CreateTexture2D(&desc,
nullptr, &tex);
3791 qWarning(
"Failed to create color renderbuffer: %s",
3792 qPrintable(QSystemError::windowsComString(hr)));
3795 D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
3796 rtvDesc.Format = dxgiFormat;
3797 rtvDesc.ViewDimension = desc.SampleDesc.Count > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS
3798 : D3D11_RTV_DIMENSION_TEXTURE2D;
3799 hr = rhiD->dev->CreateRenderTargetView(tex, &rtvDesc, &rtv);
3801 qWarning(
"Failed to create rtv: %s",
3802 qPrintable(QSystemError::windowsComString(hr)));
3805 }
else if (m_type == DepthStencil) {
3806 dxgiFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
3807 desc.Format = dxgiFormat;
3808 desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
3809 HRESULT hr = rhiD->dev->CreateTexture2D(&desc,
nullptr, &tex);
3811 qWarning(
"Failed to create depth-stencil buffer: %s",
3812 qPrintable(QSystemError::windowsComString(hr)));
3815 D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
3816 dsvDesc.Format = dxgiFormat;
3817 dsvDesc.ViewDimension = desc.SampleDesc.Count > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS
3818 : D3D11_DSV_DIMENSION_TEXTURE2D;
3819 hr = rhiD->dev->CreateDepthStencilView(tex, &dsvDesc, &dsv);
3821 qWarning(
"Failed to create dsv: %s",
3822 qPrintable(QSystemError::windowsComString(hr)));
3829 if (!m_objectName.isEmpty())
3830 tex->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData());
3833 rhiD->registerResource(
this);
3839 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
3840 return m_backingFormatHint;
3842 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
3846 int arraySize,
int sampleCount, Flags flags)
3849 for (
int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i)
3850 perLevelViews[i] =
nullptr;
3860 if (!tex && !tex3D && !tex1D)
3868 for (
int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i) {
3869 if (perLevelViews[i]) {
3870 perLevelViews[i]->Release();
3871 perLevelViews[i] =
nullptr;
3890 rhiD->unregisterResource(
this);
3896 case QRhiTexture::Format::D16:
3897 return DXGI_FORMAT_R16_UNORM;
3898 case QRhiTexture::Format::D24:
3899 return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
3900 case QRhiTexture::Format::D24S8:
3901 return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
3902 case QRhiTexture::Format::D32F:
3903 return DXGI_FORMAT_R32_FLOAT;
3904 case QRhiTexture::Format::D32FS8:
3905 return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
3908 return DXGI_FORMAT_R32_FLOAT;
3915 case QRhiTexture::Format::D16:
3916 return DXGI_FORMAT_D16_UNORM;
3917 case QRhiTexture::Format::D24:
3918 return DXGI_FORMAT_D24_UNORM_S8_UINT;
3919 case QRhiTexture::Format::D24S8:
3920 return DXGI_FORMAT_D24_UNORM_S8_UINT;
3921 case QRhiTexture::Format::D32F:
3922 return DXGI_FORMAT_D32_FLOAT;
3923 case QRhiTexture::Format::D32FS8:
3924 return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
3927 return DXGI_FORMAT_D32_FLOAT;
3933 if (tex || tex3D || tex1D)
3937 if (!rhiD->isTextureFormatSupported(m_format, m_flags))
3940 const bool isDepth = isDepthTextureFormat(m_format);
3941 const bool isCube = m_flags.testFlag(CubeMap);
3942 const bool is3D = m_flags.testFlag(ThreeDimensional);
3943 const bool isArray = m_flags.testFlag(TextureArray);
3944 const bool hasMipMaps = m_flags.testFlag(MipMapped);
3945 const bool is1D = m_flags.testFlag(OneDimensional);
3947 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
3948 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
3950 dxgiFormat = toD3DTextureFormat(m_format, m_flags);
3951 mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1);
3952 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount);
3953 if (sampleDesc.Count > 1) {
3955 qWarning(
"Cubemap texture cannot be multisample");
3959 qWarning(
"3D texture cannot be multisample");
3963 qWarning(
"Multisample texture cannot have mipmaps");
3967 if (isDepth && hasMipMaps) {
3968 qWarning(
"Depth texture cannot have mipmaps");
3971 if (isCube && is3D) {
3972 qWarning(
"Texture cannot be both cube and 3D");
3975 if (isArray && is3D) {
3976 qWarning(
"Texture cannot be both array and 3D");
3979 if (isCube && is1D) {
3980 qWarning(
"Texture cannot be both cube and 1D");
3984 qWarning(
"Texture cannot be both 1D and 3D");
3987 if (m_depth > 1 && !is3D) {
3988 qWarning(
"Texture cannot have a depth of %d when it is not 3D", m_depth);
3991 if (m_arraySize > 0 && !isArray) {
3992 qWarning(
"Texture cannot have an array size of %d when it is not an array", m_arraySize);
3995 if (m_arraySize < 1 && isArray) {
3996 qWarning(
"Texture is an array but array size is %d", m_arraySize);
4000 if (!rhiD->textureFormatInfo(m_format, size,
nullptr,
nullptr,
nullptr))
4004 *adjustedSize = size;
4012 const bool isDepth = isDepthTextureFormat(m_format);
4013 const bool isCube = m_flags.testFlag(CubeMap);
4014 const bool is3D = m_flags.testFlag(ThreeDimensional);
4015 const bool isArray = m_flags.testFlag(TextureArray);
4016 const bool is1D = m_flags.testFlag(OneDimensional);
4018 D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
4019 srvDesc.Format = isDepth ? toD3DDepthTextureSRVFormat(m_format) : dxgiFormat;
4021 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
4026 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY;
4028 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
4029 srvDesc.Texture1DArray.FirstArraySlice = UINT(m_arrayRangeStart);
4030 srvDesc.Texture1DArray.ArraySize = UINT(m_arrayRangeLength);
4032 srvDesc.Texture1DArray.FirstArraySlice = 0;
4033 srvDesc.Texture1DArray.ArraySize = UINT(qMax(0, m_arraySize));
4036 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D;
4039 }
else if (isArray) {
4040 if (sampleDesc.Count > 1) {
4041 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY;
4042 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
4043 srvDesc.Texture2DMSArray.FirstArraySlice = UINT(m_arrayRangeStart);
4044 srvDesc.Texture2DMSArray.ArraySize = UINT(m_arrayRangeLength);
4046 srvDesc.Texture2DMSArray.FirstArraySlice = 0;
4047 srvDesc.Texture2DMSArray.ArraySize = UINT(qMax(0, m_arraySize));
4050 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
4052 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
4053 srvDesc.Texture2DArray.FirstArraySlice = UINT(m_arrayRangeStart);
4054 srvDesc.Texture2DArray.ArraySize = UINT(m_arrayRangeLength);
4056 srvDesc.Texture2DArray.FirstArraySlice = 0;
4057 srvDesc.Texture2DArray.ArraySize = UINT(qMax(0, m_arraySize));
4061 if (sampleDesc.Count > 1) {
4062 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS;
4064 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
4067 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
4073 HRESULT hr = rhiD->dev->CreateShaderResourceView(textureResource(), &srvDesc, &srv);
4075 qWarning(
"Failed to create srv: %s",
4076 qPrintable(QSystemError::windowsComString(hr)));
4087 if (!prepareCreate(&size))
4090 const bool isDepth = isDepthTextureFormat(m_format);
4091 const bool isCube = m_flags.testFlag(CubeMap);
4092 const bool is3D = m_flags.testFlag(ThreeDimensional);
4093 const bool isArray = m_flags.testFlag(TextureArray);
4094 const bool is1D = m_flags.testFlag(OneDimensional);
4096 uint bindFlags = D3D11_BIND_SHADER_RESOURCE;
4097 uint miscFlags = isCube ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
4098 if (m_flags.testFlag(RenderTarget)) {
4100 bindFlags |= D3D11_BIND_DEPTH_STENCIL;
4102 bindFlags |= D3D11_BIND_RENDER_TARGET;
4104 if (m_flags.testFlag(UsedWithGenerateMips)) {
4106 qWarning(
"Depth texture cannot have mipmaps generated");
4109 bindFlags |= D3D11_BIND_RENDER_TARGET;
4110 miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
4112 if (m_flags.testFlag(UsedWithLoadStore))
4113 bindFlags |= D3D11_BIND_UNORDERED_ACCESS;
4117 D3D11_TEXTURE1D_DESC desc = {};
4118 desc.Width = UINT(size.width());
4120 desc.ArraySize = isArray ? UINT(qMax(0, m_arraySize)) : 1;
4121 desc.Format = dxgiFormat;
4122 desc.Usage = D3D11_USAGE_DEFAULT;
4123 desc.BindFlags = bindFlags;
4124 desc.MiscFlags = miscFlags;
4126 HRESULT hr = rhiD->dev->CreateTexture1D(&desc,
nullptr, &tex1D);
4128 qWarning(
"Failed to create 1D texture: %s",
4129 qPrintable(QSystemError::windowsComString(hr)));
4132 if (!m_objectName.isEmpty())
4133 tex1D->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()),
4134 m_objectName.constData());
4136 D3D11_TEXTURE2D_DESC desc = {};
4137 desc.Width = UINT(size.width());
4138 desc.Height = UINT(size.height());
4140 desc.ArraySize = isCube ? 6 : (isArray ? UINT(qMax(0, m_arraySize)) : 1);
4141 desc.Format = dxgiFormat;
4142 desc.SampleDesc = sampleDesc;
4143 desc.Usage = D3D11_USAGE_DEFAULT;
4144 desc.BindFlags = bindFlags;
4145 desc.MiscFlags = miscFlags;
4147 HRESULT hr = rhiD->dev->CreateTexture2D(&desc,
nullptr, &tex);
4149 qWarning(
"Failed to create 2D texture: %s",
4150 qPrintable(QSystemError::windowsComString(hr)));
4151 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
4155 if (!m_objectName.isEmpty())
4156 tex->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData());
4158 D3D11_TEXTURE3D_DESC desc = {};
4159 desc.Width = UINT(size.width());
4160 desc.Height = UINT(size.height());
4161 desc.Depth = UINT(qMax(1, m_depth));
4163 desc.Format = dxgiFormat;
4164 desc.Usage = D3D11_USAGE_DEFAULT;
4165 desc.BindFlags = bindFlags;
4166 desc.MiscFlags = miscFlags;
4168 HRESULT hr = rhiD->dev->CreateTexture3D(&desc,
nullptr, &tex3D);
4170 qWarning(
"Failed to create 3D texture: %s",
4171 qPrintable(QSystemError::windowsComString(hr)));
4172 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
4176 if (!m_objectName.isEmpty())
4177 tex3D->SetPrivateData(WKPDID_D3DDebugObjectName, UINT(m_objectName.size()), m_objectName.constData());
4184 rhiD->registerResource(
this);
4193 if (!prepareCreate())
4196 if (m_flags.testFlag(ThreeDimensional))
4197 tex3D =
reinterpret_cast<ID3D11Texture3D *>(src.object);
4198 else if (m_flags.testFlags(OneDimensional))
4199 tex1D =
reinterpret_cast<ID3D11Texture1D *>(src.object);
4201 tex =
reinterpret_cast<ID3D11Texture2D *>(src.object);
4208 rhiD->registerResource(
this);
4214 return { quint64(textureResource()), 0 };
4219 if (perLevelViews[level])
4220 return perLevelViews[level];
4222 const bool isCube = m_flags.testFlag(CubeMap);
4223 const bool isArray = m_flags.testFlag(TextureArray);
4224 const bool is3D = m_flags.testFlag(ThreeDimensional);
4225 const bool is1D = m_flags.testFlag(OneDimensional);
4226 D3D11_UNORDERED_ACCESS_VIEW_DESC desc = {};
4227 desc.Format = dxgiFormat;
4229 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY;
4230 desc.Texture2DArray.MipSlice = UINT(level);
4231 desc.Texture2DArray.FirstArraySlice = 0;
4232 desc.Texture2DArray.ArraySize = 6;
4233 }
else if (is1D && isArray) {
4234 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE1DARRAY;
4235 desc.Texture1DArray.MipSlice = UINT(level);
4236 desc.Texture1DArray.FirstArraySlice = 0;
4237 desc.Texture1DArray.ArraySize = UINT(qMax(0, m_arraySize));
4239 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE1D;
4240 desc.Texture1D.MipSlice = UINT(level);
4241 }
else if (isArray) {
4242 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY;
4243 desc.Texture2DArray.MipSlice = UINT(level);
4244 desc.Texture2DArray.FirstArraySlice = 0;
4245 desc.Texture2DArray.ArraySize = UINT(qMax(0, m_arraySize));
4247 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE3D;
4248 desc.Texture3D.MipSlice = UINT(level);
4249 desc.Texture3D.WSize = UINT(m_depth);
4251 desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
4252 desc.Texture2D.MipSlice = UINT(level);
4256 ID3D11UnorderedAccessView *uav =
nullptr;
4257 HRESULT hr = rhiD->dev->CreateUnorderedAccessView(textureResource(), &desc, &uav);
4259 qWarning(
"Failed to create UAV: %s",
4260 qPrintable(QSystemError::windowsComString(hr)));
4264 perLevelViews[level] = uav;
4269 AddressMode u, AddressMode v, AddressMode w)
4284 samplerState->Release();
4285 samplerState =
nullptr;
4289 rhiD->unregisterResource(
this);
4292static inline D3D11_FILTER toD3DFilter(QRhiSampler::Filter minFilter, QRhiSampler::Filter magFilter, QRhiSampler::Filter mipFilter)
4294 if (minFilter == QRhiSampler::Nearest) {
4295 if (magFilter == QRhiSampler::Nearest) {
4296 if (mipFilter == QRhiSampler::Linear)
4297 return D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR;
4299 return D3D11_FILTER_MIN_MAG_MIP_POINT;
4301 if (mipFilter == QRhiSampler::Linear)
4302 return D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR;
4304 return D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
4307 if (magFilter == QRhiSampler::Nearest) {
4308 if (mipFilter == QRhiSampler::Linear)
4309 return D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
4311 return D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT;
4313 if (mipFilter == QRhiSampler::Linear)
4314 return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
4316 return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
4321 return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
4327 case QRhiSampler::Repeat:
4328 return D3D11_TEXTURE_ADDRESS_WRAP;
4329 case QRhiSampler::ClampToEdge:
4330 return D3D11_TEXTURE_ADDRESS_CLAMP;
4331 case QRhiSampler::Mirror:
4332 return D3D11_TEXTURE_ADDRESS_MIRROR;
4335 return D3D11_TEXTURE_ADDRESS_CLAMP;
4342 case QRhiSampler::Never:
4343 return D3D11_COMPARISON_NEVER;
4344 case QRhiSampler::Less:
4345 return D3D11_COMPARISON_LESS;
4346 case QRhiSampler::Equal:
4347 return D3D11_COMPARISON_EQUAL;
4348 case QRhiSampler::LessOrEqual:
4349 return D3D11_COMPARISON_LESS_EQUAL;
4350 case QRhiSampler::Greater:
4351 return D3D11_COMPARISON_GREATER;
4352 case QRhiSampler::NotEqual:
4353 return D3D11_COMPARISON_NOT_EQUAL;
4354 case QRhiSampler::GreaterOrEqual:
4355 return D3D11_COMPARISON_GREATER_EQUAL;
4356 case QRhiSampler::Always:
4357 return D3D11_COMPARISON_ALWAYS;
4360 return D3D11_COMPARISON_NEVER;
4369 D3D11_SAMPLER_DESC desc = {};
4370 desc.Filter = toD3DFilter(m_minFilter, m_magFilter, m_mipmapMode);
4371 if (m_compareOp != Never)
4372 desc.Filter = D3D11_FILTER(desc.Filter | 0x80);
4373 desc.AddressU = toD3DAddressMode(m_addressU);
4374 desc.AddressV = toD3DAddressMode(m_addressV);
4375 desc.AddressW = toD3DAddressMode(m_addressW);
4376 desc.MaxAnisotropy = 1.0f;
4377 desc.ComparisonFunc = toD3DTextureComparisonFunc(m_compareOp);
4378 desc.MaxLOD = m_mipmapMode == None ? 0.0f : 1000.0f;
4381 HRESULT hr = rhiD->dev->CreateSamplerState(&desc, &samplerState);
4383 qWarning(
"Failed to create sampler state: %s",
4384 qPrintable(QSystemError::windowsComString(hr)));
4389 rhiD->registerResource(
this);
4408 rhiD->unregisterResource(
this);
4421 rhiD->registerResource(rpD,
false);
4458 return d.sampleCount;
4462 const QRhiTextureRenderTargetDescription &desc,
4480 if (!rtv[0] && !dsv)
4499 rhiD->unregisterResource(
this);
4506 rhiD->registerResource(rpD,
false);
4515 Q_ASSERT(m_desc.colorAttachmentCount() > 0 || m_desc.depthTexture());
4516 Q_ASSERT(!m_desc.depthStencilBuffer() || !m_desc.depthTexture());
4517 const bool hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
4521 int colorAttCount = 0;
4523 for (
auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
4525 const QRhiColorAttachment &colorAtt(*it);
4526 QRhiTexture *texture = colorAtt.texture();
4527 QRhiRenderBuffer *rb = colorAtt.renderBuffer();
4528 Q_ASSERT(texture || rb);
4531 D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
4532 rtvDesc.Format = toD3DTextureFormat(texD->format(), texD->flags());
4533 if (texD->flags().testFlag(QRhiTexture::CubeMap)) {
4534 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
4535 rtvDesc.Texture2DArray.MipSlice = UINT(colorAtt.level());
4536 rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAtt.layer());
4537 rtvDesc.Texture2DArray.ArraySize = 1;
4538 }
else if (texD->flags().testFlag(QRhiTexture::OneDimensional)) {
4539 if (texD->flags().testFlag(QRhiTexture::TextureArray)) {
4540 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1DARRAY;
4541 rtvDesc.Texture1DArray.MipSlice = UINT(colorAtt.level());
4542 rtvDesc.Texture1DArray.FirstArraySlice = UINT(colorAtt.layer());
4543 rtvDesc.Texture1DArray.ArraySize = 1;
4545 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D;
4546 rtvDesc.Texture1D.MipSlice = UINT(colorAtt.level());
4548 }
else if (texD->flags().testFlag(QRhiTexture::TextureArray)) {
4549 if (texD->sampleDesc.Count > 1) {
4550 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
4551 rtvDesc.Texture2DMSArray.FirstArraySlice = UINT(colorAtt.layer());
4552 rtvDesc.Texture2DMSArray.ArraySize = 1;
4554 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
4555 rtvDesc.Texture2DArray.MipSlice = UINT(colorAtt.level());
4556 rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAtt.layer());
4557 rtvDesc.Texture2DArray.ArraySize = 1;
4559 }
else if (texD->flags().testFlag(QRhiTexture::ThreeDimensional)) {
4560 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
4561 rtvDesc.Texture3D.MipSlice = UINT(colorAtt.level());
4562 rtvDesc.Texture3D.FirstWSlice = UINT(colorAtt.layer());
4563 rtvDesc.Texture3D.WSize = 1;
4565 if (texD->sampleDesc.Count > 1) {
4566 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
4568 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
4569 rtvDesc.Texture2D.MipSlice = UINT(colorAtt.level());
4572 HRESULT hr = rhiD->dev->CreateRenderTargetView(texD->textureResource(), &rtvDesc, &rtv[attIndex]);
4574 qWarning(
"Failed to create rtv: %s",
4575 qPrintable(QSystemError::windowsComString(hr)));
4579 if (attIndex == 0) {
4580 d.pixelSize = rhiD->q->sizeForMipLevel(colorAtt.level(), texD->pixelSize());
4581 d.sampleCount =
int(texD->sampleDesc.Count);
4586 rtv[attIndex] = rbD->rtv;
4587 if (attIndex == 0) {
4588 d.pixelSize = rbD->pixelSize();
4589 d.sampleCount =
int(rbD->sampleDesc.Count);
4595 if (hasDepthStencil) {
4596 if (m_desc.depthTexture()) {
4599 D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
4600 dsvDesc.Format = toD3DDepthTextureDSVFormat(depthTexD->format());
4601 const bool isMultisample = depthTexD->sampleDesc.Count > 1;
4602 if (depthTexD->flags().testFlag(QRhiTexture::TextureArray)) {
4603 if (isMultisample) {
4604 dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY;
4605 if (m_desc.depthLayer() >= 0) {
4606 dsvDesc.Texture2DMSArray.FirstArraySlice = UINT(m_desc.depthLayer());
4607 dsvDesc.Texture2DMSArray.ArraySize = 1;
4608 }
else if (depthTexD->arrayRangeStart() >= 0 && depthTexD->arrayRangeLength() >= 0) {
4609 dsvDesc.Texture2DMSArray.FirstArraySlice = UINT(depthTexD->arrayRangeStart());
4610 dsvDesc.Texture2DMSArray.ArraySize = UINT(depthTexD->arrayRangeLength());
4612 dsvDesc.Texture2DMSArray.FirstArraySlice = 0;
4613 dsvDesc.Texture2DMSArray.ArraySize = UINT(qMax(0, depthTexD->arraySize()));
4616 dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
4617 if (m_desc.depthLayer() >= 0) {
4618 dsvDesc.Texture2DArray.FirstArraySlice = UINT(m_desc.depthLayer());
4619 dsvDesc.Texture2DArray.ArraySize = 1;
4620 }
else if (depthTexD->arrayRangeStart() >= 0 && depthTexD->arrayRangeLength() >= 0) {
4621 dsvDesc.Texture2DArray.FirstArraySlice = UINT(depthTexD->arrayRangeStart());
4622 dsvDesc.Texture2DArray.ArraySize = UINT(depthTexD->arrayRangeLength());
4624 dsvDesc.Texture2DArray.FirstArraySlice = 0;
4625 dsvDesc.Texture2DArray.ArraySize = UINT(qMax(0, depthTexD->arraySize()));
4630 dsvDesc.ViewDimension = isMultisample ? D3D11_DSV_DIMENSION_TEXTURE2DMS
4631 : D3D11_DSV_DIMENSION_TEXTURE2D;
4633 HRESULT hr = rhiD->dev->CreateDepthStencilView(depthTexD->tex, &dsvDesc, &dsv);
4635 qWarning(
"Failed to create dsv: %s",
4636 qPrintable(QSystemError::windowsComString(hr)));
4639 if (colorAttCount == 0) {
4640 d.pixelSize = depthTexD->pixelSize();
4641 d.sampleCount =
int(depthTexD->sampleDesc.Count);
4646 dsv = depthRbD->dsv;
4647 if (colorAttCount == 0) {
4648 d.pixelSize = m_desc.depthStencilBuffer()->pixelSize();
4649 d.sampleCount =
int(depthRbD->sampleDesc.Count);
4656 d.views.setFrom(colorAttCount, rtv, dsv);
4658 d.rp =
QRHI_RES(QD3D11RenderPassDescriptor, m_renderPassDesc);
4660 QRhiRenderTargetAttachmentTracker::updateResIdList<QD3D11Texture, QD3D11RenderBuffer>(m_desc, &d.currentResIdList);
4662 rhiD->registerResource(
this);
4668 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QD3D11Texture, QD3D11RenderBuffer>(m_desc, d.currentResIdList))
4681 return d.sampleCount;
4696 sortedBindings.clear();
4697 boundResourceData.clear();
4701 rhiD->unregisterResource(
this);
4706 if (!sortedBindings.isEmpty())
4710 if (!rhiD->sanityCheckShaderResourceBindings(
this))
4713 rhiD->updateLayoutDesc(
this);
4715 std::copy(m_bindings.cbegin(), m_bindings.cend(),
std::back_inserter(sortedBindings));
4716 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
4718 boundResourceData.resize(sortedBindings.count());
4720 for (BoundResourceData &bd : boundResourceData)
4724 for (
const QRhiShaderResourceBinding &b : sortedBindings) {
4725 const QRhiShaderResourceBinding::Data *bd = QRhiImplementation::shaderResourceBindingData(b);
4726 if (bd->type() == QRhiShaderResourceBinding::UniformBuffer && bd->ubuf().hasDynamicOffset) {
4727 hasDynamicOffset =
true;
4733 rhiD->registerResource(
this,
false);
4739 sortedBindings.clear();
4740 std::copy(m_bindings.cbegin(), m_bindings.cend(),
std::back_inserter(sortedBindings));
4741 if (!flags.testFlag(BindingsAreSorted))
4742 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
4744 Q_ASSERT(boundResourceData.count() == sortedBindings.count());
4745 for (BoundResourceData &bd : boundResourceData)
4765 s.shader->Release();
4768 s.nativeResourceBindingMap.clear();
4780 blendState->Release();
4781 blendState =
nullptr;
4785 inputLayout->Release();
4786 inputLayout =
nullptr;
4790 rastState->Release();
4791 rastState =
nullptr;
4794 releasePipelineShader(vs);
4795 releasePipelineShader(hs);
4796 releasePipelineShader(ds);
4797 releasePipelineShader(gs);
4798 releasePipelineShader(fs);
4804 rhiD->unregisterResource(
this);
4810 case QRhiGraphicsPipeline::None:
4811 return D3D11_CULL_NONE;
4812 case QRhiGraphicsPipeline::Front:
4813 return D3D11_CULL_FRONT;
4814 case QRhiGraphicsPipeline::Back:
4815 return D3D11_CULL_BACK;
4818 return D3D11_CULL_NONE;
4825 case QRhiGraphicsPipeline::Fill:
4826 return D3D11_FILL_SOLID;
4827 case QRhiGraphicsPipeline::Line:
4828 return D3D11_FILL_WIREFRAME;
4831 return D3D11_FILL_SOLID;
4838 case QRhiGraphicsPipeline::Never:
4839 return D3D11_COMPARISON_NEVER;
4840 case QRhiGraphicsPipeline::Less:
4841 return D3D11_COMPARISON_LESS;
4842 case QRhiGraphicsPipeline::Equal:
4843 return D3D11_COMPARISON_EQUAL;
4844 case QRhiGraphicsPipeline::LessOrEqual:
4845 return D3D11_COMPARISON_LESS_EQUAL;
4846 case QRhiGraphicsPipeline::Greater:
4847 return D3D11_COMPARISON_GREATER;
4848 case QRhiGraphicsPipeline::NotEqual:
4849 return D3D11_COMPARISON_NOT_EQUAL;
4850 case QRhiGraphicsPipeline::GreaterOrEqual:
4851 return D3D11_COMPARISON_GREATER_EQUAL;
4852 case QRhiGraphicsPipeline::Always:
4853 return D3D11_COMPARISON_ALWAYS;
4856 return D3D11_COMPARISON_ALWAYS;
4863 case QRhiGraphicsPipeline::StencilZero:
4864 return D3D11_STENCIL_OP_ZERO;
4865 case QRhiGraphicsPipeline::Keep:
4866 return D3D11_STENCIL_OP_KEEP;
4867 case QRhiGraphicsPipeline::Replace:
4868 return D3D11_STENCIL_OP_REPLACE;
4869 case QRhiGraphicsPipeline::IncrementAndClamp:
4870 return D3D11_STENCIL_OP_INCR_SAT;
4871 case QRhiGraphicsPipeline::DecrementAndClamp:
4872 return D3D11_STENCIL_OP_DECR_SAT;
4873 case QRhiGraphicsPipeline::Invert:
4874 return D3D11_STENCIL_OP_INVERT;
4875 case QRhiGraphicsPipeline::IncrementAndWrap:
4876 return D3D11_STENCIL_OP_INCR;
4877 case QRhiGraphicsPipeline::DecrementAndWrap:
4878 return D3D11_STENCIL_OP_DECR;
4881 return D3D11_STENCIL_OP_KEEP;
4888 case QRhiVertexInputAttribute::Float4:
4889 return DXGI_FORMAT_R32G32B32A32_FLOAT;
4890 case QRhiVertexInputAttribute::Float3:
4891 return DXGI_FORMAT_R32G32B32_FLOAT;
4892 case QRhiVertexInputAttribute::Float2:
4893 return DXGI_FORMAT_R32G32_FLOAT;
4894 case QRhiVertexInputAttribute::Float:
4895 return DXGI_FORMAT_R32_FLOAT;
4896 case QRhiVertexInputAttribute::UNormByte4:
4897 return DXGI_FORMAT_R8G8B8A8_UNORM;
4898 case QRhiVertexInputAttribute::UNormByte2:
4899 return DXGI_FORMAT_R8G8_UNORM;
4900 case QRhiVertexInputAttribute::UNormByte:
4901 return DXGI_FORMAT_R8_UNORM;
4902 case QRhiVertexInputAttribute::UInt4:
4903 return DXGI_FORMAT_R32G32B32A32_UINT;
4904 case QRhiVertexInputAttribute::UInt3:
4905 return DXGI_FORMAT_R32G32B32_UINT;
4906 case QRhiVertexInputAttribute::UInt2:
4907 return DXGI_FORMAT_R32G32_UINT;
4908 case QRhiVertexInputAttribute::UInt:
4909 return DXGI_FORMAT_R32_UINT;
4910 case QRhiVertexInputAttribute::SInt4:
4911 return DXGI_FORMAT_R32G32B32A32_SINT;
4912 case QRhiVertexInputAttribute::SInt3:
4913 return DXGI_FORMAT_R32G32B32_SINT;
4914 case QRhiVertexInputAttribute::SInt2:
4915 return DXGI_FORMAT_R32G32_SINT;
4916 case QRhiVertexInputAttribute::SInt:
4917 return DXGI_FORMAT_R32_SINT;
4918 case QRhiVertexInputAttribute::Half4:
4920 case QRhiVertexInputAttribute::Half3:
4921 return DXGI_FORMAT_R16G16B16A16_FLOAT;
4922 case QRhiVertexInputAttribute::Half2:
4923 return DXGI_FORMAT_R16G16_FLOAT;
4924 case QRhiVertexInputAttribute::Half:
4925 return DXGI_FORMAT_R16_FLOAT;
4926 case QRhiVertexInputAttribute::UShort4:
4928 case QRhiVertexInputAttribute::UShort3:
4929 return DXGI_FORMAT_R16G16B16A16_UINT;
4930 case QRhiVertexInputAttribute::UShort2:
4931 return DXGI_FORMAT_R16G16_UINT;
4932 case QRhiVertexInputAttribute::UShort:
4933 return DXGI_FORMAT_R16_UINT;
4934 case QRhiVertexInputAttribute::SShort4:
4936 case QRhiVertexInputAttribute::SShort3:
4937 return DXGI_FORMAT_R16G16B16A16_SINT;
4938 case QRhiVertexInputAttribute::SShort2:
4939 return DXGI_FORMAT_R16G16_SINT;
4940 case QRhiVertexInputAttribute::SShort:
4941 return DXGI_FORMAT_R16_SINT;
4944 return DXGI_FORMAT_R32G32B32A32_FLOAT;
4951 case QRhiGraphicsPipeline::Triangles:
4952 return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
4953 case QRhiGraphicsPipeline::TriangleStrip:
4954 return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
4955 case QRhiGraphicsPipeline::Lines:
4956 return D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
4957 case QRhiGraphicsPipeline::LineStrip:
4958 return D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
4959 case QRhiGraphicsPipeline::Points:
4960 return D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
4961 case QRhiGraphicsPipeline::Patches:
4962 Q_ASSERT(patchControlPointCount >= 1 && patchControlPointCount <= 32);
4963 return D3D11_PRIMITIVE_TOPOLOGY(D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST + (patchControlPointCount - 1));
4966 return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
4973 if (c.testFlag(QRhiGraphicsPipeline::R))
4974 f |= D3D11_COLOR_WRITE_ENABLE_RED;
4975 if (c.testFlag(QRhiGraphicsPipeline::G))
4976 f |= D3D11_COLOR_WRITE_ENABLE_GREEN;
4977 if (c.testFlag(QRhiGraphicsPipeline::B))
4978 f |= D3D11_COLOR_WRITE_ENABLE_BLUE;
4979 if (c.testFlag(QRhiGraphicsPipeline::A))
4980 f |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
4993 case QRhiGraphicsPipeline::Zero:
4994 return D3D11_BLEND_ZERO;
4995 case QRhiGraphicsPipeline::One:
4996 return D3D11_BLEND_ONE;
4997 case QRhiGraphicsPipeline::SrcColor:
4998 return rgb ? D3D11_BLEND_SRC_COLOR : D3D11_BLEND_SRC_ALPHA;
4999 case QRhiGraphicsPipeline::OneMinusSrcColor:
5000 return rgb ? D3D11_BLEND_INV_SRC_COLOR : D3D11_BLEND_INV_SRC_ALPHA;
5001 case QRhiGraphicsPipeline::DstColor:
5002 return rgb ? D3D11_BLEND_DEST_COLOR : D3D11_BLEND_DEST_ALPHA;
5003 case QRhiGraphicsPipeline::OneMinusDstColor:
5004 return rgb ? D3D11_BLEND_INV_DEST_COLOR : D3D11_BLEND_INV_DEST_ALPHA;
5005 case QRhiGraphicsPipeline::SrcAlpha:
5006 return D3D11_BLEND_SRC_ALPHA;
5007 case QRhiGraphicsPipeline::OneMinusSrcAlpha:
5008 return D3D11_BLEND_INV_SRC_ALPHA;
5009 case QRhiGraphicsPipeline::DstAlpha:
5010 return D3D11_BLEND_DEST_ALPHA;
5011 case QRhiGraphicsPipeline::OneMinusDstAlpha:
5012 return D3D11_BLEND_INV_DEST_ALPHA;
5013 case QRhiGraphicsPipeline::ConstantColor:
5014 case QRhiGraphicsPipeline::ConstantAlpha:
5015 return D3D11_BLEND_BLEND_FACTOR;
5016 case QRhiGraphicsPipeline::OneMinusConstantColor:
5017 case QRhiGraphicsPipeline::OneMinusConstantAlpha:
5018 return D3D11_BLEND_INV_BLEND_FACTOR;
5019 case QRhiGraphicsPipeline::SrcAlphaSaturate:
5020 return D3D11_BLEND_SRC_ALPHA_SAT;
5021 case QRhiGraphicsPipeline::Src1Color:
5022 return rgb ? D3D11_BLEND_SRC1_COLOR : D3D11_BLEND_SRC1_ALPHA;
5023 case QRhiGraphicsPipeline::OneMinusSrc1Color:
5024 return rgb ? D3D11_BLEND_INV_SRC1_COLOR : D3D11_BLEND_INV_SRC1_ALPHA;
5025 case QRhiGraphicsPipeline::Src1Alpha:
5026 return D3D11_BLEND_SRC1_ALPHA;
5027 case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
5028 return D3D11_BLEND_INV_SRC1_ALPHA;
5031 return D3D11_BLEND_ZERO;
5038 case QRhiGraphicsPipeline::Add:
5039 return D3D11_BLEND_OP_ADD;
5040 case QRhiGraphicsPipeline::Subtract:
5041 return D3D11_BLEND_OP_SUBTRACT;
5042 case QRhiGraphicsPipeline::ReverseSubtract:
5043 return D3D11_BLEND_OP_REV_SUBTRACT;
5044 case QRhiGraphicsPipeline::Min:
5045 return D3D11_BLEND_OP_MIN;
5046 case QRhiGraphicsPipeline::Max:
5047 return D3D11_BLEND_OP_MAX;
5050 return D3D11_BLEND_OP_ADD;
5057 QCryptographicHash keyBuilder(QCryptographicHash::Sha1);
5058 keyBuilder.addData(source);
5059 return keyBuilder.result().toHex();
5063 QString *error, QShaderKey *usedShaderKey)
5065 QShaderKey key = { QShader::DxbcShader, 50, shaderVariant };
5066 QShaderCode dxbc = shader.shader(key);
5067 if (!dxbc.shader().isEmpty()) {
5069 *usedShaderKey = key;
5070 return dxbc.shader();
5073 key = { QShader::HlslShader, 50, shaderVariant };
5074 QShaderCode hlslSource = shader.shader(key);
5075 if (hlslSource.shader().isEmpty()) {
5076 qWarning() <<
"No HLSL (shader model 5.0) code found in baked shader" << shader;
5077 return QByteArray();
5081 *usedShaderKey = key;
5084 switch (shader.stage()) {
5085 case QShader::VertexStage:
5088 case QShader::TessellationControlStage:
5091 case QShader::TessellationEvaluationStage:
5094 case QShader::GeometryStage:
5097 case QShader::FragmentStage:
5100 case QShader::ComputeStage:
5104 qWarning(
"compileHlslShaderSource: Unknown SM 5.0 stage (%d)",
int(shader.stage()));
5105 return QByteArray();
5109 if (rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave)) {
5110 cacheKey.sourceHash = sourceHash(hlslSource.shader());
5111 cacheKey.target = target;
5112 cacheKey.entryPoint = hlslSource.entryPoint();
5114 auto cacheIt = m_bytecodeCache.data.constFind(cacheKey);
5115 if (cacheIt != m_bytecodeCache.data.constEnd())
5116 return cacheIt.value();
5119 static const pD3DCompile d3dCompile = QRhiD3D::resolveD3DCompile();
5120 if (d3dCompile ==
nullptr) {
5121 qWarning(
"Unable to resolve function D3DCompile()");
5122 return QByteArray();
5125 ID3DBlob *bytecode =
nullptr;
5126 ID3DBlob *errors =
nullptr;
5127 HRESULT hr = d3dCompile(hlslSource.shader().constData(), SIZE_T(hlslSource.shader().size()),
5128 nullptr,
nullptr,
nullptr,
5129 hlslSource.entryPoint().constData(), target, flags, 0, &bytecode, &errors);
5130 if (FAILED(hr) || !bytecode) {
5131 qWarning(
"HLSL shader compilation failed: 0x%x", uint(hr));
5133 *error = QString::fromUtf8(
static_cast<
const char *>(errors->GetBufferPointer()),
5134 int(errors->GetBufferSize()));
5137 return QByteArray();
5141 result.resize(
int(bytecode->GetBufferSize()));
5142 memcpy(result.data(), bytecode->GetBufferPointer(), size_t(result.size()));
5143 bytecode->Release();
5145 if (rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
5146 m_bytecodeCache.insertWithCapacityLimit(cacheKey, result);
5157 rhiD->pipelineCreationStart();
5158 if (!rhiD->sanityCheckGraphicsPipeline(
this))
5161 D3D11_RASTERIZER_DESC rastDesc = {};
5162 rastDesc.FillMode = toD3DFillMode(m_polygonMode);
5163 rastDesc.CullMode = toD3DCullMode(m_cullMode);
5164 rastDesc.FrontCounterClockwise = m_frontFace == CCW;
5165 rastDesc.DepthBias = m_depthBias;
5166 rastDesc.SlopeScaledDepthBias = m_slopeScaledDepthBias;
5167 rastDesc.DepthClipEnable = m_depthClamp ? FALSE : TRUE;
5168 rastDesc.ScissorEnable = m_flags.testFlag(UsesScissor);
5169 rastDesc.MultisampleEnable = rhiD->effectiveSampleDesc(m_sampleCount).Count > 1;
5170 HRESULT hr = rhiD->dev->CreateRasterizerState(&rastDesc, &rastState);
5172 qWarning(
"Failed to create rasterizer state: %s",
5173 qPrintable(QSystemError::windowsComString(hr)));
5177 D3D11_DEPTH_STENCIL_DESC dsDesc = {};
5178 dsDesc.DepthEnable = m_depthTest;
5179 dsDesc.DepthWriteMask = m_depthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
5180 dsDesc.DepthFunc = toD3DCompareOp(m_depthOp);
5181 dsDesc.StencilEnable = m_stencilTest;
5182 if (m_stencilTest) {
5183 dsDesc.StencilReadMask = UINT8(m_stencilReadMask);
5184 dsDesc.StencilWriteMask = UINT8(m_stencilWriteMask);
5185 dsDesc.FrontFace.StencilFailOp = toD3DStencilOp(m_stencilFront.failOp);
5186 dsDesc.FrontFace.StencilDepthFailOp = toD3DStencilOp(m_stencilFront.depthFailOp);
5187 dsDesc.FrontFace.StencilPassOp = toD3DStencilOp(m_stencilFront.passOp);
5188 dsDesc.FrontFace.StencilFunc = toD3DCompareOp(m_stencilFront.compareOp);
5189 dsDesc.BackFace.StencilFailOp = toD3DStencilOp(m_stencilBack.failOp);
5190 dsDesc.BackFace.StencilDepthFailOp = toD3DStencilOp(m_stencilBack.depthFailOp);
5191 dsDesc.BackFace.StencilPassOp = toD3DStencilOp(m_stencilBack.passOp);
5192 dsDesc.BackFace.StencilFunc = toD3DCompareOp(m_stencilBack.compareOp);
5194 hr = rhiD->dev->CreateDepthStencilState(&dsDesc, &dsState);
5196 qWarning(
"Failed to create depth-stencil state: %s",
5197 qPrintable(QSystemError::windowsComString(hr)));
5201 D3D11_BLEND_DESC blendDesc = {};
5202 blendDesc.IndependentBlendEnable = m_targetBlends.count() > 1;
5203 for (
int i = 0, ie = m_targetBlends.count(); i != ie; ++i) {
5204 const QRhiGraphicsPipeline::TargetBlend &b(m_targetBlends[i]);
5205 D3D11_RENDER_TARGET_BLEND_DESC blend = {};
5206 blend.BlendEnable = b.enable;
5207 blend.SrcBlend = toD3DBlendFactor(b.srcColor,
true);
5208 blend.DestBlend = toD3DBlendFactor(b.dstColor,
true);
5209 blend.BlendOp = toD3DBlendOp(b.opColor);
5210 blend.SrcBlendAlpha = toD3DBlendFactor(b.srcAlpha,
false);
5211 blend.DestBlendAlpha = toD3DBlendFactor(b.dstAlpha,
false);
5212 blend.BlendOpAlpha = toD3DBlendOp(b.opAlpha);
5213 blend.RenderTargetWriteMask = toD3DColorWriteMask(b.colorWrite);
5214 blendDesc.RenderTarget[i] = blend;
5216 if (m_targetBlends.isEmpty()) {
5217 D3D11_RENDER_TARGET_BLEND_DESC blend = {};
5218 blend.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
5219 blendDesc.RenderTarget[0] = blend;
5221 hr = rhiD->dev->CreateBlendState(&blendDesc, &blendState);
5223 qWarning(
"Failed to create blend state: %s",
5224 qPrintable(QSystemError::windowsComString(hr)));
5228 QByteArray vsByteCode;
5229 for (
const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
5230 int stagePushConstantRegister = -1;
5231 quint32 stagePushConstantSize = 0;
5232 auto cacheIt = rhiD->m_shaderCache.constFind(shaderStage);
5233 if (cacheIt != rhiD->m_shaderCache.constEnd()) {
5234 stagePushConstantRegister = cacheIt->pushConstantRegister;
5235 stagePushConstantSize = cacheIt->pushConstantSize;
5236 switch (shaderStage.type()) {
5237 case QRhiShaderStage::Vertex:
5238 vs.shader =
static_cast<ID3D11VertexShader *>(cacheIt->s);
5239 vs.shader->AddRef();
5240 vsByteCode = cacheIt->bytecode;
5241 vs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5243 case QRhiShaderStage::TessellationControl:
5244 hs.shader =
static_cast<ID3D11HullShader *>(cacheIt->s);
5245 hs.shader->AddRef();
5246 hs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5248 case QRhiShaderStage::TessellationEvaluation:
5249 ds.shader =
static_cast<ID3D11DomainShader *>(cacheIt->s);
5250 ds.shader->AddRef();
5251 ds.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5253 case QRhiShaderStage::Geometry:
5254 gs.shader =
static_cast<ID3D11GeometryShader *>(cacheIt->s);
5255 gs.shader->AddRef();
5256 gs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5258 case QRhiShaderStage::Fragment:
5259 fs.shader =
static_cast<ID3D11PixelShader *>(cacheIt->s);
5260 fs.shader->AddRef();
5261 fs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5268 QShaderKey shaderKey;
5269 UINT compileFlags = 0;
5270 if (m_flags.testFlag(CompileShadersWithDebugInfo))
5271 compileFlags |= D3DCOMPILE_DEBUG;
5273 const QByteArray bytecode = rhiD->compileHlslShaderSource(shaderStage.shader(), shaderStage.shaderVariant(), compileFlags,
5274 &error, &shaderKey);
5275 if (bytecode.isEmpty()) {
5276 qWarning(
"HLSL shader compilation failed: %s", qPrintable(error));
5280 if (rhiD->m_shaderCache.count() >= QRhiD3D11::MAX_SHADER_CACHE_ENTRIES) {
5282 rhiD->clearShaderCache();
5285 getPushConstantInfo(shaderStage.shader(), shaderKey, &stagePushConstantRegister, &stagePushConstantSize);
5287 switch (shaderStage.type()) {
5288 case QRhiShaderStage::Vertex:
5289 hr = rhiD->dev->CreateVertexShader(bytecode.constData(), SIZE_T(bytecode.size()),
nullptr, &vs.shader);
5291 qWarning(
"Failed to create vertex shader: %s",
5292 qPrintable(QSystemError::windowsComString(hr)));
5295 vsByteCode = bytecode;
5296 vs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5297 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(vs.shader, bytecode, vs.nativeResourceBindingMap,
5298 stagePushConstantRegister, stagePushConstantSize));
5299 vs.shader->AddRef();
5301 case QRhiShaderStage::TessellationControl:
5302 hr = rhiD->dev->CreateHullShader(bytecode.constData(), SIZE_T(bytecode.size()),
nullptr, &hs.shader);
5304 qWarning(
"Failed to create hull shader: %s",
5305 qPrintable(QSystemError::windowsComString(hr)));
5308 hs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5309 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(hs.shader, bytecode, hs.nativeResourceBindingMap,
5310 stagePushConstantRegister, stagePushConstantSize));
5311 hs.shader->AddRef();
5313 case QRhiShaderStage::TessellationEvaluation:
5314 hr = rhiD->dev->CreateDomainShader(bytecode.constData(), SIZE_T(bytecode.size()),
nullptr, &ds.shader);
5316 qWarning(
"Failed to create domain shader: %s",
5317 qPrintable(QSystemError::windowsComString(hr)));
5320 ds.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5321 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(ds.shader, bytecode, ds.nativeResourceBindingMap,
5322 stagePushConstantRegister, stagePushConstantSize));
5323 ds.shader->AddRef();
5325 case QRhiShaderStage::Geometry:
5326 hr = rhiD->dev->CreateGeometryShader(bytecode.constData(), SIZE_T(bytecode.size()),
nullptr, &gs.shader);
5328 qWarning(
"Failed to create geometry shader: %s",
5329 qPrintable(QSystemError::windowsComString(hr)));
5332 gs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5333 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(gs.shader, bytecode, gs.nativeResourceBindingMap,
5334 stagePushConstantRegister, stagePushConstantSize));
5335 gs.shader->AddRef();
5337 case QRhiShaderStage::Fragment:
5338 hr = rhiD->dev->CreatePixelShader(bytecode.constData(), SIZE_T(bytecode.size()),
nullptr, &fs.shader);
5340 qWarning(
"Failed to create pixel shader: %s",
5341 qPrintable(QSystemError::windowsComString(hr)));
5344 fs.nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
5345 rhiD->m_shaderCache.insert(shaderStage, QRhiD3D11::Shader(fs.shader, bytecode, fs.nativeResourceBindingMap,
5346 stagePushConstantRegister, stagePushConstantSize));
5347 fs.shader->AddRef();
5354 if (stagePushConstantRegister >= 0 && stagePushConstantSize) {
5355 const int stageIndex = rbmStageIndex(shaderStage.type());
5356 if (stageIndex >= 0) {
5357 pushConstants.reg = stagePushConstantRegister;
5358 pushConstants.size = qMax(pushConstants.size, stagePushConstantSize);
5359 pushConstants.stages |= 1u << uint(stageIndex);
5364 d3dTopology = toD3DTopology(m_topology, m_patchControlPointCount);
5366 if (!vsByteCode.isEmpty()) {
5367 QByteArrayList matrixSliceSemantics;
5368 QVarLengthArray<D3D11_INPUT_ELEMENT_DESC, 4> inputDescs;
5369 for (
auto it = m_vertexInputLayout.cbeginAttributes(), itEnd = m_vertexInputLayout.cendAttributes();
5372 D3D11_INPUT_ELEMENT_DESC desc = {};
5377 const int matrixSlice = it->matrixSlice();
5378 if (matrixSlice < 0) {
5379 desc.SemanticName =
"TEXCOORD";
5380 desc.SemanticIndex = UINT(it->location());
5384 std::snprintf(sem.data(), sem.size(),
"TEXCOORD%d_", it->location() - matrixSlice);
5385 matrixSliceSemantics.append(sem);
5386 desc.SemanticName = matrixSliceSemantics.last().constData();
5387 desc.SemanticIndex = UINT(matrixSlice);
5389 desc.Format = toD3DAttributeFormat(it->format());
5390 desc.InputSlot = UINT(it->binding());
5391 desc.AlignedByteOffset = it->offset();
5392 const QRhiVertexInputBinding *inputBinding = m_vertexInputLayout.bindingAt(it->binding());
5393 if (inputBinding->classification() == QRhiVertexInputBinding::PerInstance) {
5394 desc.InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
5395 desc.InstanceDataStepRate = inputBinding->instanceStepRate();
5397 desc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
5399 inputDescs.append(desc);
5401 if (!inputDescs.isEmpty()) {
5402 hr = rhiD->dev->CreateInputLayout(inputDescs.constData(), UINT(inputDescs.count()),
5403 vsByteCode, SIZE_T(vsByteCode.size()), &inputLayout);
5405 qWarning(
"Failed to create input layout: %s",
5406 qPrintable(QSystemError::windowsComString(hr)));
5412 rhiD->pipelineCreationEnd();
5414 rhiD->registerResource(
this);
5433 cs.shader->Release();
5434 cs.shader =
nullptr;
5435 cs.nativeResourceBindingMap.clear();
5440 rhiD->unregisterResource(
this);
5449 rhiD->pipelineCreationStart();
5451 auto cacheIt = rhiD->m_shaderCache.constFind(m_shaderStage);
5452 if (cacheIt != rhiD->m_shaderCache.constEnd()) {
5453 cs.shader =
static_cast<ID3D11ComputeShader *>(cacheIt->s);
5454 cs.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
5455 pushConstants.reg = cacheIt->pushConstantRegister;
5456 pushConstants.size = cacheIt->pushConstantSize;
5459 QShaderKey shaderKey;
5460 UINT compileFlags = 0;
5461 if (m_flags.testFlag(CompileShadersWithDebugInfo))
5462 compileFlags |= D3DCOMPILE_DEBUG;
5464 const QByteArray bytecode = rhiD->compileHlslShaderSource(m_shaderStage.shader(), m_shaderStage.shaderVariant(), compileFlags,
5465 &error, &shaderKey);
5466 if (bytecode.isEmpty()) {
5467 qWarning(
"HLSL compute shader compilation failed: %s", qPrintable(error));
5471 HRESULT hr = rhiD->dev->CreateComputeShader(bytecode.constData(), SIZE_T(bytecode.size()),
nullptr, &cs.shader);
5473 qWarning(
"Failed to create compute shader: %s",
5474 qPrintable(QSystemError::windowsComString(hr)));
5478 cs.nativeResourceBindingMap = m_shaderStage.shader().nativeResourceBindingMap(shaderKey);
5479 getPushConstantInfo(m_shaderStage.shader(), shaderKey, &pushConstants.reg, &pushConstants.size);
5481 if (rhiD->m_shaderCache.count() >= QRhiD3D11::MAX_SHADER_CACHE_ENTRIES)
5484 rhiD->m_shaderCache.insert(m_shaderStage, QRhiD3D11::Shader(cs.shader, bytecode, cs.nativeResourceBindingMap,
5485 pushConstants.reg, pushConstants.size));
5488 cs.shader->AddRef();
5490 rhiD->pipelineCreationEnd();
5492 rhiD->registerResource(
this);
5517 D3D11_QUERY_DESC queryDesc = {};
5519 if (!disjointQuery[i]) {
5520 queryDesc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
5521 HRESULT hr = rhiD->dev->CreateQuery(&queryDesc, &disjointQuery[i]);
5523 qWarning(
"Failed to create timestamp disjoint query: %s",
5524 qPrintable(QSystemError::windowsComString(hr)));
5528 queryDesc.Query = D3D11_QUERY_TIMESTAMP;
5529 for (
int j = 0; j < 2; ++j) {
5530 const int idx = 2 * i + j;
5532 HRESULT hr = rhiD->dev->CreateQuery(&queryDesc, &query[idx]);
5534 qWarning(
"Failed to create timestamp query: %s",
5535 qPrintable(QSystemError::windowsComString(hr)));
5548 if (disjointQuery[i]) {
5549 disjointQuery[i]->Release();
5550 disjointQuery[i] =
nullptr;
5552 for (
int j = 0; j < 2; ++j) {
5555 query[idx]->Release();
5556 query[idx] =
nullptr;
5564 bool result =
false;
5568 ID3D11Query *tsDisjoint = disjointQuery[pairIndex];
5569 ID3D11Query *tsStart = query[pairIndex * 2];
5570 ID3D11Query *tsEnd = query[pairIndex * 2 + 1];
5571 quint64 timestamps[2];
5572 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT dj;
5575 ok &= context->GetData(tsDisjoint, &dj,
sizeof(dj), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
5576 ok &= context->GetData(tsEnd, ×tamps[1],
sizeof(quint64), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
5577 ok &= context->GetData(tsStart, ×tamps[0],
sizeof(quint64), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
5580 if (!dj.Disjoint && dj.Frequency) {
5581 const float elapsedMs = (timestamps[1] - timestamps[0]) /
float(dj.Frequency) * 1000.0f;
5582 *elapsedSec = elapsedMs / 1000.0;
5585 active[pairIndex] =
false;
5594 backBufferTex =
nullptr;
5595 backBufferRtv =
nullptr;
5597 msaaTex[i] =
nullptr;
5598 msaaRtv[i] =
nullptr;
5609 if (backBufferRtv) {
5610 backBufferRtv->Release();
5611 backBufferRtv =
nullptr;
5613 if (backBufferRtvRight) {
5614 backBufferRtvRight->Release();
5615 backBufferRtvRight =
nullptr;
5617 if (backBufferTex) {
5618 backBufferTex->Release();
5619 backBufferTex =
nullptr;
5623 msaaRtv[i]->Release();
5624 msaaRtv[i] =
nullptr;
5627 msaaTex[i]->Release();
5628 msaaTex[i] =
nullptr;
5636 dcompVisual->Release();
5637 dcompVisual =
nullptr;
5641 dcompTarget->Release();
5642 dcompTarget =
nullptr;
5650 timestamps.destroy();
5652 swapChain->Release();
5653 swapChain =
nullptr;
5655 if (frameLatencyWaitableObject) {
5656 CloseHandle(frameLatencyWaitableObject);
5657 frameLatencyWaitableObject =
nullptr;
5660 QDxgiVSyncService::instance()->unregisterWindow(window);
5664 rhiD->unregisterResource(
this);
5667 rhiD->context->Flush();
5683 return targetBuffer == StereoTargetBuffer::LeftBuffer? &rt: &rtRight;
5689 return m_window->size() * m_window->devicePixelRatio();
5698 qWarning(
"Attempted to call isFormatSupported() without a window set");
5703 if (QDxgiHdrInfo(rhiD->activeAdapter).isHdrCapable(m_window))
5704 return f == QRhiSwapChain::HDRExtendedSrgbLinear || f == QRhiSwapChain::HDR10;
5715 info = QDxgiHdrInfo(rhiD->activeAdapter).queryHdrInfo(m_window);
5724 rhiD->registerResource(rpD,
false);
5729 ID3D11Texture2D **tex, ID3D11RenderTargetView **rtv)
const
5731 D3D11_TEXTURE2D_DESC desc = {};
5732 desc.Width = UINT(size.width());
5733 desc.Height = UINT(size.height());
5736 desc.Format = format;
5737 desc.SampleDesc = sampleDesc;
5738 desc.Usage = D3D11_USAGE_DEFAULT;
5739 desc.BindFlags = D3D11_BIND_RENDER_TARGET;
5742 HRESULT hr = rhiD->dev->CreateTexture2D(&desc,
nullptr, tex);
5744 qWarning(
"Failed to create color buffer texture: %s",
5745 qPrintable(QSystemError::windowsComString(hr)));
5749 D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
5750 rtvDesc.Format = format;
5751 rtvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
5752 hr = rhiD->dev->CreateRenderTargetView(*tex, &rtvDesc, rtv);
5754 qWarning(
"Failed to create color buffer rtv: %s",
5755 qPrintable(QSystemError::windowsComString(hr)));
5769 qCDebug(QRHI_LOG_INFO,
"Creating Direct Composition device (needed for semi-transparent windows)");
5770 dcompDevice = QRhiD3D::createDirectCompositionDevice();
5771 return dcompDevice ?
true :
false;
5783 const bool needsRegistration = !
window ||
window != m_window;
5784 const bool stereo = m_window->format().stereo();
5787 if (window && window != m_window)
5791 pixelSize = surfacePixelSize();
5793 if (pixelSize.isEmpty())
5796 HWND hwnd =
reinterpret_cast<HWND>(
window->winId());
5801 if (m_flags.testFlag(SurfaceHasPreMulAlpha) || m_flags.testFlag(SurfaceHasNonPreMulAlpha)) {
5804 hr = rhiD->dcompDevice->CreateTargetForHwnd(hwnd,
false, &dcompTarget);
5806 qWarning(
"Failed to create Direct Compsition target for the window: %s",
5807 qPrintable(QSystemError::windowsComString(hr)));
5810 if (dcompTarget && !dcompVisual) {
5811 hr = rhiD->dcompDevice->CreateVisual(&dcompVisual);
5813 qWarning(
"Failed to create DirectComposition visual: %s",
5814 qPrintable(QSystemError::windowsComString(hr)));
5819 if (
window->requestedFormat().alphaBufferSize() <= 0)
5820 qWarning(
"Swapchain says surface has alpha but the window has no alphaBufferSize set. "
5821 "This may lead to problems.");
5824 swapInterval = m_flags.testFlag(QRhiSwapChain::NoVSync) ? 0 : 1;
5831 if (swapInterval == 0 && rhiD->supportsAllowTearing)
5832 swapChainFlags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
5836 const bool useFrameLatencyWaitableObject = rhiD->maxFrameLatency != 0
5837 && swapInterval != 0
5838 && rhiD->driverInfoStruct.deviceType != QRhiDriverInfo::CpuDevice;
5840 if (useFrameLatencyWaitableObject) {
5842 swapChainFlags |= DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
5846 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount);
5847 colorFormat = DEFAULT_FORMAT;
5848 srgbAdjustedColorFormat = m_flags.testFlag(sRGB) ? DEFAULT_SRGB_FORMAT : DEFAULT_FORMAT;
5850 DXGI_COLOR_SPACE_TYPE hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
5851 if (m_format != SDR) {
5852 if (
QDxgiHdrInfo(rhiD->activeAdapter).isHdrCapable(m_window)) {
5855 case HDRExtendedSrgbLinear:
5856 colorFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;
5857 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
5858 srgbAdjustedColorFormat = colorFormat;
5861 colorFormat = DXGI_FORMAT_R10G10B10A2_UNORM;
5862 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
5863 srgbAdjustedColorFormat = colorFormat;
5872 qWarning(
"The output associated with the window is not HDR capable "
5873 "(or Use HDR is Off in the Display Settings), ignoring HDR format request");
5883 DXGI_SWAP_CHAIN_DESC1 desc = {};
5884 desc.Width = UINT(pixelSize.width());
5885 desc.Height = UINT(pixelSize.height());
5886 desc.Format = colorFormat;
5887 desc.SampleDesc.Count = 1;
5888 desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
5890 desc.Flags = swapChainFlags;
5891 desc.Scaling = rhiD->useLegacySwapchainModel ? DXGI_SCALING_STRETCH : DXGI_SCALING_NONE;
5892 desc.SwapEffect = rhiD->useLegacySwapchainModel ? DXGI_SWAP_EFFECT_DISCARD : DXGI_SWAP_EFFECT_FLIP_DISCARD;
5893 desc.Stereo = stereo;
5899 desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
5904 desc.Scaling = DXGI_SCALING_STRETCH;
5907 IDXGIFactory2 *fac =
static_cast<IDXGIFactory2 *>(rhiD->dxgiFactory);
5908 IDXGISwapChain1 *sc1;
5911 hr = fac->CreateSwapChainForComposition(rhiD->dev, &desc,
nullptr, &sc1);
5913 hr = fac->CreateSwapChainForHwnd(rhiD->dev, hwnd, &desc,
nullptr,
nullptr, &sc1);
5918 if (FAILED(hr) && m_format != SDR) {
5919 colorFormat = DEFAULT_FORMAT;
5920 desc.Format = DEFAULT_FORMAT;
5922 hr = fac->CreateSwapChainForComposition(rhiD->dev, &desc,
nullptr, &sc1);
5924 hr = fac->CreateSwapChainForHwnd(rhiD->dev, hwnd, &desc,
nullptr,
nullptr, &sc1);
5927 if (SUCCEEDED(hr)) {
5929 IDXGISwapChain3 *sc3 =
nullptr;
5930 if (SUCCEEDED(sc1->QueryInterface(__uuidof(IDXGISwapChain3),
reinterpret_cast<
void **>(&sc3)))) {
5931 if (m_format != SDR) {
5932 hr = sc3->SetColorSpace1(hdrColorSpace);
5934 qWarning(
"Failed to set color space on swapchain: %s",
5935 qPrintable(QSystemError::windowsComString(hr)));
5937 if (useFrameLatencyWaitableObject) {
5938 sc3->SetMaximumFrameLatency(rhiD->maxFrameLatency);
5939 frameLatencyWaitableObject = sc3->GetFrameLatencyWaitableObject();
5943 if (m_format != SDR)
5944 qWarning(
"IDXGISwapChain3 not available, HDR swapchain will not work as expected");
5945 if (useFrameLatencyWaitableObject) {
5946 IDXGISwapChain2 *sc2 =
nullptr;
5947 if (SUCCEEDED(sc1->QueryInterface(__uuidof(IDXGISwapChain2),
reinterpret_cast<
void **>(&sc2)))) {
5948 sc2->SetMaximumFrameLatency(rhiD->maxFrameLatency);
5949 frameLatencyWaitableObject = sc2->GetFrameLatencyWaitableObject();
5952 qWarning(
"IDXGISwapChain2 not available, FrameLatencyWaitableObject cannot be used");
5957 hr = dcompVisual->SetContent(sc1);
5958 if (SUCCEEDED(hr)) {
5959 hr = dcompTarget->SetRoot(dcompVisual);
5961 qWarning(
"Failed to associate Direct Composition visual with the target: %s",
5962 qPrintable(QSystemError::windowsComString(hr)));
5965 qWarning(
"Failed to set content for Direct Composition visual: %s",
5966 qPrintable(QSystemError::windowsComString(hr)));
5970 rhiD->dxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES);
5973 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
5974 qWarning(
"Device loss detected during swapchain creation");
5977 }
else if (FAILED(hr)) {
5978 qWarning(
"Failed to create D3D11 swapchain: %s"
5979 " (Width=%u Height=%u Format=%u SampleCount=%u BufferCount=%u Scaling=%u SwapEffect=%u Stereo=%u)",
5980 qPrintable(QSystemError::windowsComString(hr)),
5981 desc.Width, desc.Height, UINT(desc.Format), desc.SampleDesc.Count,
5982 desc.BufferCount, UINT(desc.Scaling), UINT(desc.SwapEffect), UINT(desc.Stereo));
5988 hr = swapChain->ResizeBuffers(UINT(BUFFER_COUNT), UINT(pixelSize.width()), UINT(pixelSize.height()),
5989 colorFormat, swapChainFlags);
5990 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
5991 qWarning(
"Device loss detected in ResizeBuffers()");
5994 }
else if (FAILED(hr)) {
5995 qWarning(
"Failed to resize D3D11 swapchain: %s",
5996 qPrintable(QSystemError::windowsComString(hr)));
6015 hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
reinterpret_cast<
void **>(&backBufferTex));
6017 qWarning(
"Failed to query swapchain backbuffer: %s",
6018 qPrintable(QSystemError::windowsComString(hr)));
6021 D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
6022 rtvDesc.Format = srgbAdjustedColorFormat;
6023 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
6024 hr = rhiD->dev->CreateRenderTargetView(backBufferTex, &rtvDesc, &backBufferRtv);
6026 qWarning(
"Failed to create rtv for swapchain backbuffer: %s",
6027 qPrintable(QSystemError::windowsComString(hr)));
6033 rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
6034 rtvDesc.Texture2DArray.FirstArraySlice = 1;
6035 rtvDesc.Texture2DArray.ArraySize = 1;
6036 hr = rhiD->dev->CreateRenderTargetView(backBufferTex, &rtvDesc, &backBufferRtvRight);
6038 qWarning(
"Failed to create rtv for swapchain backbuffer (right eye): %s",
6039 qPrintable(QSystemError::windowsComString(hr)));
6046 if (sampleDesc.Count > 1) {
6047 if (!newColorBuffer(pixelSize, srgbAdjustedColorFormat, sampleDesc, &msaaTex[i], &msaaRtv[i]))
6052 if (m_depthStencil && m_depthStencil->sampleCount() != m_sampleCount) {
6053 qWarning(
"Depth-stencil buffer's sampleCount (%d) does not match color buffers' sample count (%d). Expect problems.",
6054 m_depthStencil->sampleCount(), m_sampleCount);
6056 if (m_depthStencil && m_depthStencil->pixelSize() != pixelSize) {
6057 if (m_depthStencil->flags().testFlag(QRhiRenderBuffer::UsedWithSwapChainOnly)) {
6058 m_depthStencil->setPixelSize(pixelSize);
6059 if (!m_depthStencil->create())
6060 qWarning(
"Failed to rebuild swapchain's associated depth-stencil buffer for size %dx%d",
6061 pixelSize.width(), pixelSize.height());
6063 qWarning(
"Depth-stencil buffer's size (%dx%d) does not match the surface size (%dx%d). Expect problems.",
6064 m_depthStencil->pixelSize().width(), m_depthStencil->pixelSize().height(),
6065 pixelSize.width(), pixelSize.height());
6072 ds = m_depthStencil ?
QRHI_RES(QD3D11RenderBuffer, m_depthStencil) :
nullptr;
6074 rt.setRenderPassDescriptor(m_renderPassDesc);
6076 rtD->d.rp =
QRHI_RES(QD3D11RenderPassDescriptor, m_renderPassDesc);
6077 rtD->d.pixelSize = pixelSize;
6078 rtD->d.dpr =
float(
window->devicePixelRatio());
6079 rtD->d.sampleCount =
int(sampleDesc.Count);
6080 rtD->d.views.setFrom(1, &backBufferRtv,
ds ?
ds->dsv :
nullptr);
6083 rtD =
QRHI_RES(QD3D11SwapChainRenderTarget, &rtRight);
6084 rtD->d.rp =
QRHI_RES(QD3D11RenderPassDescriptor, m_renderPassDesc);
6085 rtD->d.pixelSize = pixelSize;
6086 rtD->d.dpr =
float(
window->devicePixelRatio());
6087 rtD->d.sampleCount =
int(sampleDesc.Count);
6088 rtD->d.views.setFrom(1, &backBufferRtvRight,
ds ?
ds->dsv :
nullptr);
6091 if (rhiD->rhiFlags.testFlag(QRhi::EnableTimestamps)) {
6092 timestamps.prepare(rhiD);
6096 QDxgiVSyncService::instance()->registerWindow(window);
6098 if (needsRegistration)
6099 rhiD->registerResource(
this);
6101 m_currentPixelSize = pixelSize;
6108 if (rtViews.dsv != currentRtViews.dsv) {
6109 rtViews.dsv = currentRtViews.dsv;
6113 ret |= rtViews.rtv[i] != currentRtViews.rtv[i];
6114 rtViews.rtv[i] = currentRtViews.rtv[i];
6116 rtViews.colorAttCount = currentRtViews.colorAttCount;
6118 ret |= rtViews.rtv[i] !=
nullptr;
6119 rtViews.rtv[i] =
nullptr;
6121 for (
int i = 0; i < count; i++) {
6122 ret |= uav[i] != uavs[i];
6126 ret |= uav[i] !=
nullptr;
QRhiDriverInfo info() const override
void updateShaderResourceBindings(QD3D11ShaderResourceBindings *srbD, const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[], uint pushConstantStages)
void setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor) override
void debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg) override
bool isYUpInNDC() const override
void drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
QRhiSwapChain * createSwapChain() override
void enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
bool isFeatureSupported(QRhi::Feature feature) const override
QRhi::FrameOpResult endOffscreenFrame(QRhi::EndFrameFlags flags) override
bool isDeviceLost() const override
void executeBufferHostWrites(QD3D11Buffer *bufD)
QRhiStats statistics() override
QList< QSize > supportedShadingRates(int sampleCount) const override
QRhiComputePipeline * createComputePipeline() override
void debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name) override
QRhi::FrameOpResult finish() override
void setVertexInput(QRhiCommandBuffer *cb, int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings, QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat) override
void dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset) override
QRhiGraphicsPipeline * createGraphicsPipeline() override
void drawIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
QRhiShaderResourceBindings * createShaderResourceBindings() override
QRhi::FrameOpResult beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags) override
QList< int > supportedSampleCounts() const override
QRhiTextureRenderTarget * createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc, QRhiTextureRenderTarget::Flags flags) override
QByteArray compileHlslShaderSource(const QShader &shader, QShader::Variant shaderVariant, uint flags, QString *error, QShaderKey *usedShaderKey)
void setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) override
bool isClipDepthZeroToOne() const override
void resetShaderResources(QD3D11CommandBuffer *cbD, QD3D11RenderTargetUavUpdateState *rtUavState)
bool ensureDirectCompositionDevice()
const QRhiNativeHandles * nativeHandles(QRhiCommandBuffer *cb) override
void beginComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
void draw(QRhiCommandBuffer *cb, quint32 vertexCount, quint32 instanceCount, quint32 firstVertex, quint32 firstInstance) override
void enqueueSubresUpload(QD3D11Texture *texD, QD3D11CommandBuffer *cbD, int layer, int level, const QRhiTextureSubresourceUploadDescription &subresDesc)
void reportLiveObjects(ID3D11Device *device)
void resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
QMatrix4x4 clipSpaceCorrMatrix() const override
void setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data) override
bool isYUpInFramebuffer() const override
int resourceLimit(QRhi::ResourceLimit limit) const override
void beginExternal(QRhiCommandBuffer *cb) override
QRhiTexture * createTexture(QRhiTexture::Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, QRhiTexture::Flags flags) override
void setPipelineCacheData(const QByteArray &data) override
void executeCommandBuffer(QD3D11CommandBuffer *cbD)
void debugMarkEnd(QRhiCommandBuffer *cb) override
void releaseCachedResources() override
double lastCompletedGpuTime(QRhiCommandBuffer *cb) override
bool importedDeviceAndContext
QRhi::FrameOpResult beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags) override
bool supportsAllowTearing
void dispatch(QRhiCommandBuffer *cb, int x, int y, int z) override
void endExternal(QRhiCommandBuffer *cb) override
void setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport) override
bool ensurePushConstantBuffer()
void drawIndexedIndirectCount(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, QRhiBuffer *countBuffer, quint32 countBufferOffset, quint32 maxDrawCount, quint32 stride) override
void setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps) override
QRhi::FrameOpResult endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags) override
QRhiShadingRateMap * createShadingRateMap() override
bool isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const override
void setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb, int dynamicOffsetCount, const QRhiCommandBuffer::DynamicOffset *dynamicOffsets) override
bool useLegacySwapchainModel
void endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
bool makeThreadLocalNativeContextCurrent() override
bool create(QRhi::Flags flags) override
void finishActiveReadbacks()
void setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize) override
QByteArray pipelineCacheData() override
const QRhiNativeHandles * nativeHandles() override
QRhiDriverInfo driverInfo() const override
void endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override
int ubufAlignment() const override
void beginPass(QRhiCommandBuffer *cb, QRhiRenderTarget *rt, const QColor &colorClearValue, const QRhiDepthStencilClearValue &depthStencilClearValue, QRhiResourceUpdateBatch *resourceUpdates, QRhiCommandBuffer::BeginPassFlags flags) override
void bindShaderResources(QD3D11CommandBuffer *cbD, const QD3D11ShaderResourceBindings::ResourceBatches &allResourceBatches, const uint *dynOfsPairs, int dynOfsPairCount, bool offsetOnlyChange, QD3D11RenderTargetUavUpdateState *rtUavState)
void drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount, quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance) override
QRhiSampler * createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter, QRhiSampler::Filter mipmapMode, QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w) override
void setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps) override
QRhiD3D11(QRhiD3D11InitParams *params, QRhiD3D11NativeHandles *importDevice=nullptr)
DXGI_SAMPLE_DESC effectiveSampleDesc(int sampleCount) const
void setStencilRef(QRhiCommandBuffer *cb, quint32 refValue) override
void drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override
static QRhiResourceUpdateBatchPrivate * get(QRhiResourceUpdateBatch *b)
void fillDriverInfo(QRhiDriverInfo *info, const DXGI_ADAPTER_DESC1 &desc)
static const DXGI_FORMAT DEFAULT_SRGB_FORMAT
static void applyDynamicOffsets(UINT *offsets, int batchIndex, const QRhiBatchedBindings< UINT > *originalBindings, const QRhiBatchedBindings< UINT > *staticOffsets, const uint *dynOfsPairs, int dynOfsPairCount)
static D3D11_TEXTURE_ADDRESS_MODE toD3DAddressMode(QRhiSampler::AddressMode m)
#define SETUAVBATCH(stagePrefixL, stagePrefixU)
static QByteArray sourceHash(const QByteArray &source)
#define SETSAMPLERBATCH(stagePrefixL, stagePrefixU)
static const int RBM_HULL
static uint toD3DBufferUsage(QRhiBuffer::UsageFlags usage)
static const int RBM_FRAGMENT
#define SETUBUFBATCH(stagePrefixL, stagePrefixU)
Int aligned(Int v, Int byteAlign)
\variable QRhiVulkanQueueSubmitParams::waitSemaphoreCount
static DXGI_FORMAT toD3DDepthTextureDSVFormat(QRhiTexture::Format format)
static D3D11_BLEND toD3DBlendFactor(QRhiGraphicsPipeline::BlendFactor f, bool rgb)
static const int RBM_VERTEX
static D3D11_BLEND_OP toD3DBlendOp(QRhiGraphicsPipeline::BlendOp op)
#define D3D11_1_UAV_SLOT_COUNT
static const int RBM_DOMAIN
static D3D11_FILTER toD3DFilter(QRhiSampler::Filter minFilter, QRhiSampler::Filter magFilter, QRhiSampler::Filter mipFilter)
static std::pair< int, int > mapBinding(int binding, int stageIndex, const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[], uint pushConstantStages)
static QD3D11RenderTargetData * rtData(QRhiRenderTarget *rt)
static UINT8 toD3DColorWriteMask(QRhiGraphicsPipeline::ColorMask c)
static D3D11_STENCIL_OP toD3DStencilOp(QRhiGraphicsPipeline::StencilOp op)
void releasePipelineShader(T &s)
static D3D11_COMPARISON_FUNC toD3DTextureComparisonFunc(QRhiSampler::CompareOp op)
static int rbmStageIndex(QRhiShaderStage::Type type)
static DXGI_FORMAT toD3DAttributeFormat(QRhiVertexInputAttribute::Format format)
static void getPushConstantInfo(const QShader &shader, const QShaderKey &key, int *reg, quint32 *size)
static const int RBM_GEOMETRY
static D3D11_PRIMITIVE_TOPOLOGY toD3DTopology(QRhiGraphicsPipeline::Topology t, int patchControlPointCount)
static IDXGIFactory1 * createDXGIFactory2()
static D3D11_FILL_MODE toD3DFillMode(QRhiGraphicsPipeline::PolygonMode mode)
static bool isDepthTextureFormat(QRhiTexture::Format format)
static const int RBM_COMPUTE
static D3D11_CULL_MODE toD3DCullMode(QRhiGraphicsPipeline::CullMode c)
#define SETSHADER(StageL, StageU)
static DXGI_FORMAT toD3DTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
static const DXGI_FORMAT DEFAULT_FORMAT
static uint clampedResourceCount(uint startSlot, int countSlots, uint maxSlots, const char *resType)
#define D3D11_VS_INPUT_REGISTER_COUNT
#define DXGI_ADAPTER_FLAG_SOFTWARE
\variable QRhiD3D11NativeHandles::dev
static QRhiTexture::Format swapchainReadbackTextureFormat(DXGI_FORMAT format, QRhiTexture::Flags *flags)
static D3D11_COMPARISON_FUNC toD3DCompareOp(QRhiGraphicsPipeline::CompareOp op)
static DXGI_FORMAT toD3DDepthTextureSRVFormat(QRhiTexture::Format format)
static const int RBM_SUPPORTED_STAGES
bool hasPendingDynamicUpdates
void endFullDynamicBufferUpdateForCurrentFrame() override
To be called when the entire contents of the buffer data has been updated in the memory block returne...
QD3D11Buffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
char * beginFullDynamicBufferUpdateForCurrentFrame() override
bool create() override
Creates the corresponding native graphics resources.
ID3D11UnorderedAccessView * createClearUnorderedAccessView(quint32 offset, quint32 size)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QRhiBuffer::NativeBuffer nativeBuffer() override
ID3D11UnorderedAccessView * unorderedAccessView(quint32 offset)
static const int MAX_DYNAMIC_OFFSET_COUNT
static const int MAX_VERTEX_BUFFER_BINDING_COUNT
int retainResourceBatches(const std::shared_ptr< QD3D11ShaderResourceBindings::ResourceBatches > &resourceBatches)
QD3D11CommandBuffer(QRhiImplementation *rhi)
uint currentPipelineGeneration
uint currentSrbGeneration
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QD3D11ComputePipeline(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QD3D11GraphicsPipeline(QRhiImplementation *rhi)
~QD3D11GraphicsPipeline()
bool create() override
Creates the corresponding native graphics resources.
QD3D11RenderBuffer(QRhiImplementation *rhi, Type type, const QSize &pixelSize, int sampleCount, QRhiRenderBuffer::Flags flags, QRhiTexture::Format backingFormatHint)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool create() override
Creates the corresponding native graphics resources.
QRhiTexture::Format backingFormat() const override
QD3D11RenderPassDescriptor(QRhiImplementation *rhi)
~QD3D11RenderPassDescriptor()
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool isCompatible(const QRhiRenderPassDescriptor *other) const override
QVector< quint32 > serializedFormat() const override
static const int MAX_COLOR_ATTACHMENTS
bool update(const QD3D11RenderTargetData::Views ¤tRtViews, ID3D11UnorderedAccessView *const *uavs=nullptr, int count=0)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QD3D11Sampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode, AddressMode u, AddressMode v, AddressMode w)
QD3D11GraphicsPipeline * lastUsedGraphicsPipeline
bool create() override
Creates the corresponding resource binding set.
~QD3D11ShaderResourceBindings()
void updateResources(UpdateFlags flags) override
QD3D11ComputePipeline * lastUsedComputePipeline
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QD3D11ShaderResourceBindings(QRhiImplementation *rhi)
int sampleCount() const override
~QD3D11SwapChainRenderTarget()
QD3D11SwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
float devicePixelRatio() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QSize pixelSize() const override
bool prepare(QRhiD3D11 *rhiD)
bool tryQueryTimestamps(int idx, ID3D11DeviceContext *context, double *elapsedSec)
bool active[TIMESTAMP_PAIRS]
static const int TIMESTAMP_PAIRS
QRhiSwapChainHdrInfo hdrInfo() override
\variable QRhiSwapChainHdrInfo::limitsType
int lastFrameLatencyWaitSlot
QRhiRenderTarget * currentFrameRenderTarget() override
QD3D11SwapChain(QRhiImplementation *rhi)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QRhiRenderTarget * currentFrameRenderTarget(StereoTargetBuffer targetBuffer) override
bool createOrResize() override
Creates the swapchain if not already done and resizes the swapchain buffers to match the current size...
QSize surfacePixelSize() override
bool newColorBuffer(const QSize &size, DXGI_FORMAT format, DXGI_SAMPLE_DESC sampleDesc, ID3D11Texture2D **tex, ID3D11RenderTargetView **rtv) const
static const int BUFFER_COUNT
bool isFormatSupported(Format f) override
QRhiCommandBuffer * currentFrameCommandBuffer() override
int currentTimestampPairIndex
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() override
QSize pixelSize() const override
QD3D11TextureRenderTarget(QRhiImplementation *rhi, const QRhiTextureRenderTargetDescription &desc, Flags flags)
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
float devicePixelRatio() const override
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() override
int sampleCount() const override
bool ownsRtv[QD3D11RenderTargetData::MAX_COLOR_ATTACHMENTS]
bool create() override
Creates the corresponding native graphics resources.
~QD3D11TextureRenderTarget()
bool create() override
Creates the corresponding native graphics resources.
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool createFrom(NativeTexture src) override
Similar to create(), except that no new native textures are created.
NativeTexture nativeTexture() override
bool prepareCreate(QSize *adjustedSize=nullptr)
QD3D11Texture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, Flags flags)
ID3D11UnorderedAccessView * unorderedAccessViewForLevel(int level)
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h