qrhid3d11.cpp 112 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt RHI module
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qrhid3d11_p.h"
Laszlo Agocs's avatar
Laszlo Agocs committed
38
#include "qrhirsh_p.h"
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <QWindow>
#include <QBakedShader>
#include <qmath.h>

#include <d3dcompiler.h>
#include <comdef.h>

QT_BEGIN_NAMESPACE

/*
  Direct3D 11 backend. Provides a double-buffered flip model (FLIP_DISCARD)
  swapchain. Textures and "static" buffers are USAGE_DEFAULT, leaving it to
  UpdateSubResource to upload the data in any way it sees fit. "Dynamic"
  buffers are USAGE_DYNAMIC and updating is done by mapping with WRITE_DISCARD.
  (so here QRhiBuffer keeps a copy of the buffer contents and all of it is
  memcpy'd every time, leaving the rest (juggling with the memory area Map
  returns) to the driver).
*/

Laszlo Agocs's avatar
Laszlo Agocs committed
58 59 60
/*!
    \class QRhiD3D11InitParams
    \inmodule QtRhi
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    \brief Direct3D 11 specific initialization parameters.

    A D3D11-based QRhi needs no special parameters for initialization. If
    desired, enableDebugLayer can be set to \c true to enable the Direct3D
    debug layer. This can be useful during development, but should be avoided
    in production builds.

    \badcode
        QRhiD3D11InitParams params;
        params.enableDebugLayer = true;
        rhi = QRhi::create(QRhi::D3D11, &params);
    \endcode

    \note QRhiSwapChain should only be used in combination with QWindow
    instances that have their surface type set to QSurface::OpenGLSurface.
    There are currently no Direct3D specifics in the Windows platform support
    of Qt and therefore there is no separate QSurface type available.

    \section2 Working with existing Direct3D 11 devices

    When interoperating with another graphics engine, it may be necessary to
82 83 84 85
    get a QRhi instance that uses the same Direct3D device. This can be
    achieved by passing a pointer to a QRhiD3D11NativeHandles to
    QRhi::create(). Both the device and the device context must be set to a
    non-null value then.
86

87 88
    The QRhi does not take ownership of any of the external objects.

89 90 91
    \note QRhi works with immediate contexts only. Deferred contexts are not
    used in any way.

92 93 94
    \note Regardless of using an imported or a QRhi-created device context, the
    \c ID3D11DeviceContext1 interface (Direct3D 11.1) must be supported.
    Initialization will fail otherwise.
Laszlo Agocs's avatar
Laszlo Agocs committed
95 96 97 98 99
 */

/*!
    \class QRhiD3D11NativeHandles
    \inmodule QtRhi
100
    \brief Holds the D3D device and device context used by the QRhi.
101 102 103 104

    \note The class uses \c{void *} as the type since including the COM-based
    \c{d3d11.h} headers is not acceptable here. The actual types are
    \c{ID3D11Device *} and \c{ID3D11DeviceContext *}.
Laszlo Agocs's avatar
Laszlo Agocs committed
105 106 107 108 109
 */

/*!
    \class QRhiD3D11TextureNativeHandles
    \inmodule QtRhi
110
    \brief Holds the D3D texture object that is backing a QRhiTexture instance.
111 112 113 114

    \note The class uses \c{void *} as the type since including the COM-based
    \c{d3d11.h} headers is not acceptable here. The actual type is
    \c{ID3D11Texture2D *}.
Laszlo Agocs's avatar
Laszlo Agocs committed
115 116
 */

117
QRhiD3D11::QRhiD3D11(QRhiD3D11InitParams *params, QRhiD3D11NativeHandles *importDevice)
118
    : ofr(this)
119
{
Laszlo Agocs's avatar
Laszlo Agocs committed
120 121 122
    if (params->resourceSharingHost)
        rsh = QRhiResourceSharingHostPrivate::get(params->resourceSharingHost);

123 124
    debugLayer = params->enableDebugLayer;
    importedDevice = importDevice != nullptr;
125
    if (importedDevice) {
126 127 128 129 130 131 132 133 134 135
        dev = reinterpret_cast<ID3D11Device *>(importDevice->dev);
        if (dev) {
            ID3D11DeviceContext *ctx = reinterpret_cast<ID3D11DeviceContext *>(importDevice->context);
            if (SUCCEEDED(ctx->QueryInterface(IID_ID3D11DeviceContext1, reinterpret_cast<void **>(&context)))) {
                // get rid of the ref added by QueryInterface
                ctx->Release();
            } else {
                qWarning("ID3D11DeviceContext1 not supported by context, cannot import");
                importedDevice = false;
            }
136
        } else {
137
            qWarning("No ID3D11Device given, cannot import");
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
            importedDevice = false;
        }
    }
}

static QString comErrorMessage(HRESULT hr)
{
#ifndef Q_OS_WINRT
    const _com_error comError(hr);
#else
    const _com_error comError(hr, nullptr);
#endif
    QString result = QLatin1String("Error 0x") + QString::number(ulong(hr), 16);
    if (const wchar_t *msg = comError.ErrorMessage())
        result += QLatin1String(": ") + QString::fromWCharArray(msg);
    return result;
}

static inline uint aligned(uint v, uint byteAlign)
{
    return (v + byteAlign - 1) & ~(byteAlign - 1);
}

161
bool QRhiD3D11::create(QRhi::Flags flags)
162
{
163 164
    Q_UNUSED(flags);

165 166
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);

167
    uint devFlags = 0;
168
    if (debugLayer)
169
        devFlags |= D3D11_CREATE_DEVICE_DEBUG;
170

171 172 173
    HRESULT hr = CreateDXGIFactory2(0, IID_IDXGIFactory2, reinterpret_cast<void **>(&dxgiFactory));
    if (FAILED(hr)) {
        qWarning("Failed to create DXGI factory: %s", qPrintable(comErrorMessage(hr)));
174
        return false;
175 176
    }

177
    if (!importedDevice) {
Laszlo Agocs's avatar
Laszlo Agocs committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        if (!rsh || !rsh->d_d3d11.dev) {
            IDXGIAdapter1 *adapterToUse = nullptr;
            IDXGIAdapter1 *adapter;
            int requestedAdapterIndex = -1;
            if (qEnvironmentVariableIsSet("QT_D3D_ADAPTER_INDEX"))
                requestedAdapterIndex = qEnvironmentVariableIntValue("QT_D3D_ADAPTER_INDEX");
            for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
                DXGI_ADAPTER_DESC1 desc;
                adapter->GetDesc1(&desc);
                const QString name = QString::fromUtf16((char16_t *) desc.Description);
                qDebug("Adapter %d: '%s' (flags 0x%x)", adapterIndex, qPrintable(name), desc.Flags);
                if (!adapterToUse && (requestedAdapterIndex < 0 || requestedAdapterIndex == adapterIndex)) {
                    adapterToUse = adapter;
                    qDebug("  using this adapter");
                } else {
                    adapter->Release();
                }
            }
            if (!adapterToUse) {
                qWarning("No adapter");
                return false;
            }

            ID3D11DeviceContext *ctx = nullptr;
            HRESULT hr = D3D11CreateDevice(adapterToUse, D3D_DRIVER_TYPE_UNKNOWN, nullptr, devFlags,
                                           nullptr, 0, D3D11_SDK_VERSION,
                                           &dev, &featureLevel, &ctx);
            adapterToUse->Release();
            if (FAILED(hr)) {
                qWarning("Failed to create D3D11 device and context: %s", qPrintable(comErrorMessage(hr)));
                return false;
            }
            if (SUCCEEDED(ctx->QueryInterface(IID_ID3D11DeviceContext1, reinterpret_cast<void **>(&context)))) {
                ctx->Release();
212
            } else {
Laszlo Agocs's avatar
Laszlo Agocs committed
213 214
                qWarning("ID3D11DeviceContext1 not supported");
                return false;
215 216
            }

Laszlo Agocs's avatar
Laszlo Agocs committed
217 218 219 220
            if (rsh) {
                rsh->d_d3d11.dev = dev;
                rsh->d_d3d11.context = context;
            }
221
        } else {
Laszlo Agocs's avatar
Laszlo Agocs committed
222 223 224
            dev = reinterpret_cast<ID3D11Device *>(rsh->d_d3d11.dev);
            context = reinterpret_cast<ID3D11DeviceContext1 *>(rsh->d_d3d11.context);
            featureLevel = dev->GetFeatureLevel();
225 226 227 228 229
        }
    } else {
        Q_ASSERT(dev && context);
        featureLevel = dev->GetFeatureLevel();
    }
