qrhi.cpp 28.3 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 38 39
/****************************************************************************
**
** 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 "qrhi_p.h"
#include <qmath.h>

Laszlo Agocs's avatar
Laszlo Agocs committed
40
#include "qrhinull_p.h"
41
#ifndef QT_NO_OPENGL
42
#include "qrhigles2_p.h"
43
#endif
44 45 46 47 48 49 50 51 52 53 54 55
#if QT_CONFIG(vulkan)
#include "qrhivulkan_p.h"
#endif
#ifdef Q_OS_WIN
#include "qrhid3d11_p.h"
#endif
#ifdef Q_OS_DARWIN
#include "qrhimetal_p.h"
#endif

QT_BEGIN_NAMESPACE

Laszlo Agocs's avatar
Laszlo Agocs committed
56 57 58
/*!
    \class QRhi
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

    \brief Accelerated 2D/3D graphics API abstraction.
 */

/*!
    \enum QRhi::Implementation
    Describes which graphics API-specific backend gets used by a QRhi instance.

    \value Null
    \value Vulkan
    \value OpenGLES2
    \value D3D11
    \value Metal
 */

/*!
    \enum QRhi::Flag
    Describes what special features to enable.

    \value EnableProfiling Enables gathering timing (CPU, GPU) and resource
    (QRhiBuffer, QRhiTexture, etc.) information and additional metadata. See
    QRhiProfiler. Avoid enabling in production builds as it may involve a
    performance penalty.

    \value EnableDebugMarkers Enables debug marker groups. Without this frame
    debugging features like making debug groups and custom resource name
    visible in external GPU debugging tools will not be available and functions
    like QRhiCommandBuffer::debugMarkBegin() will become a no-op. Avoid
    enabling in production builds as it may involve a performance penalty.
 */

/*!
    \enum QRhi::FrameOpResult
    Describes the result of operations that can have a soft failure.

    \value FrameOpSuccess Success

    \value FrameOpError Unspecified error

    \value FrameOpSwapChainOutOfDate The swapchain is in an inconsistent state
    internally. This can be recoverable by attempting to repeat the operation
    (such as, beginFrame()) later.

    \value FrameOpDeviceLost The graphics device was lost. This can be
    recoverable by attempting to repeat the operation (such as, beginFrame())
    and releasing and reinitializing all objects backed by native graphics
    resources.
 */

/*!
    \enum QRhi::Feature
    Flag values to indicate what features are supported by the backend currently in use.

    \value MultisampleTexture Textures with sample count larger than 1 are supported.
    \value MultisampleRenderBuffer Renderbuffers with sample count larger than 1 are supported.
    \value DebugMarkers Debug marker groups (and so QRhiCommandBuffer::debugMarkBegin()) are supported.
    \value Timestamps Command buffer timestamps are supported. Relevant for QRhiProfiler::gpuFrameTimes().
    \value Instancing Instanced drawing is supported.
    \value CustomInstanceStepRate Instance step rate other than 1 is supported.
 */

/*!
    \enum QRhi::ResourceSizeLimit
    Describes the resource limit to query.

    \value TextureSizeMin Minimum texture width and height. This is typically
    1. The minimum texture size is handled gracefully, meaning attempting to
    create a texture with an empty size will instead create a texture with the
    minimum size.

    \value TextureSizeMax Maximum texture width and height. This depends on the
    graphics API and sometimes the platform or implementation as well.
    Typically the value is in the range 4096 - 16384. Attempting to create
    textures larger than this is expected to fail.
Laszlo Agocs's avatar
Laszlo Agocs committed
133 134 135 136 137
 */

/*!
    \class QRhiInitParams
    \inmodule QtRhi
138
    \brief Base class for backend-specific initialization parameters.
Laszlo Agocs's avatar
Laszlo Agocs committed
139 140 141 142 143
 */

/*!
    \class QRhiColorClearValue
    \inmodule QtRhi
144
    \brief Specifies a clear color for a color buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
145 146 147 148 149
 */

/*!
    \class QRhiDepthStencilClearValue
    \inmodule QtRhi
150
    \brief Specifies clear values for a depth or stencil buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
151 152 153 154 155
 */

/*!
    \class QRhiViewport
    \inmodule QtRhi
156
    \brief Specifies a viewport rectangle.
Laszlo Agocs's avatar
Laszlo Agocs committed
157 158 159 160 161
 */

