qrhi.cpp 123 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 "qrhi_p.h"
Laszlo Agocs's avatar
Laszlo Agocs committed
38
#include "qrhirsh_p.h"
39 40
#include <qmath.h>

Laszlo Agocs's avatar
Laszlo Agocs committed
41
#include "qrhinull_p.h"
42
#ifndef QT_NO_OPENGL
43
#include "qrhigles2_p.h"
44
#endif
45 46 47 48 49 50 51 52 53 54 55 56
#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
57 58 59
/*!
    \class QRhi
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
60 61

    \brief Accelerated 2D/3D graphics API abstraction.
Laszlo Agocs's avatar
Laszlo Agocs committed
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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

     QRhi is an abstraction for hardware accelerated graphics APIs, such as,
     \l{https://www.khronos.org/opengl/}{OpenGL},
     \l{https://www.khronos.org/opengles/}{OpenGL ES},
     \l{https://docs.microsoft.com/en-us/windows/desktop/direct3d}{Direct3D},
     \l{https://developer.apple.com/metal/}{Metal}, and
     \l{https://www.khronos.org/vulkan/}{Vulkan}.

    Each QRhi instance is backed by a backend for a specific graphics API. The
    selection of the backend is a run time choice and is up to the application
    or library that creates the QRhi instance. Some backends are available on
    multiple platforms (OpenGL, Vulkan, Null), while APIs specific to a given
    platform are only available when running on the platform in question (Metal
    on macOS/iOS/tvOS, Direct3D on Windows).

    \section2 Design Fundamentals

    A QRhi cannot be instantiated directly. Instead, use the create()
    function. Delete the QRhi instance normally to release the graphics device.

    \section3 Resources

    Instances of classes deriving from QRhiResource, such as, QRhiBuffer,
    QRhiTexture, etc., encapsulate zero, one, or more native graphics
    resources. Instances of such classes are always created via the \c new
    functions of the QRhi, such as, newBuffer(), newTexture(),
    newTextureRenderTarget(), newSwapChain().

    \list

    \li The returned value from both create() and functions like newBuffer() is
    owned by the caller.

    \li Unlike QRhi, subclasses of QRhiResource should not be destroyed
    directly via delete without calling QRhiResource::release(). The typical
    approach is to call QRhiResource::releaseAndDestroy(). This is equivalent
    to QRhiResource::release() followed by \c delete.

    \li Just creating a QRhiResource subclass never allocates or initalizes any
    native resources. That is only done when calling the \c build function of a
    subclass, for example, QRhiBuffer::build() or QRhiTexture::build().

    \li The exception is
    QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor() and
    QRhiSwapChain::newCompatibleRenderPassDescriptor(). There is no \c build
    operation for these and the returned object is immediately active.

    \li The resource objects themselves are treated as immutable: once a
    resource is built, changing any parameters via the setters, such as,
    QRhiTexture::setPixelSize(), has no effect, unless the underlying native
    resource is released and \c build is called again. See more about resource
    reuse in the sections below.

    \li The underlying native resources are scheduled for releasing by calling
    QRhiResource::release(). Backends often queue release requests and defer
    executing them to an unspecified time, this is hidden from the
    applications. This way applications do not have to worry about releasing a
    native resource that may still be in use by an in flight frame.

    \endlist

    \badcode
        vbuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
        if (!vbuf->build()) { error }
        ...
        vbuf->releaseAndDestroy();
    \endcode

    \section3 Resource reuse

    From the user's point of view the QRhiResource is reusable immediately
    after calling QRhiResource::release(). With the exception of swapchains,
    calling \c build on an already built object does an implicit release. This
    provides a handy shortcut to reuse a QRhiResource instance with different
    parameters, with a new native graphics resource underneath.

    The importance of reusing the same object lies in the fact that some
    objects reference other objects: for example, a QRhiShaderResourceBindings
    can reference QRhiBuffer, QRhiTexture, and QRhiSampler instances. If now
    one of these buffers need to be resized or a sampler parameter needs
    changing, destroying and creating a whole new QRhiBuffer or QRhiSampler
    would invalidate all references to the old instance. By just changing the
    appropriate parameters via QRhiBuffer::setSize() or similar and then
    calling QRhiBuffer::build(), everything works as expected and there is no
    need to touch the QRhiShaderResourceBindings at all, even though there is a
    good chance that under the hood the QRhiBuffer is now backed by a whole new
    native buffer.

    \badcode
        ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 256);
        ubuf->build();

154
        srb = rhi->newShaderResourceBindings()
Laszlo Agocs's avatar
Laszlo Agocs committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        srb->setBindings({
            QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf)
        });
        srb->build();

        ...

        // now suddenly we need buffer with a different size
        ubuf->setSize(512);
        ubuf->build(); // same as ubuf->release(); ubuf->build();

        // that's it, srb needs no changes whatsoever
    \endcode

    \section3 Pooled objects

    There are pooled objects too, like QRhiResourceUpdateBatch. An instance is
    retrieved via a \c next function, such as, nextResourceUpdateBatch(). The
    caller does not own the returned instance in this case. The only valid way
    of operating here is calling functions on the QRhiResourceUpdateBatch and
    then passing it to QRhiCommandBuffer::beginPass() or
    QRhiCommandBuffer::endPass(). These functions take care of returning the
    batch to the pool. Alternatively, a batch can be "canceled" and returned to
    the pool without processing by calling QRhiResourceUpdateBatch::release().

    A typical pattern is thus:

    \badcode
        QRhiResourceUpdateBatch *resUpdates = rhi->nextResourceUpdateBatch();
        ...
        resUpdates->updateDynamicBuffer(ubuf, 0, 64, mvp.constData());
        if (!image.isNull()) {
            resUpdates->uploadTexture(texture, image);
            image = QImage();
        }
        ...
        QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
        cb->beginPass(swapchain->currentFrameRenderTarget(), clearCol, clearDs, resUpdates);
    \endcode

    \section3 Swapchain specifics

    QRhiSwapChain features some special semantics due to the peculiar nature of
    swapchains.

    \list

    \li It has no \c build but rather a QRhiSwapChain::buildOrResize().
    Repeatedly calling this function is \b not the same as calling
    QRhiSwapChain::release() followed by QRhiSwapChain::buildOrResize(). This
    is because swapchains often have ways to handle the case where buffers need
    to be resized in a manner that is more efficient than a brute force
    destroying and recreating from scratch.

    \li An active QRhiSwapChain must be released by calling
    QRhiSwapChain::release() whenever the targeted QWindow sends the
    QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed event. It should not be
    postponed since releasing the swapchain may become problematic when the
    native window is not around anymore (e.g. because the QPlatformWindow got
    destroyed already when getting a QWindow::close())

    \endlist

    \section3 Ownership

    The general rule is no ownership transfer. Creating a QRhi with an already
    existing graphics device does not mean the QRhi takes ownership of the
    device object. Similarly, ownership is not given away when a device or
    texture object is "exported" via QRhi::nativeHandles() or
    QRhiTexture::nativeHandles(). Most importantly, passing pointers in structs
    and via setters does not transfer ownership.

227 228 229 230
    \section3 Threading

    A QRhi instance can be created and used on any thread but all usage must be
    limited to that one single thread. When it comes to native objects, such as
Laszlo Agocs's avatar
Laszlo Agocs committed
231 232
    OpenGL contexts, passed in via a QRhiNativeHandles subclass, it is up to
    the application to ensure they are not misused by other threads.
233

Laszlo Agocs's avatar
Laszlo Agocs committed
234
    \sa {Qt Shader Tools}
Laszlo Agocs's avatar
Laszlo Agocs committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
 */