230

231 232
    if (FAILED(context->QueryInterface(IID_ID3DUserDefinedAnnotation, reinterpret_cast<void **>(&annotations))))
        annotations = nullptr;
233

234 235 236
    nativeHandlesStruct.dev = dev;
    nativeHandlesStruct.context = context;

Laszlo Agocs's avatar
Laszlo Agocs committed
237
    if (rsh) {
238 239
        qDebug("Attached to QRhiResourceSharingHost %p, currently %d other QRhi instances on ID3D11Device %p",
               rsh, rsh->rhiCount, dev);
Laszlo Agocs's avatar
Laszlo Agocs committed
240
        rsh->rhiCount += 1;
Laszlo Agocs's avatar
Laszlo Agocs committed
241
    }
Laszlo Agocs's avatar
Laszlo Agocs committed
242

243
    return true;
244 245 246 247
}

void QRhiD3D11::destroy()
{
248 249
    finishActiveReadbacks();

Laszlo Agocs's avatar
Laszlo Agocs committed
250 251
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);

252 253 254 255 256
    if (annotations) {
        annotations->Release();
        annotations = nullptr;
    }

257
    if (!importedDevice) {
258
        if (context) {
Laszlo Agocs's avatar
Laszlo Agocs committed
259 260
            if (!rsh || rsh->d_d3d11.context != context)
                context->Release();
261 262 263
            context = nullptr;
        }
        if (dev) {
Laszlo Agocs's avatar
Laszlo Agocs committed
264 265
            if (!rsh || rsh->d_d3d11.dev != dev)
                dev->Release();
266 267 268
            dev = nullptr;
        }
    }
269

Laszlo Agocs's avatar
Laszlo Agocs committed
270
    if (rsh) {
271
        if (--rsh->rhiCount == 0) {
Laszlo Agocs's avatar
Laszlo Agocs committed
272 273 274 275 276
            if (rsh->d_d3d11.context) {
                reinterpret_cast<ID3D11DeviceContext1 *>(rsh->d_d3d11.context)->Release();
                rsh->d_d3d11.context = nullptr;
            }
            if (rsh->d_d3d11.dev) {
277 278 279 280 281
                ID3D11Device *rshDev = reinterpret_cast<ID3D11Device *>(rsh->d_d3d11.dev);
#if 0
                reportLiveObjects(rshDev); // "Refcount" > 0 means that object was not released correctly
#endif
                rshDev->Release();
Laszlo Agocs's avatar
Laszlo Agocs committed
282 283 284 285 286
                rsh->d_d3d11.dev = nullptr;
            }
        }
    }

287 288 289
    if (dxgiFactory) {
        dxgiFactory->Release();
        dxgiFactory = nullptr;
290 291 292
    }
}

293 294 295 296 297 298 299 300 301 302
void QRhiD3D11::reportLiveObjects(ID3D11Device *device)
{
    // this works only when params.enableDebugLayer was true
    ID3D11Debug *debug;
    if (SUCCEEDED(device->QueryInterface(IID_ID3D11Debug, reinterpret_cast<void **>(&debug)))) {
        debug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
        debug->Release();
    }
}

303 304
QVector<int> QRhiD3D11::supportedSampleCounts() const
{
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    return { 1, 2, 4, 8 };
}

DXGI_SAMPLE_DESC QRhiD3D11::effectiveSampleCount(int sampleCount) const
{
    DXGI_SAMPLE_DESC desc;
    desc.Count = 1;
    desc.Quality = 0;

    // Stay compatible with QSurfaceFormat and friends where samples == 0 means the same as 1.
    int s = qBound(1, sampleCount, 64);

    if (!supportedSampleCounts().contains(s)) {
        qWarning("Attempted to set unsupported sample count %d", sampleCount);
        return desc;
    }

    desc.Count = s;
    desc.Quality = s > 1 ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0;
    return desc;
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
}

QRhiSwapChain *QRhiD3D11::createSwapChain()
{
    return new QD3D11SwapChain(this);
}

QRhiBuffer *QRhiD3D11::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, int size)
{
    return new QD3D11Buffer(this, type, usage, size);
}

int QRhiD3D11::ubufAlignment() const
{
    return 256;
}

bool QRhiD3D11::isYUpInFramebuffer() const
{
    return false;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
347 348 349 350 351
bool QRhiD3D11::isYUpInNDC() const
{
    return true;
}

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
QMatrix4x4 QRhiD3D11::clipSpaceCorrMatrix() const
{
    // Like with Vulkan, but Y is already good.

    static QMatrix4x4 m;
    if (m.isIdentity()) {
        // NB the ctor takes row-major
        m = QMatrix4x4(1.0f, 0.0f, 0.0f, 0.0f,
                       0.0f, 1.0f, 0.0f, 0.0f,
                       0.0f, 0.0f, 0.5f, 0.5f,
                       0.0f, 0.0f, 0.0f, 1.0f);
    }
    return m;
}

367
bool QRhiD3D11::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
368
{
369 370
    Q_UNUSED(flags);

371 372 373 374 375 376
    if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ASTC_12x12)
        return false;

    return true;
}

377 378 379 380
bool QRhiD3D11::isFeatureSupported(QRhi::Feature feature) const
{
    switch (feature) {
    case QRhi::MultisampleTexture:
381
        return true;
382 383
    case QRhi::MultisampleRenderBuffer:
        return true;
384 385
    case QRhi::DebugMarkers:
        return annotations != nullptr;
386
    case QRhi::Timestamps:
387
        return true;
388 389 390 391
    case QRhi::Instancing:
        return true;
    case QRhi::CustomInstanceStepRate:
        return true;
392 393
    case QRhi::PrimitiveRestart:
        return true;
394 395 396 397
    case QRhi::GeometryShaders:
        return false; // for now
    case QRhi::TessellationShaders:
        return false; // for now
398 399 400 401 402 403
    default:
        Q_UNREACHABLE();
        return false;
    }
}

404 405 406 407 408 409 410 411 412 413 414 415 416
int QRhiD3D11::resourceSizeLimit(QRhi::ResourceSizeLimit limit) const
{
    switch (limit) {
    case QRhi::TextureSizeMin:
        return 1;
    case QRhi::TextureSizeMax:
        return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
    default:
        Q_UNREACHABLE();
        return 0;
    }
}

417
const QRhiNativeHandles *QRhiD3D11::nativeHandles()
418 419 420 421
{
    return &nativeHandlesStruct;
}

422
QRhiRenderBuffer *QRhiD3D11::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
423
                                                int sampleCount, QRhiRenderBuffer::Flags flags)
424
{
Laszlo Agocs's avatar
Laszlo Agocs committed
425
    return new QD3D11RenderBuffer(this, type, pixelSize, sampleCount, flags);
426 427
}