/*!
    \class QRhiScissor
    \inmodule QtRhi
162
    \brief Specifies a scissor rectangle.
Laszlo Agocs's avatar
Laszlo Agocs committed
163 164 165 166 167
 */

/*!
    \class QRhiVertexInputLayout
    \inmodule QtRhi
168
    \brief Describes the layout of vertex inputs consumed by a vertex shader.
Laszlo Agocs's avatar
Laszlo Agocs committed
169 170 171 172 173
 */

/*!
    \class QRhiVertexInputLayout::Binding
    \inmodule QtRhi
174
    \brief Describes a vertex input binding.
Laszlo Agocs's avatar
Laszlo Agocs committed
175 176 177 178 179
 */

/*!
    \class QRhiVertexInputLayout::Attribute
    \inmodule QtRhi
180
    \brief Describes a single vertex input element.
Laszlo Agocs's avatar
Laszlo Agocs committed
181 182 183 184 185
 */

/*!
    \class QRhiGraphicsShaderStage
    \inmodule QtRhi
186
    \brief Specifies the type and the shader code for a shader stage in the graphics pipeline.
Laszlo Agocs's avatar
Laszlo Agocs committed
187 188 189 190 191
 */

/*!
    \class QRhiShaderResourceBinding
    \inmodule QtRhi
192
    \brief Specifies the shader resources that are made visible to one or more shader stages.
Laszlo Agocs's avatar
Laszlo Agocs committed
193 194 195 196 197
 */

/*!
    \class QRhiTextureRenderTargetDescription
    \inmodule QtRhi
198
    \brief Describes the color and depth or depth/stencil attachments of a render target.
Laszlo Agocs's avatar
Laszlo Agocs committed
199 200 201 202 203
 */

/*!
    \class QRhiTextureRenderTargetDescription::ColorAttachment
    \inmodule QtRhi
204
    \brief Describes the color attachments of a render target.
Laszlo Agocs's avatar
Laszlo Agocs committed
205 206 207 208 209
 */

/*!
    \class QRhiTextureUploadDescription
    \inmodule QtRhi
210
    \brief Describes a texture upload operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
211 212 213 214 215
 */

/*!
    \class QRhiTextureUploadDescription::Layer
    \inmodule QtRhi
216
    \brief Describes one layer (face for cubemaps) in a texture upload operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
217 218 219 220 221
 */

/*!
    \class QRhiTextureUploadDescription::Layer::MipLevel
    \inmodule QtRhi
222
    \brief Describes one mip level in a layer in a texture upload operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
223 224 225 226 227
 */

/*!
    \class QRhiTextureCopyDescription
    \inmodule QtRhi
228
    \brief Describes a texture-to-texture copy operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
229 230 231 232 233
 */

/*!
    \class QRhiReadbackDescription
    \inmodule QtRhi
234
    \brief Describes a readback (reading back texture contents from possibly GPU-only memory) operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
235 236 237 238 239
 */

/*!
    \class QRhiReadbackResult
    \inmodule QtRhi
240
    \brief Describes the results of a potentially asynchronous readback operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
241 242 243 244 245
 */

/*!
    \class QRhiNativeHandles
    \inmodule QtRhi
246
    \brief Base class for classes exposing backend-specific collections of native resource objects.
Laszlo Agocs's avatar
Laszlo Agocs committed
247 248 249 250 251
 */

/*!
    \class QRhiResource
    \inmodule QtRhi
252
    \brief Base class for classes encapsulating native resource objects.
Laszlo Agocs's avatar
Laszlo Agocs committed
253 254 255 256 257
 */

/*!
    \class QRhiBuffer
    \inmodule QtRhi
258
    \brief Vertex, index, or uniform (constant) buffer resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
259 260 261 262 263
 */

/*!
    \class QRhiTexture
    \inmodule QtRhi
264
    \brief Texture resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
265 266 267 268 269
 */

/*!
    \class QRhiSampler
    \inmodule QtRhi
270
    \brief Sampler resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
271 272 273 274 275
 */

/*!
    \class QRhiRenderBuffer
    \inmodule QtRhi
276
    \brief Renderbuffer resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
277 278 279 280 281
 */

/*!
    \class QRhiRenderPassDescriptor
    \inmodule QtRhi
282
    \brief Render pass resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
283 284 285 286 287
 */