/*!
    \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.

286 287
    \value MultisampleTexture Indicates that textures with a sample count larger
    than 1 are supported.
288

289 290
    \value MultisampleRenderBuffer Indicates that renderbuffers with a sample
    count larger than 1 are supported.
291

292
    \value DebugMarkers Indicates that debug marker groups (and so
293 294
    QRhiCommandBuffer::debugMarkBegin()) are supported.

295 296
    \value Timestamps Indicates that command buffer timestamps are supported.
    Relevant for QRhiProfiler::gpuFrameTimes().
297

298
    \value Instancing Indicates that instanced drawing is supported.
299

300 301
    \value CustomInstanceStepRate Indicates that instance step rates other than
    1 are supported.
302

303 304
    \value PrimitiveRestart Indicates that restarting the assembly of
    primitives when encountering an index value of 0xFFFF
305 306 307 308 309 310 311 312 313 314 315
    (\l{QRhiCommandBuffer::IndexUInt16}{IndexUInt16}) or 0xFFFFFFFF
    (\l{QRhiCommandBuffer::IndexUInt32}{IndexUInt32}) is always enabled, for
    certain primitive topologies at least. Due to the wildly varying primitive
    restart behavior and support in the underlying graphics APIs, primitive
    restart cannot be controlled with QRhi. Instead, applications must assume
    that whenever this feature is reported as supported, the above mentioned
    index values \c may be treated specially, depending on the topology. The
    only two topologies where primitive restart is guaranteed to behave
    identically across backends, as long as this feature is reported as
    supported, are \l{QRhiGraphicsPipeline::LineStrip}{LineStrip} and
    \l{QRhiGraphicsPipeline::TriangleStrip}{TriangleStrip}.
Laszlo Agocs's avatar
Laszlo Agocs committed
316 317 318 319 320

    \value CrossThreadResourceSharing Indicates that creating QRhi instances on
    different threads with QRhiResourceSharingHost set is allowed. Backends
    where the underlying graphics API cannot safely support using the same
    device or context from multiple threads will report this feature as
321 322 323 324 325 326 327 328 329
    unsupported. When not supported, creating a QRhi with a
    QRhiResourceSharingHost when there are already other QRhi instances on
    other threads associated with the same QRhiResourceSharingHost will behave
    as if the QRhiResourceSharingHost was not set at all. Application and
    framework design may need to take support for this feature into account:
    making resources like textures visible to multiple QRhi instances is not
    neccessarily possible, so the design should be flexible enough to allow
    functioning in that case as well (by using per-QRhi resources instead of a
    single shared one, and possibly duplicating work).
Laszlo Agocs's avatar
Laszlo Agocs committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
 */

/*!
    \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
345 346 347 348 349
 */

/*!
    \class QRhiInitParams
    \inmodule QtRhi
350
    \brief Base class for backend-specific initialization parameters.
351 352 353 354 355 356 357 358 359 360 361

    Contains fields that are relevant to all backends.

    \l resourceSharingHost is set to null by default. Setting it to an actual
    QRhiResourceSharingHost instance is optional. When set, it causes the QRhi
    to share either the graphics device, or, in case of OpenGL, use a context
    that shares resources, with all other QRhi instances that have the same
    QRhiResourceSharingHost set in their QRhiInitParams. This makes the
    underlying graphics resources of QRhiResource subclasses such as
    QRhiTexture visible to all the QRhi instances that use the same
    QRhiResourceSharingHost.
Laszlo Agocs's avatar
Laszlo Agocs committed
362

363
    \sa QRhiResource::isShareable()
Laszlo Agocs's avatar
Laszlo Agocs committed
364 365 366 367 368
 */

/*!
    \class QRhiColorClearValue
    \inmodule QtRhi
369
    \brief Specifies a clear color for a color buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
370 371
 */

372 373 374
/*!
    Constructs a color clear value with \c{(0, 0, 0, 1)} (opaque black).
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
375 376 377 378 379
QRhiColorClearValue::QRhiColorClearValue()
    : m_rgba(0, 0, 0, 1)
{
}

380 381 382 383
/*!
    Constructs a color clear value with the floating point color components
    (\c{0.0f - 1.0f}) specified in \a c.
  */
Laszlo Agocs's avatar
Laszlo Agocs committed
384 385 386 387 388
QRhiColorClearValue::QRhiColorClearValue(const QVector4D &c)
    : m_rgba(c)
{
}

389 390 391 392
/*!
    Constructs a color clear value with the floating point color components
    (\c{0.0f - 1.0f}) specified in \a r, \a g, \a b, and \a a.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
393 394 395 396 397
QRhiColorClearValue::QRhiColorClearValue(float r, float g, float b, float a)
    : m_rgba(r, g, b, a)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
398 399 400
/*!
    \class QRhiDepthStencilClearValue
    \inmodule QtRhi
401
    \brief Specifies clear values for a depth or stencil buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
402 403
 */

404 405 406 407
/*!
    Constructs a depth/stencil clear value with depth clear value 1.0f and
    stencil clear value 0.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
408 409 410 411 412 413
QRhiDepthStencilClearValue::QRhiDepthStencilClearValue()
    : m_d(1),
      m_s(0)
{
}

414 415 416 417
/*!
    Constructs a depth/stencil clear value with depth clear value \a d and
    stencil clear value \a s.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
418 419 420 421 422 423
QRhiDepthStencilClearValue::QRhiDepthStencilClearValue(float d, quint32 s)
    : m_d(d),
      m_s(s)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
424 425 426
/*!
    \class QRhiViewport
    \inmodule QtRhi
427
    \brief Specifies a viewport rectangle.
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

    Used with QRhiCommandBuffer::setViewport().

    \note QRhi assumes OpenGL-style viewport coordinates, meaning x and y are
    bottom-left.

    Typical usage is like the following:

    \badcode
      const QSize outputSizeInPixels = swapchain->currentPixelSize();
      const QRhiViewport viewport(0, 0, outputSizeInPixels.width(), outputSizeInPixels.height());
      cb->beginPass(swapchain->currentFrameRenderTarget(), { 0, 0, 0, 1 }, { 1, 0 });
      cb->setGraphicsPipeline(ps);
      cb->setViewport(viewport);
      ...
    \endcode

    \sa QRhiCommandBuffer::setViewport(), QRhi::clipSpaceCorrMatrix(), QRhiScissor
Laszlo Agocs's avatar
Laszlo Agocs committed
446 447
 */

448 449 450 451 452 453
/*!
    Constructs a viewport description with a default rectangle and depth range.
    The default depth range is 0.0f - 1.0f.

    \sa QRhi::clipSpaceCorrMatrix()
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
454 455 456 457 458 459 460
QRhiViewport::QRhiViewport()
    : m_rect(0, 0, 1280, 720),
      m_minDepth(0),
      m_maxDepth(1)
{
}

461 462 463 464 465 466 467 468
/*!
    Constructs a viewport description with the rectangle specified by \a x, \a
    y, \a w, \a h and the depth range \a minDepth and \a maxDepth.

    \note x and y are assumed to be the bottom-left position.

    \sa QRhi::clipSpaceCorrMatrix()
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
469 470 471 472 473 474 475
QRhiViewport::QRhiViewport(float x, float y, float w, float h, float minDepth, float maxDepth)
    : m_rect(x, y, w, h),
      m_minDepth(minDepth),
      m_maxDepth(maxDepth)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
476 477 478
/*!
    \class QRhiScissor
    \inmodule QtRhi
479
    \brief Specifies a scissor rectangle.
480 481 482 483 484

    Used with QRhiCommandBuffer::setScissor(). Setting a scissor rectangle is
    only possible with a QRhiGraphicsPipeline that has
    QRhiGraphicsPipeline::UsesScissor set.

Laszlo Agocs's avatar
Laszlo Agocs committed
485
    \note QRhi assumes OpenGL-style scissor coordinates, meaning x and y are
486 487 488
    bottom-left.

    \sa QRhiCommandBuffer::setScissor(), QRhiViewport
Laszlo Agocs's avatar
Laszlo Agocs committed
489 490
 */