Laszlo Agocs's avatar
Laszlo Agocs committed
428 429
QRhiTexture *QRhiD3D11::createTexture(QRhiTexture::Format format, const QSize &pixelSize,
                                      int sampleCount, QRhiTexture::Flags flags)
430
{
Laszlo Agocs's avatar
Laszlo Agocs committed
431
    return new QD3D11Texture(this, format, pixelSize, sampleCount, flags);
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
}

QRhiSampler *QRhiD3D11::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
                                      QRhiSampler::Filter mipmapMode,
                                      QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
{
    return new QD3D11Sampler(this, magFilter, minFilter, mipmapMode, u, v, w);
}

QRhiTextureRenderTarget *QRhiD3D11::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
                                                              QRhiTextureRenderTarget::Flags flags)
{
    return new QD3D11TextureRenderTarget(this, desc, flags);
}

QRhiGraphicsPipeline *QRhiD3D11::createGraphicsPipeline()
{
    return new QD3D11GraphicsPipeline(this);
}

QRhiShaderResourceBindings *QRhiD3D11::createShaderResourceBindings()
{
    return new QD3D11ShaderResourceBindings(this);
}

void QRhiD3D11::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps, QRhiShaderResourceBindings *srb)
{
    Q_ASSERT(inPass);

Laszlo Agocs's avatar
Laszlo Agocs committed
461
    QD3D11GraphicsPipeline *psD = QRHI_RES(QD3D11GraphicsPipeline, ps);
462
    if (!srb)
Laszlo Agocs's avatar
Laszlo Agocs committed
463
        srb = psD->m_shaderResourceBindings;
464 465 466 467

    QD3D11ShaderResourceBindings *srbD = QRHI_RES(QD3D11ShaderResourceBindings, srb);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);

468
    bool srbUpdate = false;
469
    for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
470
        const QRhiShaderResourceBindingPrivate *b = QRhiShaderResourceBindingPrivate::get(&srbD->sortedBindings[i]);
471
        QD3D11ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
472
        switch (b->type) {
Laszlo Agocs's avatar
Laszlo Agocs committed
473
        case QRhiShaderResourceBinding::UniformBuffer:
474
        {
475
            QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, b->u.ubuf.buf);
476 477 478 479 480 481
            if (bufD->m_type == QRhiBuffer::Dynamic)
                executeBufferHostWritesForCurrentFrame(bufD);

            if (bufD->generation != bd.ubuf.generation) {
                srbUpdate = true;
                bd.ubuf.generation = bufD->generation;
482
            }
483
        }
484
            break;
Laszlo Agocs's avatar
Laszlo Agocs committed
485
        case QRhiShaderResourceBinding::SampledTexture:
486
        {
487 488
            QD3D11Texture *texD = QRHI_RES(QD3D11Texture, b->u.stex.tex);
            QD3D11Sampler *samplerD = QRHI_RES(QD3D11Sampler, b->u.stex.sampler);
489 490
            if (texD->generation != bd.stex.texGeneration
                    || samplerD->generation != bd.stex.samplerGeneration)
491
            {
492 493 494
                srbUpdate = true;
                bd.stex.texGeneration = texD->generation;
                bd.stex.samplerGeneration = samplerD->generation;
495
            }
496
        }
497 498 499 500 501 502
            break;
        default:
            Q_UNREACHABLE();
            break;
        }
    }
503

504
    if (srbUpdate)
505 506 507 508 509
        updateShaderResourceBindings(srbD);

    const bool pipelineChanged = cbD->currentPipeline != ps || cbD->currentPipelineGeneration != psD->generation;
    const bool srbChanged = cbD->currentSrb != srb || cbD->currentSrbGeneration != srbD->generation;

510
    if (pipelineChanged || srbChanged || srbUpdate) {
511 512 513 514 515 516 517 518 519
        cbD->currentPipeline = ps;
        cbD->currentPipelineGeneration = psD->generation;
        cbD->currentSrb = srb;
        cbD->currentSrbGeneration = srbD->generation;

        QD3D11CommandBuffer::Command cmd;
        cmd.cmd = QD3D11CommandBuffer::Command::BindGraphicsPipeline;
        cmd.args.bindGraphicsPipeline.ps = psD;
        cmd.args.bindGraphicsPipeline.srb = srbD;
520
        cmd.args.bindGraphicsPipeline.srbOnlyChange = !pipelineChanged;
521 522 523 524
        cbD->commands.append(cmd);
    }
}

525 526
void QRhiD3D11::setVertexInput(QRhiCommandBuffer *cb, int startBinding, const QVector<QRhiCommandBuffer::VertexInput> &bindings,
                               QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
527 528 529 530
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);

531
    bool needsBindVBuf = false;
532
    for (int i = 0, ie = bindings.count(); i != ie; ++i) {
533 534
        const int inputSlot = startBinding + i;
        QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, bindings[i].first);
Laszlo Agocs's avatar
Laszlo Agocs committed
535 536
        Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
        if (bufD->m_type == QRhiBuffer::Dynamic)
537
            executeBufferHostWritesForCurrentFrame(bufD);
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

        if (cbD->currentVertexBuffers[inputSlot] != bufD->buffer
                || cbD->currentVertexOffsets[inputSlot] != bindings[i].second)
        {
            needsBindVBuf = true;
            cbD->currentVertexBuffers[inputSlot] = bufD->buffer;
            cbD->currentVertexOffsets[inputSlot] = bindings[i].second;
        }
    }

    if (needsBindVBuf) {
        QD3D11CommandBuffer::Command cmd;
        cmd.cmd = QD3D11CommandBuffer::Command::BindVertexBuffers;
        cmd.args.bindVertexBuffers.startSlot = startBinding;
        cmd.args.bindVertexBuffers.slotCount = bindings.count();
Laszlo Agocs's avatar
Laszlo Agocs committed
553 554
        const QVector<QRhiVertexInputBinding> inputBindings =
                QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline)->m_vertexInputLayout.bindings();
555 556 557 558
        for (int i = 0, ie = bindings.count(); i != ie; ++i) {
            QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, bindings[i].first);
            cmd.args.bindVertexBuffers.buffers[i] = bufD->buffer;
            cmd.args.bindVertexBuffers.offsets[i] = bindings[i].second;
Laszlo Agocs's avatar
Laszlo Agocs committed
559
            cmd.args.bindVertexBuffers.strides[i] = inputBindings[i].stride();
560 561
        }
        cbD->commands.append(cmd);
562 563 564 565
    }

    if (indexBuf) {
        QD3D11Buffer *ibufD = QRHI_RES(QD3D11Buffer, indexBuf);
Laszlo Agocs's avatar
Laszlo Agocs committed
566 567
        Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
        if (ibufD->m_type == QRhiBuffer::Dynamic)
568
            executeBufferHostWritesForCurrentFrame(ibufD);
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586

        const DXGI_FORMAT dxgiFormat = indexFormat == QRhiCommandBuffer::IndexUInt16 ? DXGI_FORMAT_R16_UINT
                                                                                     : DXGI_FORMAT_R32_UINT;
        if (cbD->currentIndexBuffer != ibufD->buffer
                || cbD->currentIndexOffset != indexOffset
                || cbD->currentIndexFormat != dxgiFormat)
        {
            cbD->currentIndexBuffer = ibufD->buffer;
            cbD->currentIndexOffset = indexOffset;
            cbD->currentIndexFormat = dxgiFormat;

            QD3D11CommandBuffer::Command cmd;
            cmd.cmd = QD3D11CommandBuffer::Command::BindIndexBuffer;
            cmd.args.bindIndexBuffer.buffer = ibufD->buffer;
            cmd.args.bindIndexBuffer.offset = indexOffset;
            cmd.args.bindIndexBuffer.format = dxgiFormat;
            cbD->commands.append(cmd);
        }
587 588 589 590 591 592 593 594 595 596
    }
}