/*!
    \class QRhiRenderTarget
    \inmodule QtRhi
288
    \brief Represents an onscreen (swapchain) or offscreen (texture) render target.
Laszlo Agocs's avatar
Laszlo Agocs committed
289 290 291 292 293
 */

/*!
    \class QRhiTextureRenderTarget
    \inmodule QtRhi
294
    \brief Texture render target resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
295 296 297 298 299
 */

/*!
    \class QRhiShaderResourceBindings
    \inmodule QtRhi
300
    \brief Encapsulates resources for making buffer, texture, sampler resources visible to shaders.
Laszlo Agocs's avatar
Laszlo Agocs committed
301 302 303 304 305
 */

/*!
    \class QRhiGraphicsPipeline
    \inmodule QtRhi
306
    \brief Graphics pipeline state resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
307 308 309 310 311
 */

/*!
    \class QRhiGraphicsPipeline::TargetBlend
    \inmodule QtRhi
312
    \brief Describes the blend state for one color attachment.
Laszlo Agocs's avatar
Laszlo Agocs committed
313 314 315 316 317
 */

/*!
    \class QRhiGraphicsPipeline::StencilOpState
    \inmodule QtRhi
318
    \brief Describes the stencil operation state.
Laszlo Agocs's avatar
Laszlo Agocs committed
319 320 321 322 323
 */

/*!
    \class QRhiSwapChain
    \inmodule QtRhi
324
    \brief Swapchain resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
325 326 327 328 329
 */

/*!
    \class QRhiCommandBuffer
    \inmodule QtRhi
330 331 332 333 334 335
    \brief Command buffer resource.

    Not creatable by applications at the moment. The only ways to obtain a
    valid QRhiCommandBuffer are to get it from the targeted swapchain via
    QRhiSwapChain::currentFrameCommandBuffer(), or, in case of rendering
    compeletely offscreen, initializing one via beginOffscreenFrame().
Laszlo Agocs's avatar
Laszlo Agocs committed
336 337 338 339 340
 */

/*!
    \class QRhiResourceUpdateBatch
    \inmodule QtRhi
341
    \brief Records upload and copy type of operations.
Laszlo Agocs's avatar
Laszlo Agocs committed
342 343
 */

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
QRhiResource::QRhiResource(QRhiImplementation *rhi_)
    : rhi(rhi_)
{
}

QRhiResource::~QRhiResource()
{
}

void QRhiResource::releaseAndDestroy()
{
    release();
    delete this;
}

359 360 361 362 363 364 365 366 367 368
QByteArray QRhiResource::name() const
{
    return objectName;
}

void QRhiResource::setName(const QByteArray &name)
{
    objectName = name;
}

369 370
QRhiBuffer::QRhiBuffer(QRhiImplementation *rhi, Type type_, UsageFlags usage_, int size_)
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
371
      m_type(type_), m_usage(usage_), m_size(size_)
372 373 374 375
{
}

QRhiRenderBuffer::QRhiRenderBuffer(QRhiImplementation *rhi, Type type_, const QSize &pixelSize_,
Laszlo Agocs's avatar
Laszlo Agocs committed
376
                                   int sampleCount_, Flags flags_)
377
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
378
      m_type(type_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_)
379 380 381
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
382 383
QRhiTexture::QRhiTexture(QRhiImplementation *rhi, Format format_, const QSize &pixelSize_,
                         int sampleCount_, Flags flags_)
384
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
385
      m_format(format_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_)
386 387 388
{
}

389
const QRhiNativeHandles *QRhiTexture::nativeHandles()
390 391 392 393
{
    return nullptr;
}

394
bool QRhiTexture::buildFrom(const QRhiNativeHandles *src)
395 396 397 398 399
{
    Q_UNUSED(src);
    return false;
}

400 401 402 403
QRhiSampler::QRhiSampler(QRhiImplementation *rhi,
                         Filter magFilter_, Filter minFilter_, Filter mipmapMode_,
                         AddressMode u_, AddressMode v_, AddressMode w_)
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
404 405
      m_magFilter(magFilter_), m_minFilter(minFilter_), m_mipmapMode(mipmapMode_),
      m_addressU(u_), m_addressV(v_), m_addressW(w_)
406 407 408
{
}

409
QRhiRenderPassDescriptor::QRhiRenderPassDescriptor(QRhiImplementation *rhi)
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    : QRhiResource(rhi)
{
}