491 492 493
/*!
    Constructs an empty scissor.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
494 495 496 497
QRhiScissor::QRhiScissor()
{
}

498 499 500 501 502 503
/*!
    Constructs a scissor with the rectangle specified by \a x, \a y, \a w, and
    \a h.

    \note x and y are assumed to be the bottom-left position.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
504 505 506 507
QRhiScissor::QRhiScissor(int x, int y, int w, int h)
    : m_rect(x, y, w, h)
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
508 509

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
510
    \class QRhiVertexInputBinding
Laszlo Agocs's avatar
Laszlo Agocs committed
511
    \inmodule QtRhi
512
    \brief Describes a vertex input binding.
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

    Specifies the stride (in bytes, must be a multiple of 4), the
    classification and optionally the instance step rate.

    As an example, assume a vertex shader with the following inputs:

    \badcode
        layout(location = 0) in vec4 position;
        layout(location = 1) in vec2 texcoord;
    \endcode

    Now let's assume also that 3 component vertex positions \c{(x, y, z)} and 2
    component texture coordinates \c{(u, v)} are provided in a non-interleaved
    format in a buffer (or separate buffers even). Definining two bindings
    could then be done like this:

    \badcode
        QRhiVertexInputLayout inputLayout;
Laszlo Agocs's avatar
Laszlo Agocs committed
531
        inputLayout.setBindings({
532 533
            { 3 * sizeof(float) },
            { 2 * sizeof(float) }
Laszlo Agocs's avatar
Laszlo Agocs committed
534
        });
535 536 537
    \endcode

    Only the stride is interesting here since instancing is not used. The
Laszlo Agocs's avatar
Laszlo Agocs committed
538
    binding number is given by the index of the QRhiVertexInputBinding
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
    element in the bindings vector of the QRhiVertexInputLayout.

    Once a graphics pipeline with this vertex input layout is bound, the vertex
    inputs could be set up like the following for drawing a cube with 36
    vertices, assuming we have a single buffer with first the positions and
    then the texture coordinates:

    \badcode
        cb->setVertexInput(0, { { cubeBuf, 0 }, { cubeBuf, 36 * 3 * sizeof(float) } });
    \endcode

    Note how the index defined by \c {startBinding + i}, where \c i is the
    index in the second argument of
    \l{QRhiCommandBuffer::setVertexInput()}{setVertexInput()}, matches the
    index of the corresponding entry in the \c bindings vector of the
    QRhiVertexInputLayout.

    \note the stride must always be a multiple of 4.

    \sa QRhiCommandBuffer::setVertexInput()
Laszlo Agocs's avatar
Laszlo Agocs committed
559 560
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
561
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
562
    \enum QRhiVertexInputBinding::Classification
Laszlo Agocs's avatar
Laszlo Agocs committed
563 564 565 566 567 568
    Describes the input data classification.

    \value PerVertex Data is per-vertex
    \value PerInstance Data is per-instance
 */

569 570 571
/*!
    Constructs an empty vertex input binding description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
572 573 574 575
QRhiVertexInputBinding::QRhiVertexInputBinding()
{
}

576 577 578 579 580 581 582
/*!
    Constructs a vertex input binding description with the specified \a stride,
    classification \a cls, and instance step rate \a stepRate.

    \note \a stepRate other than 1 is only supported when
    QRhi::CustomInstanceStepRate is reported to be supported.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
583 584 585 586 587 588 589
QRhiVertexInputBinding::QRhiVertexInputBinding(quint32 stride, Classification cls, int stepRate)
    : m_stride(stride),
      m_classification(cls),
      m_instanceStepRate(stepRate)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
590
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
591
    \class QRhiVertexInputAttribute
Laszlo Agocs's avatar
Laszlo Agocs committed
592
    \inmodule QtRhi
593
    \brief Describes a single vertex input element.
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615

    The members specify the binding number, location, format, and offset for a
    single vertex input element.

    \note For HLSL it is assumed that the vertex shader uses
    \c{TEXCOORD<location>} as the semantic for each input. Hence no separate
    semantic name and index.

    As an example, assume a vertex shader with the following inputs:

    \badcode
        layout(location = 0) in vec4 position;
        layout(location = 1) in vec2 texcoord;
    \endcode

    Now let's assume that we have 3 component vertex positions \c{(x, y, z)}
    and 2 component texture coordinates \c{(u, v)} are provided in a
    non-interleaved format in a buffer (or separate buffers even). Once two
    bindings are defined, the attributes could be specified as:

    \badcode
        QRhiVertexInputLayout inputLayout;
Laszlo Agocs's avatar
Laszlo Agocs committed
616
        inputLayout.setBindings({
617 618
            { 3 * sizeof(float) },
            { 2 * sizeof(float) }
Laszlo Agocs's avatar
Laszlo Agocs committed
619 620 621 622 623
        });
        inputLayout.setAttributes({
            { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
            { 1, 1, QRhiVertexInputAttribute::Float2, 0 }
        });
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    \endcode

    Once a graphics pipeline with this vertex input layout is bound, the vertex
    inputs could be set up like the following for drawing a cube with 36
    vertices, assuming we have a single buffer with first the positions and
    then the texture coordinates:

    \badcode
        cb->setVertexInput(0, { { cubeBuf, 0 }, { cubeBuf, 36 * 3 * sizeof(float) } });
    \endcode

    When working with interleaved data, there will typically be just one
    binding, with multiple attributes refering to that same buffer binding
    point:

    \badcode
        QRhiVertexInputLayout inputLayout;
Laszlo Agocs's avatar
Laszlo Agocs committed
641
        inputLayout.setBindings({
642
            { 5 * sizeof(float) }
Laszlo Agocs's avatar
Laszlo Agocs committed
643 644 645 646 647
        });
        inputLayout.setAttributes({
            { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
            { 0, 1, QRhiVertexInputAttribute::Float2, 3 * sizeof(float) }
        });
648 649 650 651 652 653 654 655 656
    \endcode

    and then:

    \badcode
        cb->setVertexInput(0, { { interleavedCubeBuf, 0 } });
    \endcode

    \sa QRhiCommandBuffer::setVertexInput()
Laszlo Agocs's avatar
Laszlo Agocs committed
657 658
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
659
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
660
    \enum QRhiVertexInputAttribute::Format
Laszlo Agocs's avatar
Laszlo Agocs committed
661 662 663 664 665 666 667 668 669 670 671
    Specifies the type of the element data.

    \value Float4 Four component float vector
    \value Float3 Three component float vector
    \value Float2 Two component float vector
    \value Float Float
    \value UNormByte4 Four component normalized unsigned byte vector
    \value UNormByte2 Two component normalized unsigned byte vector
    \value UNormByte Normalized unsigned byte
 */

672 673 674
/*!
    Constructs an empty vertex input attribute description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
675 676 677 678
QRhiVertexInputAttribute::QRhiVertexInputAttribute()
{
}

679 680 681 682
/*!
    Constructs a vertex input attribute description with the specified \a
    binding number, \a location, \a format, and \a offset.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
683 684 685 686 687 688 689 690 691 692 693 694
QRhiVertexInputAttribute::QRhiVertexInputAttribute(int binding, int location, Format format, quint32 offset)
    : m_binding(binding),
      m_location(location),
      m_format(format),
      m_offset(offset)
{
}

/*!
    \class QRhiVertexInputLayout
    \inmodule QtRhi
    \brief Describes the layout of vertex inputs consumed by a vertex shader.
695 696 697

    The vertex input layout is defined by the collections of
    QRhiVertexInputBinding and QRhiVertexInputAttribute.
Laszlo Agocs's avatar
Laszlo Agocs committed
698 699
 */

700 701 702
/*!
    Constructs an empty vertex input layout description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
703 704 705 706
QRhiVertexInputLayout::QRhiVertexInputLayout()
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
707 708 709
/*!
    \class QRhiGraphicsShaderStage
    \inmodule QtRhi
710
    \brief Specifies the type and the shader code for a shader stage in the graphics pipeline.
711 712 713

    \note There is no geometry stage because some graphics APIs (Metal) have no support
    for it.
Laszlo Agocs's avatar
Laszlo Agocs committed
714 715
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
716 717 718 719 720 721 722 723 724 725
/*!
    \enum QRhiGraphicsShaderStage::Type
    Specifies the type of the shader stage.

    \value Vertex Vertex stage
    \value Fragment Fragment (pixel) stage
    \value TessellationControl Tessellation control (hull) stage
    \value TessellationEvaluation Tessellation evaluation (domain) stage
 */

726 727 728
/*!
    Constructs an empty shader stage description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
729 730 731
QRhiGraphicsShaderStage::QRhiGraphicsShaderStage()
{
}
732

733 734 735 736
/*!
    Constructs a shader stage description with the \a type of the stage and the
    \a shader.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
737 738 739 740 741
QRhiGraphicsShaderStage::QRhiGraphicsShaderStage(Type type, const QBakedShader &shader)
    : m_type(type),
      m_shader(shader)
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
742 743

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
744
    \class QRhiColorAttachment
Laszlo Agocs's avatar
Laszlo Agocs committed
745
    \inmodule QtRhi
746 747 748
    \brief Describes the a single color attachment of a render target.

    A color attachment is either a QRhiTexture or a QRhiRenderBuffer. The
Laszlo Agocs's avatar
Laszlo Agocs committed
749
    former, when texture() is set, is used in most cases.
750

Laszlo Agocs's avatar
Laszlo Agocs committed
751 752
    \note texture() and renderBuffer() cannot be both set (be non-null at the
    same time).
753 754 755 756 757 758 759 760

    Setting renderBuffer instead is recommended only when multisampling is
    needed. Relying on QRhi::MultisampleRenderBuffer is a better choice than
    QRhi::MultisampleTexture in practice since the former is available in more
    run time configurations (e.g. when running on OpenGL ES 3.0 which has no
    support for multisample textures, but does support multisample
    renderbuffers).

Laszlo Agocs's avatar
Laszlo Agocs committed
761
    When targeting a non-multisample texture, the layer() and level()
762 763 764
    indicate the targeted layer (face index \c{0-5} for cubemaps) and mip
    level.

Laszlo Agocs's avatar
Laszlo Agocs committed
765
    When texture() or renderBuffer() is multisample, resolveTexture() can be
766 767 768 769 770 771 772
    set optionally. When set, samples are resolved automatically into that
    (non-multisample) texture at the end of the render pass. When rendering
    into a multisample renderbuffers, this is the only way to get resolved,
    non-multisample content out of them. Multisample textures allow sampling in
    shaders so for them this is just one option.

    \note when resolving is enabled, the multisample data may not be written
Laszlo Agocs's avatar
Laszlo Agocs committed
773 774
    out at all. This means that the multisample texture() must not be used
    afterwards with shaders for sampling when resolveTexture() is set.
Laszlo Agocs's avatar
Laszlo Agocs committed
775 776
 */