void QRhiD3D11::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    Q_ASSERT(cbD->currentTarget);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::Viewport;
Laszlo Agocs's avatar
Laszlo Agocs committed
597 598
    const QVector4D r = viewport.viewport();
    cmd.args.viewport.x = r.x();
Laszlo Agocs's avatar
Laszlo Agocs committed
599
    // d3d expects top-left, QRhiViewport is bottom-left
Laszlo Agocs's avatar
Laszlo Agocs committed
600 601 602
    cmd.args.viewport.y = cbD->currentTarget->sizeInPixels().height() - (r.y() + r.w());
    cmd.args.viewport.w = r.z();
    cmd.args.viewport.h = r.w();
Laszlo Agocs's avatar
Laszlo Agocs committed
603 604
    cmd.args.viewport.d0 = viewport.minDepth();
    cmd.args.viewport.d1 = viewport.maxDepth();
605 606 607 608 609 610 611 612 613 614
    cbD->commands.append(cmd);
}

void QRhiD3D11::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    Q_ASSERT(cbD->currentTarget);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::Scissor;
Laszlo Agocs's avatar
Laszlo Agocs committed
615 616
    const QVector4D r = scissor.scissor();
    cmd.args.scissor.x = r.x();
617
    // d3d expects top-left, QRhiScissor is bottom-left
Laszlo Agocs's avatar
Laszlo Agocs committed
618 619 620
    cmd.args.scissor.y = cbD->currentTarget->sizeInPixels().height() - (r.y() + r.w());
    cmd.args.scissor.w = r.z();
    cmd.args.scissor.h = r.w();
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    cbD->commands.append(cmd);
}

void QRhiD3D11::setBlendConstants(QRhiCommandBuffer *cb, const QVector4D &c)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::BlendConstants;
    cmd.args.blendConstants.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline);
    memcpy(cmd.args.blendConstants.c, &c, 4 * sizeof(float));
    cbD->commands.append(cmd);
}

void QRhiD3D11::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::StencilRef;
    cmd.args.stencilRef.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline);
    cmd.args.stencilRef.ref = refValue;
    cbD->commands.append(cmd);
}

void QRhiD3D11::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
                     quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::Draw;
    cmd.args.draw.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline);
    cmd.args.draw.vertexCount = vertexCount;
    cmd.args.draw.instanceCount = instanceCount;
    cmd.args.draw.firstVertex = firstVertex;
    cmd.args.draw.firstInstance = firstInstance;
    cbD->commands.append(cmd);
}

void QRhiD3D11::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
                            quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::DrawIndexed;
    cmd.args.drawIndexed.ps = QRHI_RES(QD3D11GraphicsPipeline, cbD->currentPipeline);
    cmd.args.drawIndexed.indexCount = indexCount;
    cmd.args.drawIndexed.instanceCount = instanceCount;
    cmd.args.drawIndexed.firstIndex = firstIndex;
    cmd.args.drawIndexed.vertexOffset = vertexOffset;
    cmd.args.drawIndexed.firstInstance = firstInstance;
    cbD->commands.append(cmd);
}

677 678
void QRhiD3D11::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
{
679
    if (!debugMarkers || !annotations)
680 681
        return;

682 683 684 685 686 687
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::DebugMarkBegin;
    strncpy(cmd.args.debugMark.s, name.constData(), sizeof(cmd.args.debugMark.s));
    cmd.args.debugMark.s[sizeof(cmd.args.debugMark.s) - 1] = '\0';
    cbD->commands.append(cmd);
688 689 690 691
}

void QRhiD3D11::debugMarkEnd(QRhiCommandBuffer *cb)
{
692
    if (!debugMarkers || !annotations)
693 694
        return;

695 696 697 698
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::DebugMarkEnd;
    cbD->commands.append(cmd);
699 700 701 702
}

void QRhiD3D11::debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg)
{
703
    if (!debugMarkers || !annotations)
704 705
        return;

706 707 708 709 710 711
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    QD3D11CommandBuffer::Command cmd;
    cmd.cmd = QD3D11CommandBuffer::Command::DebugMarkMsg;
    strncpy(cmd.args.debugMark.s, msg.constData(), sizeof(cmd.args.debugMark.s));
    cmd.args.debugMark.s[sizeof(cmd.args.debugMark.s) - 1] = '\0';
    cbD->commands.append(cmd);
712 713
}

714
QRhi::FrameOpResult QRhiD3D11::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags)
715
{
716
    Q_UNUSED(flags);
717 718
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);

719 720 721 722
    Q_ASSERT(!inFrame);
    inFrame = true;

    QD3D11SwapChain *swapChainD = QRHI_RES(QD3D11SwapChain, swapChain);
Laszlo Agocs's avatar
Laszlo Agocs committed
723
    contextState.currentSwapChain = swapChainD;
724 725
    const int currentFrameSlot = swapChainD->currentFrameSlot;
    QRhiProfilerPrivate *rhiP = profilerPrivateOrNull();