QRhiRenderTarget::QRhiRenderTarget(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

QRhiReferenceRenderTarget::QRhiReferenceRenderTarget(QRhiImplementation *rhi)
    : QRhiRenderTarget(rhi)
{
}

QRhiTextureRenderTarget::QRhiTextureRenderTarget(QRhiImplementation *rhi,
                                                 const QRhiTextureRenderTargetDescription &desc_,
                                                 Flags flags_)
    : QRhiRenderTarget(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
428 429
      m_desc(desc_),
      m_flags(flags_)
430 431 432 433 434 435 436 437
{
}

QRhiShaderResourceBindings::QRhiShaderResourceBindings(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
438
QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
439 440
        int binding_, StageFlags stage_, QRhiBuffer *buf_)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
441
    QRhiShaderResourceBinding b;
442 443 444 445 446 447 448 449 450
    b.binding = binding_;
    b.stage = stage_;
    b.type = UniformBuffer;
    b.ubuf.buf = buf_;
    b.ubuf.offset = 0;
    b.ubuf.maybeSize = 0; // entire buffer
    return b;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
451
QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
452 453 454
        int binding_, StageFlags stage_, QRhiBuffer *buf_, int offset_, int size_)
{
    Q_ASSERT(size_ > 0);
Laszlo Agocs's avatar
Laszlo Agocs committed
455
    QRhiShaderResourceBinding b;
456 457 458 459 460 461 462 463 464
    b.binding = binding_;
    b.stage = stage_;
    b.type = UniformBuffer;
    b.ubuf.buf = buf_;
    b.ubuf.offset = offset_;
    b.ubuf.maybeSize = size_;
    return b;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
465
QRhiShaderResourceBinding QRhiShaderResourceBinding::sampledTexture(
466 467
        int binding_, StageFlags stage_, QRhiTexture *tex_, QRhiSampler *sampler_)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
468
    QRhiShaderResourceBinding b;
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    b.binding = binding_;
    b.stage = stage_;
    b.type = SampledTexture;
    b.stex.tex = tex_;
    b.stex.sampler = sampler_;
    return b;
}

QRhiGraphicsPipeline::QRhiGraphicsPipeline(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

QRhiSwapChain::QRhiSwapChain(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

QRhiCommandBuffer::QRhiCommandBuffer(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

QRhiImplementation::~QRhiImplementation()
{
    qDeleteAll(resUpdPool);
}

497 498 499 500 501
void QRhiImplementation::sendVMemStatsToProfiler()
{
    // nothing to do in the default implementation
}

502
bool QRhiImplementation::isCompressedFormat(QRhiTexture::Format format) const
503 504 505 506 507 508 509
{
    return (format >= QRhiTexture::BC1 && format <= QRhiTexture::BC7)
            || (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ETC2_RGBA8)
            || (format >= QRhiTexture::ASTC_4x4 && format <= QRhiTexture::ASTC_12x12);
}

void QRhiImplementation::compressedFormatInfo(QRhiTexture::Format format, const QSize &size,
510 511
                                              quint32 *bpl, quint32 *byteSize,
                                              QSize *blockDim) const
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
{
    int xdim = 4;
    int ydim = 4;
    quint32 blockSize = 0;

    switch (format) {
    case QRhiTexture::BC1:
        blockSize = 8;
        break;
    case QRhiTexture::BC2:
        blockSize = 16;
        break;
    case QRhiTexture::BC3:
        blockSize = 16;
        break;
    case QRhiTexture::BC4:
        blockSize = 8;
        break;
    case QRhiTexture::BC5:
        blockSize = 16;
        break;
    case QRhiTexture::BC6H:
        blockSize = 16;
        break;
    case QRhiTexture::BC7:
        blockSize = 16;
        break;

    case QRhiTexture::ETC2_RGB8:
        blockSize = 8;
        break;
    case QRhiTexture::ETC2_RGB8A1:
        blockSize = 8;
        break;
    case QRhiTexture::ETC2_RGBA8:
        blockSize = 16;
        break;

    case QRhiTexture::ASTC_4x4:
        blockSize = 16;
        break;
    case QRhiTexture::ASTC_5x4:
        blockSize = 16;
        xdim = 5;
        break;
    case QRhiTexture::ASTC_5x5:
        blockSize = 16;
        xdim = ydim = 5;
        break;
    case QRhiTexture::ASTC_6x5:
        blockSize = 16;
        xdim = 6;
        ydim = 5;
        break;
    case QRhiTexture::ASTC_6x6:
        blockSize = 16;
        xdim = ydim = 6;
        break;
    case QRhiTexture::ASTC_8x5:
        blockSize = 16;
        xdim = 8;
        ydim = 5;
        break;
    case QRhiTexture::ASTC_8x6:
        blockSize = 16;
        xdim = 8;
        ydim = 6;
        break;
    case QRhiTexture::ASTC_8x8:
        blockSize = 16;
        xdim = ydim = 8;
        break;
    case QRhiTexture::ASTC_10x5:
        blockSize = 16;
        xdim = 10;
        ydim = 5;
        break;
    case QRhiTexture::ASTC_10x6:
        blockSize = 16;
        xdim = 10;
        ydim = 6;
        break;
    case QRhiTexture::ASTC_10x8:
        blockSize = 16;
        xdim = 10;
        ydim = 8;
        break;
    case QRhiTexture::ASTC_10x10:
        blockSize = 16;
        xdim = ydim = 10;
        break;
    case QRhiTexture::ASTC_12x10:
        blockSize = 16;
        xdim = 12;
        ydim = 10;
        break;
    case QRhiTexture::ASTC_12x12:
        blockSize = 16;
        xdim = ydim = 12;
        break;

    default:
        Q_UNREACHABLE();
        break;
    }

    const quint32 wblocks = (size.width() + xdim - 1) / xdim;
    const quint32 hblocks = (size.height() + ydim - 1) / ydim;

    if (bpl)
        *bpl = wblocks * blockSize;
    if (byteSize)
        *byteSize = wblocks * hblocks * blockSize;
625 626
    if (blockDim)
        *blockDim = QSize(xdim, ydim);
627 628 629
}

void QRhiImplementation::textureFormatInfo(QRhiTexture::Format format, const QSize &size,
630
                                           quint32 *bpl, quint32 *byteSize) const
631 632
{
    if (isCompressedFormat(format)) {
633
        compressedFormatInfo(format, size, bpl, byteSize, nullptr);
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
        return;
    }

    quint32 bpc = 0;
    switch (format) {
    case QRhiTexture::RGBA8:
        bpc = 4;
        break;
    case QRhiTexture::BGRA8:
        bpc = 4;
        break;
    case QRhiTexture::R8:
        bpc = 1;
        break;
    case QRhiTexture::R16:
        bpc = 2;
        break;

    case QRhiTexture::D16:
        bpc = 2;
        break;
    case QRhiTexture::D32:
        bpc = 4;
        break;

    default:
        Q_UNREACHABLE();
        break;
    }

    if (bpl)
        *bpl = size.width() * bpc;
    if (byteSize)
        *byteSize = size.width() * size.height() * bpc;
}

670
// Approximate because it excludes subresource alignment or multisampling.
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
quint32 QRhiImplementation::approxByteSizeForTexture(QRhiTexture::Format format, const QSize &baseSize,
                                                     int mipCount, int layerCount)
{
    quint32 approxSize = 0;
    for (int level = 0; level < mipCount; ++level) {
        quint32 byteSize = 0;
        const QSize size(qFloor(float(qMax(1, baseSize.width() >> level))),
                         qFloor(float(qMax(1, baseSize.height() >> level))));
        textureFormatInfo(format, size, nullptr, &byteSize);
        approxSize += byteSize;
    }
    approxSize *= layerCount;
    return approxSize;
}

686 687 688 689 690 691
QRhi::QRhi()
{
}

QRhi::~QRhi()
{
692 693 694 695
    if (d) {
        d->destroy();
        delete d;
    }
696 697
}

698
QRhi *QRhi::create(Implementation impl, QRhiInitParams *params, Flags flags)
699
{
700 701
    QScopedPointer<QRhi> r(new QRhi);

702
    switch (impl) {
Laszlo Agocs's avatar
Laszlo Agocs committed
703 704 705
    case Null:
        r->d = new QRhiNull(params);
        break;
706 707 708
    case Vulkan:
#if QT_CONFIG(vulkan)
        r->d = new QRhiVulkan(params);
709
        break;
710 711 712 713 714
#else
        qWarning("This build of Qt has no Vulkan support");
        break;
#endif
    case OpenGLES2:
715
#ifndef QT_NO_OPENGL
716
        r->d = new QRhiGles2(params);
717
        break;
718 719 720 721
#else
        qWarning("This build of Qt has no OpenGL support");
        break;
#endif
722 723 724
    case D3D11:
#ifdef Q_OS_WIN
        r->d = new QRhiD3D11(params);
725
        break;
726 727 728 729 730 731 732
#else
        qWarning("This platform has no Direct3D 11 support");
        break;
#endif
    case Metal:
#ifdef Q_OS_DARWIN
        r->d = new QRhiMetal(params);
733
        break;
734 735 736 737 738 739 740
#else
        qWarning("This platform has no Metal support");
        break;
#endif
    default:
        break;
    }
741

742 743 744 745 746 747
    if (r->d) {
        if (flags.testFlag(EnableProfiling)) {
            QRhiProfilerPrivate *profD = QRhiProfilerPrivate::get(&r->d->profiler);
            profD->rhi = r.data();
            profD->rhiD = r->d;
        }
748
        r->d->debugMarkers = flags.testFlag(EnableDebugMarkers);
749 750 751
        if (r->d->create(flags))
            return r.take();
    }
752

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    return nullptr;
}

QRhiResourceUpdateBatch::QRhiResourceUpdateBatch(QRhiImplementation *rhi)
    : d(new QRhiResourceUpdateBatchPrivate)
{
    d->q = this;
    d->rhi = rhi;
}

QRhiResourceUpdateBatch::~QRhiResourceUpdateBatch()
{
    delete d;
}

void QRhiResourceUpdateBatch::release()
{
    d->free();
}

773 774 775 776 777
void QRhiResourceUpdateBatch::merge(QRhiResourceUpdateBatch *other)
{
    d->merge(other->d);
}

778 779 780 781 782
void QRhiResourceUpdateBatch::updateDynamicBuffer(QRhiBuffer *buf, int offset, int size, const void *data)
{
    d->dynamicBufferUpdates.append({ buf, offset, size, data });
}

783 784 785 786 787
void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, int offset, int size, const void *data)
{
    d->staticBufferUploads.append({ buf, offset, size, data });
}

788 789
void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, const void *data)
{
790
    d->staticBufferUploads.append({ buf, 0, 0, data });
791 792
}

Laszlo Agocs's avatar
Laszlo Agocs committed
793
void QRhiResourceUpdateBatch::uploadTexture(QRhiTexture *tex, const QRhiTextureUploadDescription &desc)
794 795 796 797 798 799 800 801 802
{
    d->textureUploads.append({ tex, desc });
}

void QRhiResourceUpdateBatch::uploadTexture(QRhiTexture *tex, const QImage &image)
{
    uploadTexture(tex, {{{{{ image }}}}});
}

803 804 805 806 807
void QRhiResourceUpdateBatch::copyTexture(QRhiTexture *dst, QRhiTexture *src, const QRhiTextureCopyDescription &desc)
{
    d->textureCopies.append({ dst, src, desc });
}

808 809 810 811 812
void QRhiResourceUpdateBatch::readBackTexture(const QRhiReadbackDescription &rb, QRhiReadbackResult *result)
{
    d->textureReadbacks.append({ rb, result });
}

813 814
void QRhiResourceUpdateBatch::generateMips(QRhiTexture *tex)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
815
    d->textureMipGens.append(QRhiResourceUpdateBatchPrivate::TextureMipGen(tex));
816 817
}

818 819 820 821 822
void QRhiResourceUpdateBatch::prepareTextureForUse(QRhiTexture *tex, TexturePrepareFlags flags)
{
    d->texturePrepares.append({ tex, flags });
}

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
QRhiResourceUpdateBatch *QRhi::nextResourceUpdateBatch()
{
    auto nextFreeBatch = [this]() -> QRhiResourceUpdateBatch * {
        for (int i = 0, ie = d->resUpdPoolMap.count(); i != ie; ++i) {
            if (!d->resUpdPoolMap.testBit(i)) {
                d->resUpdPoolMap.setBit(i);
                QRhiResourceUpdateBatch *u = d->resUpdPool[i];
                QRhiResourceUpdateBatchPrivate::get(u)->poolIndex = i;
                return u;
            }
        }
        return nullptr;
    };

    QRhiResourceUpdateBatch *u = nextFreeBatch();
    if (!u) {
        const int oldSize = d->resUpdPool.count();
        const int newSize = oldSize + 4;
        d->resUpdPool.resize(newSize);
        d->resUpdPoolMap.resize(newSize);
        for (int i = oldSize; i < newSize; ++i)
            d->resUpdPool[i] = new QRhiResourceUpdateBatch(d);
        u = nextFreeBatch();
        Q_ASSERT(u);
    }

    return u;
}

void QRhiResourceUpdateBatchPrivate::free()
{
    Q_ASSERT(poolIndex >= 0 && rhi->resUpdPool[poolIndex] == q);

    dynamicBufferUpdates.clear();
    staticBufferUploads.clear();
    textureUploads.clear();
859
    textureCopies.clear();
860
    textureReadbacks.clear();
861
    textureMipGens.clear();
862
    texturePrepares.clear();
863 864 865 866 867

    rhi->resUpdPoolMap.clearBit(poolIndex);
    poolIndex = -1;
}

868 869 870 871 872
void QRhiResourceUpdateBatchPrivate::merge(QRhiResourceUpdateBatchPrivate *other)
{
    dynamicBufferUpdates += other->dynamicBufferUpdates;
    staticBufferUploads += other->staticBufferUploads;
    textureUploads += other->textureUploads;
873
    textureCopies += other->textureCopies;
874
    textureReadbacks += other->textureReadbacks;
875
    textureMipGens += other->textureMipGens;
876 877 878
    texturePrepares += other->texturePrepares;
}

879 880 881 882 883
void QRhiCommandBuffer::resourceUpdate(QRhiResourceUpdateBatch *resourceUpdates)
{
    rhi->resourceUpdate(this, resourceUpdates);
}

884 885 886 887 888
void QRhiCommandBuffer::beginPass(QRhiRenderTarget *rt,
                                  const QRhiColorClearValue &colorClearValue,
                                  const QRhiDepthStencilClearValue &depthStencilClearValue,
                                  QRhiResourceUpdateBatch *resourceUpdates)
{
889
    rhi->beginPass(this, rt, colorClearValue, depthStencilClearValue, resourceUpdates);
890 891
}

892
void QRhiCommandBuffer::endPass(QRhiResourceUpdateBatch *resourceUpdates)
893
{
894
    rhi->endPass(this, resourceUpdates);
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
}

void QRhiCommandBuffer::setGraphicsPipeline(QRhiGraphicsPipeline *ps,
                                            QRhiShaderResourceBindings *srb)
{
    rhi->setGraphicsPipeline(this, ps, srb);
}

void QRhiCommandBuffer::setVertexInput(int startBinding, const QVector<VertexInput> &bindings,
                                       QRhiBuffer *indexBuf, quint32 indexOffset,
                                       IndexFormat indexFormat)
{
    rhi->setVertexInput(this, startBinding, bindings, indexBuf, indexOffset, indexFormat);
}

void QRhiCommandBuffer::setViewport(const QRhiViewport &viewport)
{
    rhi->setViewport(this, viewport);
}

void QRhiCommandBuffer::setScissor(const QRhiScissor &scissor)
{
    rhi->setScissor(this, scissor);
}

void QRhiCommandBuffer::setBlendConstants(const QVector4D &c)
{
    rhi->setBlendConstants(this, c);
}

void QRhiCommandBuffer::setStencilRef(quint32 refValue)
{
    rhi->setStencilRef(this, refValue);
}

void QRhiCommandBuffer::draw(quint32 vertexCount,
                             quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
{
    rhi->draw(this, vertexCount, instanceCount, firstVertex, firstInstance);
}

void QRhiCommandBuffer::drawIndexed(quint32 indexCount,
                                    quint32 instanceCount, quint32 firstIndex,
                                    qint32 vertexOffset, quint32 firstInstance)
{
    rhi->drawIndexed(this, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
}

943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
void QRhiCommandBuffer::debugMarkBegin(const QByteArray &name)
{
    rhi->debugMarkBegin(this, name);
}

void QRhiCommandBuffer::debugMarkEnd()
{
    rhi->debugMarkEnd(this);
}

void QRhiCommandBuffer::debugMarkMsg(const QByteArray &msg)
{
    rhi->debugMarkMsg(this, msg);
}

958 959 960 961 962 963 964 965 966 967 968 969 970
int QRhi::ubufAligned(int v) const
{
    const int byteAlign = ubufAlignment();
    return (v + byteAlign - 1) & ~(byteAlign - 1);
}

int QRhi::mipLevelsForSize(const QSize &size) const
{
    return qCeil(std::log2(qMax(size.width(), size.height()))) + 1;
}

QSize QRhi::sizeForMipLevel(int mipLevel, const QSize &baseLevelSize) const
{
971 972
    const int w = qFloor(float(qMax(1, baseLevelSize.width() >> mipLevel)));
    const int h = qFloor(float(qMax(1, baseLevelSize.height() >> mipLevel)));
973 974 975 976 977 978 979 980 981 982 983 984 985
    return QSize(w, h);
}

bool QRhi::isYUpInFramebuffer() const
{
    return d->isYUpInFramebuffer();
}

QMatrix4x4 QRhi::clipSpaceCorrMatrix() const
{
    return d->clipSpaceCorrMatrix();
}

986
bool QRhi::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
987
{
988
    return d->isTextureFormatSupported(format, flags);
989 990
}

991 992 993 994 995
bool QRhi::isFeatureSupported(QRhi::Feature feature) const
{
    return d->isFeatureSupported(feature);
}

996 997 998 999 1000
int QRhi::resourceSizeLimit(ResourceSizeLimit limit) const
{
    return d->resourceSizeLimit(limit);
}

1001
const QRhiNativeHandles *QRhi::nativeHandles()
1002 1003 1004 1005
{
    return d->nativeHandles();
}

1006
QRhiProfiler *QRhi::profiler()
1007 1008 1009 1010
{
    return &d->profiler;
}

1011
QRhiGraphicsPipeline *QRhi::newGraphicsPipeline()
1012 1013 1014 1015
{
    return d->createGraphicsPipeline();
}

1016
QRhiShaderResourceBindings *QRhi::newShaderResourceBindings()
1017 1018 1019 1020
{
    return d->createShaderResourceBindings();
}

1021 1022 1023
QRhiBuffer *QRhi::newBuffer(QRhiBuffer::Type type,
                            QRhiBuffer::UsageFlags usage,
                            int size)
1024 1025 1026 1027
{
    return d->createBuffer(type, usage, size);
}

1028 1029 1030
QRhiRenderBuffer *QRhi::newRenderBuffer(QRhiRenderBuffer::Type type,
                                        const QSize &pixelSize,
                                        int sampleCount,
Laszlo Agocs's avatar
Laszlo Agocs committed
1031
                                        QRhiRenderBuffer::Flags flags)
1032
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1033
    return d->createRenderBuffer(type, pixelSize, sampleCount, flags);
1034 1035
}

1036 1037
QRhiTexture *QRhi::newTexture(QRhiTexture::Format format,
                              const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
1038
                              int sampleCount,
1039
                              QRhiTexture::Flags flags)
1040
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1041
    return d->createTexture(format, pixelSize, sampleCount, flags);
1042 1043
}

1044 1045 1046
QRhiSampler *QRhi::newSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
                              QRhiSampler::Filter mipmapMode,
                              QRhiSampler:: AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
1047 1048 1049 1050
{
    return d->createSampler(magFilter, minFilter, mipmapMode, u, v, w);
}

1051 1052
QRhiTextureRenderTarget *QRhi::newTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
                                                      QRhiTextureRenderTarget::Flags flags)
1053 1054 1055 1056
{
    return d->createTextureRenderTarget(desc, flags);
}

1057
QRhiSwapChain *QRhi::newSwapChain()
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
{
    return d->createSwapChain();
}

QRhi::FrameOpResult QRhi::beginFrame(QRhiSwapChain *swapChain)
{
    return d->beginFrame(swapChain);
}

QRhi::FrameOpResult QRhi::endFrame(QRhiSwapChain *swapChain)
{
    return d->endFrame(swapChain);
}

1072 1073 1074 1075 1076
QRhi::FrameOpResult QRhi::beginOffscreenFrame(QRhiCommandBuffer **cb)
{
    return d->beginOffscreenFrame(cb);
}

1077
QRhi::FrameOpResult QRhi::endOffscreenFrame()
1078
{
1079 1080 1081 1082 1083 1084
    return d->endOffscreenFrame();
}

QRhi::FrameOpResult QRhi::finish()
{
    return d->finish();
1085 1086
}

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
QVector<int> QRhi::supportedSampleCounts() const
{
    return d->supportedSampleCounts();
}

int QRhi::ubufAlignment() const
{
    return d->ubufAlignment();
}

QT_END_NAMESPACE