777 778 779
/*!
    Constructs an empty color attachment description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
780 781 782 783
QRhiColorAttachment::QRhiColorAttachment()
{
}

784 785 786 787
/*!
    Constructs a color attachment description that specifies \a texture as the
    associated color buffer.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
788 789 790 791 792
QRhiColorAttachment::QRhiColorAttachment(QRhiTexture *texture)
    : m_texture(texture)
{
}

793 794 795 796
/*!
    Constructs a color attachment description that specifies \a renderBuffer as
    the associated color buffer.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
QRhiColorAttachment::QRhiColorAttachment(QRhiRenderBuffer *renderBuffer)
    : m_renderBuffer(renderBuffer)
{
}

/*!
    \class QRhiTextureRenderTargetDescription
    \inmodule QtRhi
    \brief Describes the color and depth or depth/stencil attachments of a render target.

    A texture render target has zero or more textures as color attachments,
    zero or one renderbuffer as combined depth/stencil buffer or zero or one
    texture as depth buffer.

    \note depthStencilBuffer() and depthTexture() cannot be both set (cannot be
    non-null at the same time).
 */

815 816 817
/*!
    Constructs an empty texture render target description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
818 819 820 821
QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription()
{
}

822 823 824 825
/*!
    Constructs a texture render target description with one attachment
    described by \a colorAttachment.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
826 827 828 829 830
QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription(const QRhiColorAttachment &colorAttachment)
{
    m_colorAttachments.append(colorAttachment);
}

831 832 833 834 835
/*!
    Constructs a texture render target description with two attachments, a
    color attachment described by \a colorAttachment, and a depth/stencil
    attachment with \a depthStencilBuffer.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
836 837 838 839 840 841 842
QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription(const QRhiColorAttachment &colorAttachment,
                                                                       QRhiRenderBuffer *depthStencilBuffer)
    : m_depthStencilBuffer(depthStencilBuffer)
{
    m_colorAttachments.append(colorAttachment);
}

843 844 845 846 847 848 849 850
/*!
    Constructs a texture render target description with two attachments, a
    color attachment described by \a colorAttachment, and a depth attachment
    with \a depthTexture.

    \note \a depthTexture must have a suitable format, such as QRhiTexture::D16
    or QRhiTexture::D32.
 */
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
QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription(const QRhiColorAttachment &colorAttachment,
                                                                       QRhiTexture *depthTexture)
    : m_depthTexture(depthTexture)
{
    m_colorAttachments.append(colorAttachment);
}

/*!
    \class QRhiTextureMipLevel
    \inmodule QtRhi
    \brief Describes one mip level in a layer in a texture upload operation.

    The source content is specified either as a QImage or as a raw blob. The
    former is only allowed for uncompressed textures, while the latter is only
    supported for compressed ones.

    \note image() and compressedData() cannot be both set at the same time.

    destinationTopLeft() specifies the top-left corner of the target
    rectangle. Defaults to (0, 0).

    An empty sourceSize() (the default) indicates that size is assumed to be
    the size of the subresource. For uncompressed textures this implies that
    the size of the source image() must match the subresource. For compressed
    textures sufficient amount of data must be provided in compressedData().

    \note With compressed textures the first upload must always match the
    subresource size due to graphics API limitations with some backends.

    sourceTopLeft() is is only supported for uncompressed textures, and
    specifies the top-left corner of the source rectangle.

    \note Setting sourceSize() or sourceTopLeft() may trigger a QImage copy
    internally, depending on the format and the backend.
 */

887 888 889
/*!
    Constructs an empty mip level description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
890 891 892 893
QRhiTextureMipLevel::QRhiTextureMipLevel()
{
}

894 895 896 897 898 899 900 901 902 903 904 905
/*!
    Constructs a mip level description with a \a image.

    The \l{QImage::size()}{size} of \a image must match the size of the mip
    level. For level 0 that is the \l{QRhiTexture::pixelSize()}{texture size}.

    The bit depth of \a image must be compatible with the
    \l{QRhiTexture::Format}{texture format}.

    To describe a partial upload, call setSourceSize(), setSourceTopLeft(), or
    setDestinationTopLeft() afterwards.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
906 907 908 909 910
QRhiTextureMipLevel::QRhiTextureMipLevel(const QImage &image)
    : m_image(image)
{
}

911 912 913 914
/*!
    Constructs a mip level description suitable for compressed textures. The
    compressed data is specified in \a compressedData.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
915 916 917 918 919 920 921 922 923 924 925
QRhiTextureMipLevel::QRhiTextureMipLevel(const QByteArray &compressedData)
    : m_compressedData(compressedData)
{
}

/*!
    \class QRhiTextureLayer
    \inmodule QtRhi
    \brief Describes one layer (face for cubemaps) in a texture upload operation.
 */

926 927 928
/*!
    Constructs an empty texture layer description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
929 930 931 932
QRhiTextureLayer::QRhiTextureLayer()
{
}

933 934 935 936
/*!
    Constructs a texture layer description with the specified list of \a
    mipImages.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
937 938 939 940 941
QRhiTextureLayer::QRhiTextureLayer(const QVector<QRhiTextureMipLevel> &mipImages)
    : m_mipImages(mipImages)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
942 943 944
/*!
    \class QRhiTextureUploadDescription
    \inmodule QtRhi
945
    \brief Describes a texture upload operation.
946

947 948 949 950 951 952 953 954
    Used with QRhiResourceUpdateBatch::uploadTexture(). That function has two
    variants: one taking a QImage and one taking a
    QRhiTextureUploadDescription. The former is a convenience version,
    internally creating a QRhiTextureUploadDescription with a single layer and
    a single image in that layer. However, when cubemaps, pre-generated mip
    images, or compressed textures are involved, applications will have to work
    directly with this class instead.

955 956
    \note Cubemaps have one layer for each of the six faces in the order +X,
    -X, +Y, -Y, +Z, -Z.
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

    For example, specifying the faces of a cubemap could look like the following:

    \badcode
        QImage faces[6];
        ...
        QVector<QRhiTextureLayer> layers;
        for (int i = 0; i < 6; ++i)
          layers.append(QRhiTextureLayer({ QRhiTextureMipLevel(faces[i]) });
        QRhiTextureUploadDescription desc(layers);
        resourceUpdates->uploadTexture(texture, desc);
    \endcode

    Another example that specifies mip images for a compressed texture:

    \badcode
        QVector<QRhiTextureMipLevel> mipImages;
        const int mipCount = rhi->mipLevelsForSize(compressedTexture->pixelSize());
        for (int level = 0; level < mipCount; ++level) {
            const QByteArray compressedDataForLevel = ...
            mipImages.append(QRhiTextureMipLevel(compressedDataForLevel));
        }
        QRhiTextureLayer layer(mipImages);
        QRhiTextureUploadDescription desc({ layer });
        resourceUpdates->uploadTexture(compressedTexture, desc);
    \endcode
Laszlo Agocs's avatar
Laszlo Agocs committed
983 984
 */