Laszlo Agocs's avatar
Laszlo Agocs committed
726 727 728 729 730 731

    if (swapChainD->timestampActive[currentFrameSlot]) {
        ID3D11Query *tsDisjoint = swapChainD->timestampDisjointQuery[currentFrameSlot];
        const int tsIdx = QD3D11SwapChain::BUFFER_COUNT * currentFrameSlot;
        ID3D11Query *tsStart = swapChainD->timestampQuery[tsIdx];
        ID3D11Query *tsEnd = swapChainD->timestampQuery[tsIdx + 1];
732 733 734
        quint64 timestamps[2];
        D3D11_QUERY_DATA_TIMESTAMP_DISJOINT dj;
        bool ok = true;
Laszlo Agocs's avatar
Laszlo Agocs committed
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        ok &= context->GetData(tsDisjoint, &dj, sizeof(dj), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
        ok &= context->GetData(tsEnd, &timestamps[1], sizeof(quint64), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
        // this above is often not ready, not even in frame_where_recorded+2,
        // not clear why. so make the whole thing async and do not touch the
        // queries until they are finally all available in frame this+2 or
        // this+4 or ...
        ok &= context->GetData(tsStart, &timestamps[0], sizeof(quint64), D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK;
        if (ok) {
            if (!dj.Disjoint && dj.Frequency) {
                const float elapsedMs = (timestamps[1] - timestamps[0]) / float(dj.Frequency) * 1000.0f;
                // finally got a value, just report it, the profiler cares about min/max/avg anyway
                QRHI_PROF_F(swapChainFrameGpuTime(swapChain, elapsedMs));
            }
            swapChainD->timestampActive[currentFrameSlot] = false;
        } // else leave timestampActive set to true, will retry in a subsequent beginFrame
750 751
    }

752 753
    swapChainD->cb.resetState();

754
    swapChainD->rt.d.rtv[0] = swapChainD->sampleDesc.Count > 1 ?
755
                swapChainD->msaaRtv[currentFrameSlot] : swapChainD->rtv[currentFrameSlot];
756
    swapChainD->rt.d.dsv = swapChainD->ds ? swapChainD->ds->dsv : nullptr;
757

758 759
    QRHI_PROF_F(beginSwapChainFrame(swapChain));

760
    lock.unlock();
761 762
    finishActiveReadbacks();

763 764 765
    return QRhi::FrameOpSuccess;
}

766
QRhi::FrameOpResult QRhiD3D11::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
767
{
768 769
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);

770 771 772 773
    Q_ASSERT(inFrame);
    inFrame = false;

    QD3D11SwapChain *swapChainD = QRHI_RES(QD3D11SwapChain, swapChain);
774
    Q_ASSERT(contextState.currentSwapChain = swapChainD);
775 776 777 778 779 780
    const int currentFrameSlot = swapChainD->currentFrameSlot;

    ID3D11Query *tsDisjoint = swapChainD->timestampDisjointQuery[currentFrameSlot];
    const int tsIdx = QD3D11SwapChain::BUFFER_COUNT * currentFrameSlot;
    ID3D11Query *tsStart = swapChainD->timestampQuery[tsIdx];
    ID3D11Query *tsEnd = swapChainD->timestampQuery[tsIdx + 1];
781
    const bool recordTimestamps = tsDisjoint && tsStart && tsEnd && !swapChainD->timestampActive[currentFrameSlot];
782

Laszlo Agocs's avatar
Laszlo Agocs committed
783
    // send all commands to the context
784
    if (recordTimestamps)
Laszlo Agocs's avatar
Laszlo Agocs committed
785
        executeCommandBuffer(&swapChainD->cb, swapChainD);
786
    else
Laszlo Agocs's avatar
Laszlo Agocs committed
787
        executeCommandBuffer(&swapChainD->cb);
788

789
    if (swapChainD->sampleDesc.Count > 1) {
790 791
        context->ResolveSubresource(swapChainD->tex[currentFrameSlot], 0,
                                    swapChainD->msaaTex[currentFrameSlot], 0,
792 793 794
                                    swapChainD->colorFormat);
    }

795 796
    // this is here because we want to include the time spent on the resolve as well
    if (recordTimestamps) {
797 798
        context->End(tsEnd);
        context->End(tsDisjoint);
Laszlo Agocs's avatar
Laszlo Agocs committed
799
        swapChainD->timestampActive[currentFrameSlot] = true;
800 801
    }

802 803 804 805
    QRhiProfilerPrivate *rhiP = profilerPrivateOrNull();
    // this must be done before the Present
    QRHI_PROF_F(endSwapChainFrame(swapChain, swapChainD->frameCount + 1));

806 807 808 809 810
    if (!flags.testFlag(QRhi::SkipPresent)) {
        const UINT presentFlags = 0;
        HRESULT hr = swapChainD->swapChain->Present(swapChainD->swapInterval, presentFlags);
        if (FAILED(hr))
            qWarning("Failed to present: %s", qPrintable(comErrorMessage(hr)));
811

812 813 814 815 816
        // move on to the next buffer
        swapChainD->currentFrameSlot = (swapChainD->currentFrameSlot + 1) % QD3D11SwapChain::BUFFER_COUNT;
    } else {
        context->Flush();
    }
817

818
    swapChainD->frameCount += 1;
Laszlo Agocs's avatar
Laszlo Agocs committed
819
    contextState.currentSwapChain = nullptr;
820 821 822
    return QRhi::FrameOpSuccess;
}

823 824
QRhi::FrameOpResult QRhiD3D11::beginOffscreenFrame(QRhiCommandBuffer **cb)
{
825 826 827 828 829 830 831 832
    Q_ASSERT(!inFrame);
    inFrame = true;
    ofr.active = true;

    ofr.cbWrapper.resetState();
    *cb = &ofr.cbWrapper;

    return QRhi::FrameOpSuccess;
833 834
}

835
QRhi::FrameOpResult QRhiD3D11::endOffscreenFrame()
836
{
837 838
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);

839 840 841 842 843
    Q_ASSERT(inFrame && ofr.active);
    inFrame = false;
    ofr.active = false;

    executeCommandBuffer(&ofr.cbWrapper);
844 845

    lock.unlock();
846
    finishActiveReadbacks();
847 848

    return QRhi::FrameOpSuccess;;
849 850
}

Laszlo Agocs's avatar
Laszlo Agocs committed
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
static inline DXGI_FORMAT toD3DTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
{
    const bool srgb = flags.testFlag(QRhiTexture::sRGB);
    switch (format) {
    case QRhiTexture::RGBA8:
        return srgb ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
    case QRhiTexture::BGRA8:
        return srgb ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : DXGI_FORMAT_B8G8R8A8_UNORM;
    case QRhiTexture::R8:
        return DXGI_FORMAT_R8_UNORM;
    case QRhiTexture::R16:
        return DXGI_FORMAT_R16_UNORM;

    case QRhiTexture::D16:
        return DXGI_FORMAT_R16_TYPELESS;
    case QRhiTexture::D32:
        return DXGI_FORMAT_R32_TYPELESS;

    case QRhiTexture::BC1:
        return srgb ? DXGI_FORMAT_BC1_UNORM_SRGB : DXGI_FORMAT_BC1_UNORM;
    case QRhiTexture::BC2:
        return srgb ? DXGI_FORMAT_BC2_UNORM_SRGB : DXGI_FORMAT_BC2_UNORM;
    case QRhiTexture::BC3:
        return srgb ? DXGI_FORMAT_BC3_UNORM_SRGB : DXGI_FORMAT_BC3_UNORM;
    case QRhiTexture::BC4:
        return DXGI_FORMAT_BC4_UNORM;
    case QRhiTexture::BC5:
        return DXGI_FORMAT_BC5_UNORM;
    case QRhiTexture::BC6H:
        return DXGI_FORMAT_BC6H_UF16;
    case QRhiTexture::BC7:
        return srgb ? DXGI_FORMAT_BC7_UNORM_SRGB : DXGI_FORMAT_BC7_UNORM;

    case QRhiTexture::ETC2_RGB8:
        Q_FALLTHROUGH();
    case QRhiTexture::ETC2_RGB8A1:
        Q_FALLTHROUGH();
    case QRhiTexture::ETC2_RGBA8:
        qWarning("QRhiD3D11 does not support ETC2 textures");
        return DXGI_FORMAT_R8G8B8A8_UNORM;

    case QRhiTexture::ASTC_4x4:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_5x4:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_5x5:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_6x5:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_6x6:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_8x5:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_8x6:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_8x8:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_10x5:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_10x6:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_10x8:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_10x10:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_12x10:
        Q_FALLTHROUGH();
    case QRhiTexture::ASTC_12x12:
        qWarning("QRhiD3D11 does not support ASTC textures");
        return DXGI_FORMAT_R8G8B8A8_UNORM;

    default:
        Q_UNREACHABLE();
        return DXGI_FORMAT_R8G8B8A8_UNORM;
    }
}

static inline QRhiTexture::Format colorTextureFormatFromDxgiFormat(DXGI_FORMAT format, QRhiTexture::Flags *flags)
{
    switch (format) {
    case DXGI_FORMAT_R8G8B8A8_UNORM:
        return QRhiTexture::RGBA8;
    case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
        if (flags)
            (*flags) |= QRhiTexture::sRGB;
        return QRhiTexture::RGBA8;
    case DXGI_FORMAT_B8G8R8A8_UNORM:
        return QRhiTexture::BGRA8;
    case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
        if (flags)
            (*flags) |= QRhiTexture::sRGB;
        return QRhiTexture::BGRA8;
    case DXGI_FORMAT_R8_UNORM:
        return QRhiTexture::R8;
    case DXGI_FORMAT_R16_UNORM:
        return QRhiTexture::R16;
    default: // this cannot assert, must warn and return unknown
        qWarning("DXGI_FORMAT %d is not a recognized uncompressed color format", format);
        break;
    }
    return QRhiTexture::UnknownFormat;
}

static inline bool isDepthTextureFormat(QRhiTexture::Format format)
955
{
Laszlo Agocs's avatar
Laszlo Agocs committed
956 957 958 959 960
    switch (format) {
    case QRhiTexture::Format::D16:
        Q_FALLTHROUGH();
    case QRhiTexture::Format::D32:
        return true;
961

Laszlo Agocs's avatar
Laszlo Agocs committed
962 963 964 965 966
    default:
        return false;
    }
}