985 986 987
/*!
    Constructs an empty texture upload description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
988 989 990
QRhiTextureUploadDescription::QRhiTextureUploadDescription()
{
}
991

992 993 994 995
/*!
    Constructs a texture upload description with the specified list of \a
    layers.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
996 997 998 999
QRhiTextureUploadDescription::QRhiTextureUploadDescription(const QVector<QRhiTextureLayer> &layers)
    : m_layers(layers)
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1000 1001 1002 1003

/*!
    \class QRhiTextureCopyDescription
    \inmodule QtRhi
1004
    \brief Describes a texture-to-texture copy operation.
1005

1006 1007 1008
    An empty pixelSize() indicates that the entire subresource is to be copied.
    A default constructed copy description therefore leads to copying the
    entire subresource at level 0 of layer 0.
1009 1010 1011

    \note The source texture must be created with
    QRhiTexture::UsedAsTransferSource.
1012 1013 1014 1015

    \note The source and destination rectangles defined by pixelSize(),
    sourceTopLeft(), and destinationTopLeft() must fit the source and
    destination textures, respectively. The behavior is undefined otherwise.
Laszlo Agocs's avatar
Laszlo Agocs committed
1016 1017
 */

1018 1019 1020
/*!
    Constructs an empty texture copy description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1021 1022 1023 1024
QRhiTextureCopyDescription::QRhiTextureCopyDescription()
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1025 1026 1027
/*!
    \class QRhiReadbackDescription
    \inmodule QtRhi
1028
    \brief Describes a readback (reading back texture contents from possibly GPU-only memory) operation.
1029 1030

    The source of the readback operation is either a QRhiTexture or the
1031 1032
    current backbuffer of the currently targeted QRhiSwapChain. When
    texture() is not set, the swapchain is used. Otherwise the specified
1033 1034 1035 1036 1037 1038 1039 1040
    QRhiTexture is treated as the source.

    \note Textures used in readbacks must be created with
    QRhiTexture::UsedAsTransferSource.

    \note Swapchains used in readbacks must be created with
    QRhiSwapChain::UsedAsTransferSource.

1041
    layer() and level() are only applicable when the source is a QRhiTexture.
1042 1043 1044

    \note Multisample textures cannot be read back. Readbacks are supported for
    multisample swapchain buffers however.
Laszlo Agocs's avatar
Laszlo Agocs committed
1045 1046
 */

1047 1048 1049 1050 1051 1052 1053 1054 1055
/*!
    Constructs an empty texture readback description.

    \note The source texture is set to null by default, which is still a valid
    readback: it specifies that the backbuffer of the current swapchain is to
    be read back. (current meaning the frame's target swapchain at the time of
    committing the QRhiResourceUpdateBatch with the
    \l{QRhiResourceUpdateBatch::readBackTexture()}{texture readback} on it)
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1056 1057 1058 1059
QRhiReadbackDescription::QRhiReadbackDescription()
{
}

1060 1061 1062 1063 1064 1065 1066
/*!
    Constructs an texture readback description that specifies that level 0 of
    layer 0 of \a texture is to be read back.

    \note \a texture can also be null in which case this constructor is
    identical to the argumentless variant.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1067 1068 1069 1070 1071
QRhiReadbackDescription::QRhiReadbackDescription(QRhiTexture *texture)
    : m_texture(texture)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1072 1073 1074
/*!
    \class QRhiReadbackResult
    \inmodule QtRhi
1075
    \brief Describes the results of a potentially asynchronous readback operation.
1076 1077 1078 1079

    When \l completed is set, the function is invoked when the \l data is
    available. \l format and \l pixelSize are set upon completion together with
    \l data.
Laszlo Agocs's avatar
Laszlo Agocs committed
1080 1081 1082 1083 1084
 */

/*!
    \class QRhiNativeHandles
    \inmodule QtRhi
1085
    \brief Base class for classes exposing backend-specific collections of native resource objects.
Laszlo Agocs's avatar
Laszlo Agocs committed
1086 1087 1088 1089 1090
 */

/*!
    \class QRhiResource
    \inmodule QtRhi
1091
    \brief Base class for classes encapsulating native resource objects.
Laszlo Agocs's avatar
Laszlo Agocs committed
1092 1093 1094
 */

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1095
    \internal
Laszlo Agocs's avatar
Laszlo Agocs committed
1096
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1097 1098 1099 1100
QRhiResource::QRhiResource(QRhiImplementation *rhi_)
    : rhi(rhi_)
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1101

1102
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1103
   Destructor.
1104
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1105 1106 1107
QRhiResource::~QRhiResource()
{
}
1108

Laszlo Agocs's avatar
Laszlo Agocs committed
1109
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1110
    \fn void QRhiResource::release()
Laszlo Agocs's avatar
Laszlo Agocs committed
1111

Laszlo Agocs's avatar
Laszlo Agocs committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    Releases the underlying native graphics resources. Safe to call multiple
    times, subsequent invocations will be a no-op then.

    Once release() is called, the QRhiResource instance can be reused, by
    calling the appropriate \c build() function again, or destroyed.
 */

/*!
    Releases native graphics resources, if there is any, and destroys the
    QRhiResource. Equivalent to \c{r->release(); delete r; }.
 */
void QRhiResource::releaseAndDestroy()
{
    release();
    delete this;
}

/*!
    \return the currently set object name. By default the name is empty.
 */
QByteArray QRhiResource::name() const
{
    return objectName;
}

/*!
    Sets a \a name for the object.

    This has two uses: to get descriptive names for the native graphics
    resources visible in graphics debugging tools, such as
    \l{https://renderdoc.org/}{RenderDoc} and
    \l{https://developer.apple.com/xcode/}{XCode}, and in the output stream of
    QRhiProfiler.

    When it comes to naming native objects by relaying the name via the
    appropriate graphics API, note that the name is ignored when
    QRhi::DebugMarkers are not supported, and may, depending on the backend,
    also be ignored when QRhi::EnableDebugMarkers is not set.

    \note The name may be ignored for objects other than buffers,
    renderbuffers, and textures, depending on the backend.

    \note The name may be modified. For slotted resources, such as a QRhiBuffer
    backed by multiple native buffers, QRhi will append a suffix to make the
    underlying native buffers easily distinguishable from each other.
 */
void QRhiResource::setName(const QByteArray &name)
{
    objectName = name;
    objectName.replace(',', '_'); // cannot contain comma for QRhiProfiler
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1164
/*!
1165
    \return true if this resource is shareable between QRhi instances via a
Laszlo Agocs's avatar
Laszlo Agocs committed
1166 1167 1168
    QRhiResourceSharingHost. It also means that such an QRhiResource can
    outlive the QRhi on which it was created.

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    \note Once a shareable QRhiResource is \c orphaned, meaning that the QRhi
    from which it was created gets destroyed, \c{build()} is not a valid
    operation anymore. The QRhiResource can then only be used in graphics
    operations (as the underlying graphics objects are still there and valid)
    or can be released, as long as the QRhiResourceSharingHost,
    with which the creator QRhi was associated with, has at least one
    associated QRhi alive.

    \note Shareable resources typically include buffers, textures, samplers,
    and renderbuffers. Most backends will not support other type of shareable
    resources.
Laszlo Agocs's avatar
Laszlo Agocs committed
1180 1181 1182

    \sa QRhiResourceSharingHost, QRhi::CrossThreadResourceSharing
 */
1183
bool QRhiResource::isShareable() const
Laszlo Agocs's avatar
Laszlo Agocs committed
1184 1185 1186 1187
{
    return false;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
/*!
    \class QRhiBuffer
    \inmodule QtRhi
    \brief Vertex, index, or uniform (constant) buffer resource.
 */

/*!
    \enum QRhiBuffer::Type
    Specifies type of buffer resource.

    \value Immutable Indicates that the data is not expected to change ever
    after the initial upload. Under the hood such buffer resources are
    typically placed in device local (GPU) memory (on systems where
    applicable). Uploading new data is possible, but frequent changes can be
    expensive. Upload typically happens by copying to a separate, host visible
    staging buffer from which a GPU buffer-to-buffer copy is issued into the
    actual GPU-only buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228

    \value Static Indicates that the data is expected to change only
    infrequently. Typically placed in device local (GPU) memory, where
    applicable. On backends where host visible staging buffers are used for
    uploading, the staging buffers are kept around for this type, unlike with
    Immutable, so subsequent uploads do not suffer in performance. Frequent
    updates should be avoided.

    \value Dynamic Indicates that the data is expected to change frequently.
    Not recommended for large buffers. Typically backed by host visible memory
    in 2 copies in order to allow for changing without stalling the graphics
    pipeline. The double buffering is managed transparently to the applications
    and is not exposed in the API here in any form.
 */

/*!
    \enum QRhiBuffer::UsageFlag
    Flag values to specify how the buffer is going to be used.

    \value VertexBuffer Vertex buffer
    \value IndexBuffer Index buffer
    \value UniformBuffer Uniform (constant) buffer
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
/*!
    \fn void QRhiBuffer::setSize(int sz)

    Sets the size of the buffer in bytes. The size is normally specified in
    QRhi::newBuffer() so this function is only used when the size has to be
    changed. As with other setters, the size only takes effect when calling
    build(), and for already built buffers this involves releasing the previous
    native resource and creating new ones under the hood.

    Backends may choose to allocate buffers bigger than \a sz in order to
    fulfill alignment requirements. This is hidden from the applications and
    size() will always report the size requested in \a sz.
 */

/*!
    \internal
 */
QRhiBuffer::QRhiBuffer(QRhiImplementation *rhi, Type type_, UsageFlags usage_, int size_)
    : QRhiResource(rhi),
      m_type(type_), m_usage(usage_), m_size(size_)
{
}

/*!
    \fn bool QRhiBuffer::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

/*!
    \class QRhiRenderBuffer
    \inmodule QtRhi
    \brief Renderbuffer resource.

    Renderbuffers cannot be sampled or read but have some benefits over
    textures in some cases:

    A DepthStencil renderbuffer may be lazily allocated and be backed by
    transient memory with some APIs. On some platforms this may mean the
    depth/stencil buffer uses no physical backing at all.

    Color renderbuffers are useful since QRhi::MultisampleRenderBuffer may be
    supported even when QRhi::MultisampleTexture is not.

    How the renderbuffer is implemented by a backend is not exposed to the
    applications. In some cases it may be backed by ordinary textures, while in
    others there may be a different kind of native resource used.
 */

/*!
    \enum QRhiRenderBuffer::Type
    Specifies the type of the renderbuffer

    \value DepthStencil Combined depth/stencil
    \value Color Color
 */

/*!
    \enum QRhiRenderBuffer::Flag
    Flag values for flags() and setFlags()

    \value UsedWithSwapChainOnly For DepthStencil renderbuffers this indicates
    that the renderbuffer is only used in combination with a QRhiSwapChain and
    never in other ways. Relevant with some backends, while others ignore it.
    With OpenGL where a separate windowing system interface API is in use (EGL,
    GLX, etc.), the flag is important since it avoids creating any actual
    resource as there is already a windowing system provided depth/stencil
    buffer as requested by QSurfaceFormat.
 */

/*!
    \internal
 */
QRhiRenderBuffer::QRhiRenderBuffer(QRhiImplementation *rhi, Type type_, const QSize &pixelSize_,
                                   int sampleCount_, Flags flags_)
    : QRhiResource(rhi),
      m_type(type_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_)
{
}

/*!
    \fn bool QRhiRenderBuffer::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1325 1326 1327
/*!
    \class QRhiTexture
    \inmodule QtRhi
1328
    \brief Texture resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
1329 1330
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 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 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
/*!
    \enum QRhiTexture::Flag

    Flag values to specify how the texture is going to be used. Not honoring
    the flags set before build() and attempting to use the texture in ways that
    was not declared upfront can lead to unspecified behavior or decreased
    performance depending on the backend and the underlying graphics API.

    \value RenderTarget The texture going to be used in combination with
    QRhiTextureRenderTarget

    \value ChangesFrequently Performance hint to indicate that the texture
    contents will change frequently and so staging buffers, if any, are to be
    kept alive to avoid performance hits

    \value CubeMap The texture is a cubemap. Such textures have 6 layers, one
    for each face in the order of +X, -X, +Y, -Y, +Z, -Z. Cubemap textures
    cannot be multisample.

     \value MipMapped The texture has mipmaps. The appropriate mip count is
     calculated automatically and can also be retrieved via
     QRhi::mipLevelsForSize(). The images for the mip levels have to be
     provided in the texture uploaded or generated via
     QRhiResourceUpdateBatch::generateMips(). Multisample textures cannot have
     mipmaps.

    \value sRGB Use an sRGB format

    \value UsedAsTransferSource The texture is used as the source of a texture
    copy or readback, meaning the texture is given as the source in
    QRhiResourceUpdateBatch::copyTexture() or
    QRhiResourceUpdateBatch::readBackTexture().

     \value UsedWithGenerateMips The texture is going to be used with
     QRhiResourceUpdateBatch::generateMips().
 */

/*!
    \enum QRhiTexture::Format

    Specifies the texture format. See also QRhi::isTextureFormatSupported() and
    note that flags() can modify the format when QRhiTexture::sRGB is set.

    \value UnknownFormat Not a valid format. This cannot be passed to setFormat().
    \value RGBA8
    \value BGRA8
    \value R8
    \value R16
    \value D16
    \value D32
    \value BC1
    \value BC2
    \value BC3
    \value BC4
    \value BC5
    \value BC6H
    \value BC7
    \value ETC2_RGB8
    \value ETC2_RGB8A1
    \value ETC2_RGBA8
    \value ASTC_4x4
    \value ASTC_5x4
    \value ASTC_5x5
    \value ASTC_6x5
    \value ASTC_6x6
    \value ASTC_8x5
    \value ASTC_8x6
    \value ASTC_8x8
    \value ASTC_10x5
    \value ASTC_10x6
    \value ASTC_10x8
    \value ASTC_10x10
    \value ASTC_12x10
    \value ASTC_12x12
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
/*!
    \internal
 */
QRhiTexture::QRhiTexture(QRhiImplementation *rhi, Format format_, const QSize &pixelSize_,
                         int sampleCount_, Flags flags_)
    : QRhiResource(rhi),
      m_format(format_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_)
{
}

/*!
    \fn bool QRhiTexture::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

/*!
    \return a pointer to a backend-specific QRhiNativeHandles subclass, such as
    QRhiVulkanTextureNativeHandles. The returned value is null when exposing
    the underlying native resources is not supported by the backend.

    \sa QRhiVulkanTextureNativeHandles, QRhiD3D11TextureNativeHandles,
    QRhiMetalTextureNativeHandles, QRhiGles2TextureNativeHandles
 */
const QRhiNativeHandles *QRhiTexture::nativeHandles()
{
    return nullptr;
}

/*!
    Similar to build() except that no new native textures are created. Instead,
    the texture from \a src is used.

    This allows importing an existing native texture object (which must belong
    to the same device or sharing context, depending on the graphics API) from
    an external graphics engine.

    \note format(), pixelSize(), sampleCount(), and flags() must still be set
    correctly. Passing incorrect sizes and other values to QRhi::newTexture()
    and then following it with a buildFrom() expecting that the native texture
    object alone is sufficient to deduce such values is \b wrong and will lead
    to problems.

    \note QRhiTexture does not take ownership of the texture object. release()
    does not free the object or any associated memory.

    The opposite of this operation, exposing a QRhiTexture-created native
    texture object to a foreign engine, is possible via nativeHandles().

    \sa QRhiVulkanTextureNativeHandles, QRhiD3D11TextureNativeHandles,
    QRhiMetalTextureNativeHandles, QRhiGles2TextureNativeHandles
 */
bool QRhiTexture::buildFrom(const QRhiNativeHandles *src)
{
    Q_UNUSED(src);
    return false;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1470 1471 1472
/*!
    \class QRhiSampler
    \inmodule QtRhi
1473
    \brief Sampler resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
1474 1475
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
/*!
    \enum QRhiSampler::Filter
    Specifies the minification, magnification, or mipmap filtering

    \value None Applicable only for mipmapMode(), indicates no mipmaps to be used
    \value Nearest
    \value Linear
 */

/*!
    \enum QRhiSampler::AddressMode
    Specifies the addressing mode

    \value Repeat
    \value ClampToEdge
    \value Border
    \value Mirror
    \value MirrorOnce
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1496
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
    \internal
 */
QRhiSampler::QRhiSampler(QRhiImplementation *rhi,
                         Filter magFilter_, Filter minFilter_, Filter mipmapMode_,
                         AddressMode u_, AddressMode v_, AddressMode w_)
    : QRhiResource(rhi),
      m_magFilter(magFilter_), m_minFilter(minFilter_), m_mipmapMode(mipmapMode_),
      m_addressU(u_), m_addressV(v_), m_addressW(w_)
{
}
1507

Laszlo Agocs's avatar
Laszlo Agocs committed
1508 1509 1510 1511
/*!
    \class QRhiRenderPassDescriptor
    \inmodule QtRhi
    \brief Render pass resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
1512 1513
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1514
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1515
    \internal
Laszlo Agocs's avatar
Laszlo Agocs committed
1516
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1517 1518 1519 1520
QRhiRenderPassDescriptor::QRhiRenderPassDescriptor(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1521 1522 1523 1524

/*!
    \class QRhiRenderTarget
    \inmodule QtRhi
1525
    \brief Represents an onscreen (swapchain) or offscreen (texture) render target.
Laszlo Agocs's avatar
Laszlo Agocs committed
1526 1527
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
/*!
    \enum QRhiRenderTarget::Type
    Specifies the type of the render target

    \value RtRef This is a reference to another resource's buffer(s). Used by
    targets returned from QRhiSwapChain::currentFrameRenderTarget().

    \value RtTexture This is a QRhiTextureRenderTarget.
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
/*!
    \internal
 */
QRhiRenderTarget::QRhiRenderTarget(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

/*!
    \fn QRhiRenderTarget::Type QRhiRenderTarget::type() const

    \return the type of the render target.
 */

/*!
    \fn QSize QRhiRenderTarget::sizeInPixels() const

    \return the size in pixels.
 */

/*!
    \fn float QRhiRenderTarget::devicePixelRatio() const

    \return the device pixel ratio. For QRhiTextureRenderTarget this is always
    1. For targets retrieved from a QRhiSwapChain the value reflects the
    \l{QWindow::devicePixelRatio()}{device pixel ratio} of the targeted
    QWindow.
 */

/*!
    \internal
 */
QRhiReferenceRenderTarget::QRhiReferenceRenderTarget(QRhiImplementation *rhi)
    : QRhiRenderTarget(rhi)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1575 1576 1577
/*!
    \class QRhiTextureRenderTarget
    \inmodule QtRhi
1578
    \brief Texture render target resource.
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597

    A texture render target allows rendering into one or more textures,
    optionally with a depth texture or depth/stencil renderbuffer.

    \note Textures used in combination with QRhiTextureRenderTarget must be
    created with the QRhiTexture::RenderTarget flag.

    The simplest example of creating a render target with a texture as its
    single color attachment:

    \badcode
        texture = rhi->newTexture(QRhiTexture::RGBA8, size, 1, QRhiTexture::RenderTarget);
        texture->build();
        rt = rhi->newTextureRenderTarget({ texture });
        rp = rt->newCompatibleRenderPassDescriptor();
        rt->setRenderPassDescriptor(rt);
        rt->build();
        // rt can now be used with beginPass()
    \endcode
Laszlo Agocs's avatar
Laszlo Agocs committed
1598 1599
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1600 1601
/*!
    \enum QRhiTextureRenderTarget::Flag
1602 1603 1604 1605 1606 1607

    Flag values describing the load/store behavior for the render target. The
    load/store behavior may be baked into native resources under the hood,
    depending on the backend, and therefore it needs to be known upfront and
    cannot be changed without rebuilding (and so releasing and creating new
    native resources).
Laszlo Agocs's avatar
Laszlo Agocs committed
1608 1609 1610 1611 1612 1613 1614 1615 1616

    \value PreserveColorContents Indicates that the contents of the color
    attachments is to be loaded when starting a render pass, instead of
    clearing. This is potentially more expensive, especially on mobile (tiled)
    GPUs, but allows preserving the existing contents between passes.

    \value PreserveDepthStencilContents Indicates that the contents of the
    depth texture is to be loaded when starting a render pass, instead
    clearing. Only applicable when a texture is used as the depth buffer
Laszlo Agocs's avatar
Laszlo Agocs committed
1617
    (QRhiTextureRenderTargetDescription::depthTexture() is set) because
Laszlo Agocs's avatar
Laszlo Agocs committed
1618 1619 1620 1621
    depth/stencil renderbuffers may not have any physical backing and data may
    not be written out in the first place.
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
/*!
    \internal
 */
QRhiTextureRenderTarget::QRhiTextureRenderTarget(QRhiImplementation *rhi,
                                                 const QRhiTextureRenderTargetDescription &desc_,
                                                 Flags flags_)
    : QRhiRenderTarget(rhi),
      m_desc(desc_),
      m_flags(flags_)
{
}

/*!
    \fn QRhiRenderPassDescriptor *QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor()

    \return a new QRhiRenderPassDescriptor that is compatible with this render
    target.

    The returned value is used in two ways: it can be passed to
    setRenderPassDescriptor() and
    QRhiGraphicsPipeline::setRenderPassDescriptor(). A render pass descriptor
    describes the attachments (color, depth/stencil) and the load/store
    behavior that can be affected by flags(). A QRhiGraphicsPipeline can only
    be used in combination with a render target that has the same
    QRhiRenderPassDescriptor set.

    Two QRhiTextureRenderTarget instances can share the same render pass
    descriptor as long as they have the same number and type of attachments.
    The associated QRhiTexture or QRhiRenderBuffer instances are not part of
    the render pass descriptor so those can differ in the two
    QRhiTextureRenderTarget intances.

    \note resources, such as QRhiTexture instances, referenced in description()
    must already be built

    \sa build()
 */

/*!
    \fn bool QRhiTextureRenderTarget::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \note renderPassDescriptor() must be set before calling build(). To obtain
    a QRhiRenderPassDescriptor compatible with the render target, call
    newCompatibleRenderPassDescriptor() before build() but after setting all
    other parameters, such as description() and flags(). To save resources,
    reuse the same QRhiRenderPassDescriptor with multiple
    QRhiTextureRenderTarget instances, whenever possible. Sharing the same
    render pass descriptor is only possible when the render targets have the
    same number and type of attachments (the actual textures can differ) and
    the same flags.

    \note resources, such as QRhiTexture instances, referenced in description()
    must already be built

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1684 1685 1686
/*!
    \class QRhiShaderResourceBindings
    \inmodule QtRhi
1687
    \brief Encapsulates resources for making buffer, texture, sampler resources visible to shaders.
Laszlo Agocs's avatar
Laszlo Agocs committed
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745

    A QRhiShaderResourceBindings is a collection of QRhiShaderResourceBinding
    instances, each of which describe a single binding.

    Take a fragment shader with the following interface:

    \badcode
        layout(std140, binding = 0) uniform buf {
            mat4 mvp;
            int flip;
        } ubuf;

        layout(binding = 1) uniform sampler2D tex;
    \endcode

    To make resources visible to the shader, the following
    QRhiShaderResourceBindings could be created and then passed to
    QRhiGraphicsPipeline::setShaderResourceBindings():

    \badcode
        srb = rhi->newShaderResourceBindings();
        srb->setBindings({
            QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf),
            QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, texture, sampler)
        });
        srb->build();
        ...
        ps = rhi->newGraphicsPipeline();
        ...
        ps->setShaderResourceBindings(srb);
        ps->build();
        ...
        cb->setGraphicsPipeline(ps);
    \endcode

    This assumes that \c ubuf is a QRhiBuffer, \c texture is a QRhiTexture,
    while \a sampler is a QRhiSampler. The example also assumes that the
    uniform block is present in the vertex shader as well so the same buffer is
    made visible to the vertex stage too.

    \section3 Advanced usage

    Building on the above example, let's assume that a pass now needs to use
    the exact same pipeline and shaders with a different texture. Creating a
    whole separate QRhiGraphicsPipeline just for this would be an overkill.
    This is why QRhiCommandBuffer::setGraphicsPipeline() allows specifying an
    optional \a srb argument. As long as the layouts (so the number of bindings
    and the binding points) match between two QRhiShaderResourceBindings, they
    can both be used with the same pipeline, assuming the pipeline was built
    with one of them in the first place.

    Creating and then using a new \c srb2 that is very similar to \c srb with
    the exception of referencing another texture could be implemented like the
    following:

    \badcode
        srb2 = rhi->newShaderResourceBindings();
        QVector<QRhiShaderResourceBinding> bindings = srb->bindings();
Laszlo Agocs's avatar
Laszlo Agocs committed
1746
        bindings[1] = QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, anotherTexture, sampler);
Laszlo Agocs's avatar
Laszlo Agocs committed
1747 1748 1749 1750 1751
        srb2->setBindings(bindings);
        srb2->build();
        ...
        cb->setGraphicsPipeline(ps, srb2);
    \endcode
Laszlo Agocs's avatar
Laszlo Agocs committed
1752 1753 1754
 */

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1755
    \internal
1756
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1757 1758 1759 1760
QRhiShaderResourceBindings::QRhiShaderResourceBindings(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}
1761 1762

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1763 1764 1765
    \class QRhiShaderResourceBinding
    \inmodule QtRhi
    \brief Specifies the shader resources that are made visible to one or more shader stages.
1766

Laszlo Agocs's avatar
Laszlo Agocs committed
1767 1768
    A QRhiShaderResourceBinding cannot be constructed directly. Instead, use
    the static functions uniformBuffer(), sampledTexture() to get an instance.
Laszlo Agocs's avatar
Laszlo Agocs committed
1769 1770
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1771
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1772 1773
    \enum QRhiShaderResourceBinding::Type
    Specifies type of the shader resource bound to a binding point
Laszlo Agocs's avatar
Laszlo Agocs committed
1774

Laszlo Agocs's avatar
Laszlo Agocs committed
1775 1776
    \value UniformBuffer Uniform buffer
    \value SampledTexture Combined image sampler
Laszlo Agocs's avatar
Laszlo Agocs committed
1777 1778 1779
 */

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1780 1781
    \enum QRhiShaderResourceBinding::StageFlag
    Flag values to indicate which stages the shader resource is visible in
Laszlo Agocs's avatar
Laszlo Agocs committed
1782

Laszlo Agocs's avatar
Laszlo Agocs committed
1783 1784 1785 1786
    \value VertexStage Vertex stage
    \value FragmentStage Fragment (pixel) stage
    \value TessellationControlStage Tessellation control (hull) stage
    \value TessellationEvaluationStage Tessellation evaluation (domain) stage
Laszlo Agocs's avatar
Laszlo Agocs committed
1787 1788 1789
 */

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1790
    \internal
Laszlo Agocs's avatar
Laszlo Agocs committed
1791
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1792 1793 1794 1795
QRhiShaderResourceBinding::QRhiShaderResourceBinding()
    : d(new QRhiShaderResourceBindingPrivate)
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1796 1797

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1798
    \internal
Laszlo Agocs's avatar
Laszlo Agocs committed
1799
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1800 1801 1802 1803 1804 1805 1806 1807 1808
void QRhiShaderResourceBinding::detach()
{
    if (d->ref.load() != 1) {
        QRhiShaderResourceBindingPrivate *newd = new QRhiShaderResourceBindingPrivate(d);
        if (!d->ref.deref())
            delete d;
        d = newd;
    }
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1809 1810

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1811 1812 1813 1814 1815 1816 1817
    \internal
 */
QRhiShaderResourceBinding::QRhiShaderResourceBinding(const QRhiShaderResourceBinding &other)
{
    d = other.d;
    d->ref.ref();
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1818

Laszlo Agocs's avatar
Laszlo Agocs committed
1819 1820
/*!
    \internal
Laszlo Agocs's avatar
Laszlo Agocs committed
1821
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
QRhiShaderResourceBinding &QRhiShaderResourceBinding::operator=(const QRhiShaderResourceBinding &other)
{
    if (d != other.d) {
        other.d->ref.ref();
        if (!d->ref.deref())
            delete d;
        d = other.d;
    }
    return *this;
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1832 1833

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1834 1835 1836 1837 1838 1839 1840
    Destructor.
 */
QRhiShaderResourceBinding::~QRhiShaderResourceBinding()
{
    if (!d->ref.deref())
        delete d;
}
1841

1842
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1843 1844
    \return a shader resource binding for the given binding number, pipeline
    stage, and buffer specified by \a binding, \a stage, and \a buf.
1845
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1846 1847
QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
        int binding, StageFlags stage, QRhiBuffer *buf)
1848
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
    QRhiShaderResourceBinding b;
    QRhiShaderResourceBindingPrivate *d = QRhiShaderResourceBindingPrivate::get(&b);
    Q_ASSERT(d->ref.load() == 1);
    d->binding = binding;
    d->stage = stage;
    d->type = UniformBuffer;
    d->u.ubuf.buf = buf;
    d->u.ubuf.offset = 0;
    d->u.ubuf.maybeSize = 0; // entire buffer
    return b;
1859 1860
}

1861
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1862 1863 1864
    \return a shader resource binding for the given binding number, pipeline
    stage, and buffer specified by \a binding, \a stage, and \a buf. This
    overload binds a region only, as specified by \a offset and \a size.
1865

Laszlo Agocs's avatar
Laszlo Agocs committed
1866 1867
    \note It is up to the user to ensure the offset is aligned to
    QRhi::ubufAlignment().
1868
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1869 1870
QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
        int binding, StageFlags stage, QRhiBuffer *buf, int offset, int size)
1871
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
    Q_ASSERT(size > 0);
    QRhiShaderResourceBinding b;
    QRhiShaderResourceBindingPrivate *d = QRhiShaderResourceBindingPrivate::get(&b);
    Q_ASSERT(d->ref.load() == 1);
    d->binding = binding;
    d->stage = stage;
    d->type = UniformBuffer;
    d->u.ubuf.buf = buf;
    d->u.ubuf.offset = offset;
    d->u.ubuf.maybeSize = size;
    return b;
1883 1884
}

1885
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1886 1887 1888
    \return a shader resource binding for the given binding number, pipeline
    stage, texture, and sampler specified by \a binding, \a stage, \a tex,
    \a sampler.
1889
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1890 1891
QRhiShaderResourceBinding QRhiShaderResourceBinding::sampledTexture(
        int binding, StageFlags stage, QRhiTexture *tex, QRhiSampler *sampler)
1892
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1893 1894 1895 1896 1897 1898 1899 1900 1901
    QRhiShaderResourceBinding b;
    QRhiShaderResourceBindingPrivate *d = QRhiShaderResourceBindingPrivate::get(&b);
    Q_ASSERT(d->ref.load() == 1);
    d->binding = binding;
    d->stage = stage;
    d->type = SampledTexture;
    d->u.stex.tex = tex;
    d->u.stex.sampler = sampler;
    return b;
1902 1903
}

1904
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1905 1906 1907
    \class QRhiGraphicsPipeline
    \inmodule QtRhi
    \brief Graphics pipeline state resource.
1908

Laszlo Agocs's avatar
Laszlo Agocs committed
1909 1910 1911
    \note Setting the shader resource bindings is mandatory. The referenced
    QRhiShaderResourceBindings must already be built by the time build() is
    called.
1912

Laszlo Agocs's avatar
Laszlo Agocs committed
1913 1914 1915 1916
    \note Setting the render pass descriptor is mandatory. To obtain a
    QRhiRenderPassDescriptor that can be passed to setRenderPassDescriptor(),
    use either QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor() or
    QRhiSwapChain::newCompatibleRenderPassDescriptor().
1917

Laszlo Agocs's avatar
Laszlo Agocs committed
1918
    \note Setting the vertex input layout is mandatory.
1919

Laszlo Agocs's avatar
Laszlo Agocs committed
1920
    \note Setting the shader stages is mandatory.
1921

Laszlo Agocs's avatar
Laszlo Agocs committed
1922 1923
    \note sampleCount() defaults to 1 and must match the sample count of the
    render target's color and depth stencil attachments.
1924

Laszlo Agocs's avatar
Laszlo Agocs committed
1925 1926
    \note The depth test, depth write, and stencil test are disabled by
    default.
1927

Laszlo Agocs's avatar
Laszlo Agocs committed
1928 1929
    \note stencilReadMask() and stencilWriteMask() apply to both faces. They
    both default to 0xFF.
1930
 */
1931

1932
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1933 1934 1935 1936 1937 1938 1939
    \fn void QRhiGraphicsPipeline::setTargetBlends(const QVector<TargetBlend> &blends)

    Sets the blend specification for color attachments. Each element in \a
    blends corresponds to a color attachment of the render target.

    By default no blends are set, which is a shortcut to disabling blending and
    enabling color write for all four channels.
1940
 */
1941

1942
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1943
    \enum QRhiGraphicsPipeline::Flag
1944

Laszlo Agocs's avatar
Laszlo Agocs committed
1945
    Flag values for describing the dynamic state of the pipeline. The viewport is always dynamic.
1946

Laszlo Agocs's avatar
Laszlo Agocs committed
1947 1948
    \value UsesBlendConstants Indicates that a blend color constant will be set
    via QRhiCommandBuffer::setBlendConstants()
1949

Laszlo Agocs's avatar
Laszlo Agocs committed
1950 1951
    \value UsesStencilRef Indicates that a stencil reference value will be set
    via QRhiCommandBuffer::setStencilRef()
1952

Laszlo Agocs's avatar
Laszlo Agocs committed
1953 1954
    \value UsesScissor Indicates that a scissor rectangle will be set via
    QRhiCommandBuffer::setScissor()
1955 1956 1957
 */

/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1958 1959
    \enum QRhiGraphicsPipeline::Topology
    Specifies the primitive topology
1960