967 968
QRhi::FrameOpResult QRhiD3D11::finish()
{
969
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);
970
    Q_ASSERT(!inPass);
971

Laszlo Agocs's avatar
Laszlo Agocs committed
972 973 974 975 976 977 978
    if (inFrame) {
        if (ofr.active) {
            Q_ASSERT(!contextState.currentSwapChain);
            executeCommandBuffer(&ofr.cbWrapper);
            ofr.cbWrapper.resetCommands();
        } else {
            Q_ASSERT(contextState.currentSwapChain);
979
            executeCommandBuffer(&contextState.currentSwapChain->cb, contextState.currentSwapChain);
Laszlo Agocs's avatar
Laszlo Agocs committed
980 981 982
            contextState.currentSwapChain->cb.resetCommands();
        }
    }
983 984

    lock.unlock();
985
    finishActiveReadbacks();
986

987 988 989
    return QRhi::FrameOpSuccess;
}

990
void QRhiD3D11::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
991
{
992
    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
993
    QRhiResourceUpdateBatchPrivate *ud = QRhiResourceUpdateBatchPrivate::get(resourceUpdates);
994
    QRhiProfilerPrivate *rhiP = profilerPrivateOrNull();
995 996 997

    for (const QRhiResourceUpdateBatchPrivate::DynamicBufferUpdate &u : ud->dynamicBufferUpdates) {
        QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
998
        Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
999 1000 1001 1002 1003 1004
        memcpy(bufD->dynBuf.data() + u.offset, u.data.constData(), u.data.size());
        bufD->hasPendingDynamicUpdates = true;
    }

    for (const QRhiResourceUpdateBatchPrivate::StaticBufferUpload &u : ud->staticBufferUploads) {
        QD3D11Buffer *bufD = QRHI_RES(QD3D11Buffer, u.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
1005
        Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
1006
        Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
1007 1008 1009 1010 1011 1012
        QD3D11CommandBuffer::Command cmd;
        cmd.cmd = QD3D11CommandBuffer::Command::UpdateSubRes;
        cmd.args.updateSubRes.dst = bufD->buffer;
        cmd.args.updateSubRes.dstSubRes = 0;
        cmd.args.updateSubRes.src = cbD->retainData(u.data);
        cmd.args.updateSubRes.srcRowPitch = 0;
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        // Specify the region (even when offset is 0 and all data is provided)
        // since the ID3D11Buffer's size is rounded up to be a multiple of 256
        // while the data we have has the original size.
        D3D11_BOX box;
        box.left = u.offset;
        box.top = box.front = 0;
        box.back = box.bottom = 1;
        box.right = u.offset + u.data.size(); // no -1: right, bottom, back are exclusive, see D3D11_BOX doc
        cmd.args.updateSubRes.hasDstBox = true;
        cmd.args.updateSubRes.dstBox = box;
1023
        cbD->commands.append(cmd);
1024 1025 1026 1027
    }

    for (const QRhiResourceUpdateBatchPrivate::TextureUpload &u : ud->textureUploads) {
        QD3D11Texture *texD = QRHI_RES(QD3D11Texture, u.tex);
1028 1029 1030 1031 1032 1033
        const QVector<QRhiTextureLayer> layers = u.desc.layers();
        for (int layer = 0, layerCount = layers.count(); layer != layerCount; ++layer) {
            const QRhiTextureLayer &layerDesc(layers[layer]);
            const QVector<QRhiTextureMipLevel> mipImages = layerDesc.mipImages();
            for (int level = 0, levelCount = mipImages.count(); level != levelCount; ++level) {
                const QRhiTextureMipLevel &mipDesc(mipImages[level]);
1034
                UINT subres = D3D11CalcSubresource(level, layer, texD->mipLevelCount);
1035
                const QPoint dp = mipDesc.destinationTopLeft();
1036 1037 1038 1039
                D3D11_BOX box;
                box.front = 0;
                // back, right, bottom are exclusive
                box.back = 1;
1040 1041 1042 1043 1044
                QD3D11CommandBuffer::Command cmd;
                cmd.cmd = QD3D11CommandBuffer::Command::UpdateSubRes;
                cmd.args.updateSubRes.dst = texD->tex;
                cmd.args.updateSubRes.dstSubRes = subres;

1045 1046 1047
                if (!mipDesc.image().isNull()) {
                    QImage img = mipDesc.image();
                    QSize size = img.size();
1048
                    int bpl = img.bytesPerLine();
1049 1050 1051 1052
                    if (!mipDesc.sourceSize().isEmpty() || !mipDesc.sourceTopLeft().isNull()) {
                        const QPoint sp = mipDesc.sourceTopLeft();
                        if (!mipDesc.sourceSize().isEmpty())
                            size = mipDesc.sourceSize();
1053
                        if (img.depth() == 32) {
1054
                            const int offset = sp.y() * img.bytesPerLine() + sp.x() * 4;
1055
                            cmd.args.updateSubRes.src = cbD->retainImage(img) + offset;
1056
                        } else {
1057
                            img = img.copy(sp.x(), sp.y(), size.width(), size.height());
1058
                            bpl = img.bytesPerLine();
1059
                            cmd.args.updateSubRes.src = cbD->retainImage(img);
1060
                        }
1061 1062
                    } else {
                        cmd.args.updateSubRes.src = cbD->retainImage(img);
1063
                    }
1064 1065 1066 1067
                    box.left = dp.x();
                    box.top = dp.y();
                    box.right = dp.x() + size.width();
                    box.bottom = dp.y() + size.height();
1068 1069 1070
                    cmd.args.updateSubRes.hasDstBox = true;
                    cmd.args.updateSubRes.dstBox = box;
                    cmd.args.updateSubRes.srcRowPitch = bpl;
1071
                } else if (!mipDesc.compressedData().isEmpty() && isCompressedFormat(texD->m_format)) {
1072 1073
                    const QSize size = mipDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
                                                                      : mipDesc.sourceSize();
1074
                    quint32 bpl = 0;
1075
                    QSize blockDim;
1076
                    compressedFormatInfo(texD->m_format, size, &bpl, nullptr, &blockDim);
1077 1078 1079
                    // Everything must be a multiple of the block width and
                    // height, so e.g. a mip level of size 2x2 will be 4x4 when it
                    // comes to the actual data.
1080 1081 1082 1083
                    box.left = aligned(dp.x(), blockDim.width());
                    box.top = aligned(dp.y(), blockDim.height());
                    box.right = aligned(dp.x() + size.width(), blockDim.width());
                    box.bottom = aligned(dp.y() + size.height(), blockDim.height());
1084 1085
                    cmd.args.updateSubRes.hasDstBox = true;
                    cmd.args.updateSubRes.dstBox = box;
1086
                    cmd.args.updateSubRes.src = cbD->retainData(mipDesc.compressedData());
1087
                    cmd.args.updateSubRes.srcRowPitch = bpl;
1088
                }
1089
                cbD->commands.append(cmd);
1090 1091 1092 1093
            }
        }
    }

1094 1095 1096 1097
    for (const QRhiResourceUpdateBatchPrivate::TextureCopy &u : ud->textureCopies) {
        Q_ASSERT(u.src && u.dst);
        QD3D11Texture *srcD = QRHI_RES(QD3D11Texture, u.src);
        QD3D11Texture *dstD = QRHI_RES(QD3D11Texture, u.dst);
1098 1099 1100 1101 1102
        UINT srcSubRes = D3D11CalcSubresource(u.desc.sourceLevel(), u.desc.sourceLayer(), srcD->mipLevelCount);
        UINT dstSubRes = D3D11CalcSubresource(u.desc.destinationLevel(), u.desc.destinationLayer(), dstD->mipLevelCount);
        const QPoint dp = u.desc.destinationTopLeft();
        const QSize size = u.desc.pixelSize().isEmpty() ? srcD->m_pixelSize : u.desc.pixelSize();
        const QPoint sp = u.desc.sourceTopLeft();
1103
        D3D11_BOX srcBox;
1104 1105
        srcBox.left = sp.x();
        srcBox.top = sp.y();
1106 1107 1108 1109 1110
        srcBox.front = 0;
        // back, right, bottom are exclusive
        srcBox.right = srcBox.left + size.width();
        srcBox.bottom = srcBox.top + size.height();
        srcBox.back = 1;
1111 1112 1113 1114
        QD3D11CommandBuffer::Command cmd;
        cmd.cmd = QD3D11CommandBuffer::Command::CopySubRes;
        cmd.args.copySubRes.dst = dstD->tex;
        cmd.args.copySubRes.dstSubRes = dstSubRes;
1115 1116
        cmd.args.copySubRes.dstX = dp.x();
        cmd.args.copySubRes.dstY = dp.y();
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
        cmd.args.copySubRes.src = srcD->tex;
        cmd.args.copySubRes.srcSubRes = srcSubRes;
        cmd.args.copySubRes.hasSrcBox = true;
        cmd.args.copySubRes.srcBox = srcBox;
        cbD->commands.append(cmd);
    }

    for (const QRhiResourceUpdateBatchPrivate::TextureRead &u : ud->textureReadbacks) {
        ActiveReadback aRb;
        aRb.desc = u.rb;
        aRb.result = u.result;

        ID3D11Resource *src;
        DXGI_FORMAT dxgiFormat;
        QSize pixelSize;
        QRhiTexture::Format format;
        UINT subres = 0;
1134
        QD3D11Texture *texD = QRHI_RES(QD3D11Texture, u.rb.texture());
1135 1136 1137 1138 1139 1140 1141 1142
        QD3D11SwapChain *swapChainD = nullptr;

        if (texD) {
            if (texD->sampleDesc.Count > 1) {
                qWarning("Multisample texture cannot be read back");
                continue;
            }
            src = texD->tex;
Laszlo Agocs's avatar
Laszlo Agocs committed
1143
            dxgiFormat = texD->dxgiFormat;
1144
            pixelSize = u.rb.level() > 0 ? q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize) : texD->m_pixelSize;
1145
            format = texD->m_format;
1146
            subres = D3D11CalcSubresource(u.rb.level(), u.rb.layer(), texD->mipLevelCount);
1147 1148 1149
        } else {
            Q_ASSERT(contextState.currentSwapChain);
            swapChainD = QRHI_RES(QD3D11SwapChain, contextState.currentSwapChain);
1150 1151 1152 1153 1154
            if (swapChainD->sampleDesc.Count > 1) {
                // Unlike with textures, reading back a multisample swapchain image
                // has to be supported. Insert a resolve.
                QD3D11CommandBuffer::Command rcmd;
                rcmd.cmd = QD3D11CommandBuffer::Command::ResolveSubRes;
1155
                rcmd.args.resolveSubRes.dst = swapChainD->tex[swapChainD->currentFrameSlot];
1156
                rcmd.args.resolveSubRes.dstSubRes = 0;
1157
                rcmd.args.resolveSubRes.src = swapChainD->msaaTex[swapChainD->currentFrameSlot];
1158 1159 1160 1161
                rcmd.args.resolveSubRes.srcSubRes = 0;
                rcmd.args.resolveSubRes.format = swapChainD->colorFormat;
                cbD->commands.append(rcmd);
            }
1162
            src = swapChainD->tex[swapChainD->currentFrameSlot];
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
            dxgiFormat = swapChainD->colorFormat;
            pixelSize = swapChainD->pixelSize;
            format = colorTextureFormatFromDxgiFormat(dxgiFormat, nullptr);
            if (format == QRhiTexture::UnknownFormat)
                continue;
        }
        quint32 bufSize = 0;
        textureFormatInfo(format, pixelSize, nullptr, &bufSize);

        D3D11_TEXTURE2D_DESC desc;
        memset(&desc, 0, sizeof(desc));
        desc.Width = pixelSize.width();
        desc.Height = pixelSize.height();
        desc.MipLevels = 1;
        desc.ArraySize = 1;
        desc.Format = dxgiFormat;
        desc.SampleDesc.Count = 1;
        desc.Usage = D3D11_USAGE_STAGING;
        desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
        ID3D11Texture2D *stagingTex;
        HRESULT hr = dev->CreateTexture2D(&desc, nullptr, &stagingTex);
        if (FAILED(hr)) {
            qWarning("Failed to create readback staging texture: %s", qPrintable(comErrorMessage(hr)));
            return;
        }
1188 1189 1190
        QRHI_PROF_F(newReadbackBuffer(quint64(quintptr(stagingTex)),
                                      texD ? static_cast<QRhiResource *>(texD) : static_cast<QRhiResource *>(swapChainD),
                                      bufSize));
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208

        QD3D11CommandBuffer::Command cmd;
        cmd.cmd = QD3D11CommandBuffer::Command::CopySubRes;
        cmd.args.copySubRes.dst = stagingTex;
        cmd.args.copySubRes.dstSubRes = 0;
        cmd.args.copySubRes.dstX = 0;
        cmd.args.copySubRes.dstY = 0;
        cmd.args.copySubRes.src = src;
        cmd.args.copySubRes.srcSubRes = subres;
        cmd.args.copySubRes.hasSrcBox = false;
        cbD->commands.append(cmd);

        aRb.stagingTex = stagingTex;
        aRb.bufSize = bufSize;
        aRb.pixelSize = pixelSize;
        aRb.format = format;

        activeReadbacks.append(aRb);
1209 1210
    }

1211 1212 1213 1214 1215 1216 1217 1218
    for (const QRhiResourceUpdateBatchPrivate::TextureMipGen &u : ud->textureMipGens) {
        Q_ASSERT(u.tex->flags().testFlag(QRhiTexture::UsedWithGenerateMips));
        QD3D11CommandBuffer::Command cmd;
        cmd.cmd = QD3D11CommandBuffer::Command::GenMip;
        cmd.args.genMip.tex = QRHI_RES(QD3D11Texture, u.tex);
        cbD->commands.append(cmd);
    }

1219 1220 1221
    ud->free();
}

1222 1223
void QRhiD3D11::finishActiveReadbacks()
{
1224
    QMutexLocker lock(rsh ? &rsh->mtx : nullptr);
1225
    QVarLengthArray<std::function<void()>, 4> completedCallbacks;
1226
    QRhiProfilerPrivate *rhiP = profilerPrivateOrNull();
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244

    for (int i = activeReadbacks.count() - 1; i >= 0; --i) {
        const QRhiD3D11::ActiveReadback &aRb(activeReadbacks[i]);
        aRb.result->format = aRb.format;
        aRb.result->pixelSize = aRb.pixelSize;
        aRb.result->data.resize(aRb.bufSize);

        D3D11_MAPPED_SUBRESOURCE mp;
        HRESULT hr = context->Map(aRb.stagingTex, 0, D3D11_MAP_READ, 0, &mp);
        if (FAILED(hr)) {
            qWarning("Failed to map readback staging texture: %s", qPrintable(comErrorMessage(hr)));
            aRb.stagingTex->Release();
            continue;
        }
        memcpy(aRb.result->data.data(), mp.pData, aRb.result->data.size());
        context->Unmap(aRb.stagingTex, 0);

        aRb.stagingTex->Release();
1245
        QRHI_PROF_F(releaseReadbackBuffer(quint64(quintptr(aRb.stagingTex))));
1246 1247 1248 1249 1250 1251 1252

        if (aRb.result->completed)
            completedCallbacks.append(aRb.result->completed);

        activeReadbacks.removeAt(i);
    }

1253
    lock.unlock();
1254 1255 1256 1257
    for (auto f : completedCallbacks)
        f();
}

1258
static inline QD3D11RenderTargetData *rtData(QRhiRenderTarget *rt)
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
{
    switch (rt->type()) {
    case QRhiRenderTarget::RtRef:
        return &QRHI_RES(QD3D11ReferenceRenderTarget, rt)->d;
    case QRhiRenderTarget::RtTexture:
        return &QRHI_RES(QD3D11TextureRenderTarget, rt)->d;
    default:
        Q_UNREACHABLE();
        return nullptr;
    }
}

1271 1272 1273 1274 1275 1276 1277 1278 1279
void QRhiD3D11::resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
{
    Q_ASSERT(inFrame && !inPass);

    enqueueResourceUpdates(cb, resourceUpdates);
}

void QRhiD3D11::beginPass(QRhiCommandBuffer *cb,
                          QRhiRenderTarget *rt,
1280 1281 1282 1283 1284 1285 1286
                          const QRhiColorClearValue &colorClearValue,
                          const QRhiDepthStencilClearValue &depthStencilClearValue,
                          QRhiResourceUpdateBatch *resourceUpdates)
{
    Q_ASSERT(!inPass);

    if (resourceUpdates)
1287
        enqueueResourceUpdates(cb, resourceUpdates);
1288 1289 1290

    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
    bool needsColorClear = true;
1291
    bool needsDsClear = true;
1292
    QD3D11RenderTargetData *rtD = rtData(rt);
1293 1294
    if (rt->type() == QRhiRenderTarget::RtTexture) {
        QD3D11TextureRenderTarget *rtTex = QRHI_RES(QD3D11TextureRenderTarget, rt);
Laszlo Agocs's avatar
Laszlo Agocs committed
1295
        needsColorClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
1296
        needsDsClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
    }

    cbD->currentTarget = rt;

    QD3D11CommandBuffer::Command fbCmd;
    fbCmd.cmd = QD3D11CommandBuffer::Command::SetRenderTarget;
    fbCmd.args.setRenderTarget.rt = rt;
    cbD->commands.append(fbCmd);

    QD3D11CommandBuffer::Command clearCmd;
    clearCmd.cmd = QD3D11CommandBuffer::Command::Clear;
    clearCmd.args.clear.rt = rt;
    clearCmd.args.clear.mask = 0;
1310
    if (rtD->colorAttCount && needsColorClear)
1311
        clearCmd.args.clear.mask |= QD3D11CommandBuffer::Command::Color;
1312 1313
    if (rtD->dsAttCount && needsDsClear)
        clearCmd.args.clear.mask |= QD3D11CommandBuffer::Command::Depth | QD3D11CommandBuffer::Command::Stencil;
1314

Laszlo Agocs's avatar
Laszlo Agocs committed
1315 1316 1317 1318
    const QVector4D rgba = colorClearValue.rgba();
    memcpy(clearCmd.args.clear.c, &rgba, sizeof(float) * 4);
    clearCmd.args.clear.d = depthStencilClearValue.depthClearValue();
    clearCmd.args.clear.s = depthStencilClearValue.stencilClearValue();
1319 1320 1321 1322 1323 1324

    cbD->commands.append(clearCmd);

    inPass = true;
}

1325
void QRhiD3D11::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
1326 1327 1328 1329 1330
{
    Q_ASSERT(inPass);
    inPass = false;

    QD3D11CommandBuffer *cbD = QRHI_RES(QD3D11CommandBuffer, cb);
1331 1332
    if (cbD->currentTarget->type() == QRhiRenderTarget::RtTexture) {
        QD3D11TextureRenderTarget *rtTex = QRHI_RES(QD3D11TextureRenderTarget, cbD->currentTarget);
Laszlo Agocs's avatar
Laszlo Agocs committed
1333 1334 1335 1336
        const QVector<QRhiColorAttachment> colorAttachments = rtTex->m_desc.colorAttachments();
        for (int att = 0, attCount = colorAttachments.count(); att != attCount; ++att) {
            const QRhiColorAttachment &colorAtt(colorAttachments[att]);
            if (!colorAtt.resolveTexture())
1337 1338
                continue;

Laszlo Agocs's avatar
Laszlo Agocs committed
1339 1340 1341
            QD3D11Texture *dstTexD = QRHI_RES(QD3D11Texture, colorAtt.resolveTexture());
            QD3D11Texture *srcTexD = QRHI_RES(QD3D11Texture, colorAtt.texture());
            QD3D11RenderBuffer *srcRbD = QRHI_RES(QD3D11RenderBuffer, colorAtt.renderBuffer());
1342 1343 1344 1345
            Q_ASSERT(srcTexD || srcRbD);
            QD3D11CommandBuffer::Command cmd;
            cmd.cmd = QD3D11CommandBuffer::Command::ResolveSubRes;
            cmd.args.resolveSubRes.dst = dstTexD->tex;
Laszlo Agocs's avatar
Laszlo Agocs committed
1346 1347
            cmd.args.resolveSubRes.dstSubRes = D3D11CalcSubresource(colorAtt.resolveLevel(),
                                                                    colorAtt.resolveLayer(),
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
                                                                    dstTexD->mipLevelCount);
            if (srcTexD) {
                cmd.args.resolveSubRes.src = srcTexD->tex;
                if (srcTexD->dxgiFormat != dstTexD->dxgiFormat) {
                    qWarning("Resolve source and destination formats do not match");
                    continue;
                }
                if (srcTexD->sampleDesc.Count <= 1) {
                    qWarning("Cannot resolve a non-multisample texture");
                    continue;
                }
                if (srcTexD->m_pixelSize != dstTexD->m_pixelSize) {
                    qWarning("Resolve source and destination sizes do not match");
                    continue;
                }
            } else {
                cmd.args.resolveSubRes.src = srcRbD->tex;
                if (srcRbD->dxgiFormat != dstTexD->dxgiFormat) {
                    qWarning("Resolve source and destination formats do not match");
                    continue;
                }
                if (srcRbD->m_pixelSize != dstTexD->m_pixelSize) {
                    qWarning("Resolve source and destination sizes do not match");
                    continue;
                }
            }
Laszlo Agocs's avatar
Laszlo Agocs committed
1374
            cmd.args.resolveSubRes.srcSubRes = D3D11CalcSubresource(0, colorAtt.layer(), 1);
1375 1376 1377 1378 1379
            cmd.args.resolveSubRes.format = dstTexD->dxgiFormat;
            cbD->commands.append(cmd);
        }
    }

1380
    cbD->currentTarget = nullptr;
1381 1382

    if (resourceUpdates)
1383
        enqueueResourceUpdates(cb, resourceUpdates);
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
}

void QRhiD3D11::updateShaderResourceBindings(QD3D11ShaderResourceBindings *srbD)
{
    srbD->vsubufs.clear();
    srbD->vsubufoffsets.clear();
    srbD->vsubufsizes.clear();

    srbD->fsubufs.clear();
    srbD->fsubufoffsets.clear();
    srbD->fsubufsizes.clear();

    srbD->vssamplers.clear();
    srbD->vsshaderresources.clear();

    srbD->fssamplers.clear();
    srbD->fsshaderresources.clear();

    for (int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
1403
        const QRhiShaderResourceBindingPrivate *b = QRhiShaderResourceBindingPrivate::get(&srbD->sortedBindings[i]);
1404
        QD3D11ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
Laszlo Agocs's avatar