qrhi.cpp 144 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

    \brief Accelerated 2D/3D graphics API abstraction.
Laszlo Agocs's avatar
Laszlo Agocs committed
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

     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().

89 90 91 92 93 94 95
    \badcode
        vbuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
        if (!vbuf->build()) { error }
        ...
        vbuf->releaseAndDestroy();
    \endcode

Laszlo Agocs's avatar
Laszlo Agocs committed
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
    \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
125 126 127 128 129 130 131
    native resource that may still be in use by an in-flight frame.

    \li Note that this does not mean that resources can freely be released
    within a frame (that is, in a
    \l{QRhiCommandBuffer::beginFrame()}{beginFrame()} -
    \l{QRhiCommandBuffer::endFrame()}{endFrame()} section). As a general rule,
    all referenced QRhiResource objects must stay unchanged until the frame is
Laszlo Agocs's avatar
Laszlo Agocs committed
132 133 134 135
    submitted by calling \l{QRhiCommandBuffer::endFrame()}{endFrame()}. To ease
    this, QRhiResource::releaseAndDestroyLater() is provided as a convenience.
    This allows applications to safely issue a (defered) releaseAndDestroy()
    while recording a frame.
Laszlo Agocs's avatar
Laszlo Agocs committed
136 137 138

    \endlist

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    \section3 Command buffers and defered command execution

    Regardless of the design and capabilities of the underlying graphics API,
    all QRhi backends implement some level of command buffers. No
    QRhiCommandBuffer function issues any native bind or draw command (such as,
    \c glDrawElements) directly. Commands are always recorded in a queue,
    either native or provided by the QRhi backend. The command buffer is
    submitted, and so execution starts only upon QRhi::endFrame() or
    QRhi::finish().

    The defered nature has consequences for some types of objects. For example,
    writing to a dynamic buffer multiple times within a frame, in case such
    buffers are backed by host-visible memory, will result in making the
    results of all writes are visible to all draw calls in the command buffer
    of the frame, regardless of when the dynamic buffer update was recorded
    relative to a draw call.

    Furthermore, instances of QRhiResource subclasses must be treated immutable
    within a frame in which they are referenced in any way. Create or rebuild
    all resources upfront, before starting to record commands for the next
    frame. Reusing a QRhiResource instance within a frame (by rebuilding it and
    then referencing it again in the same \c{beginFrame - endFrame} section)
    should be avoided as it may lead to unexpected results, depending on the
Laszlo Agocs's avatar
Laszlo Agocs committed
162 163 164 165 166 167 168 169 170 171
    backend.

    As a general rule, all referenced QRhiResource objects must stay valid and
    unmodified until the frame is submitted by calling
    \l{QRhiCommandBuffer::endFrame()}{endFrame()}. On the other hand,
    \l{QRhiResource::release()}{release()} or
    \l{QRhiResource::releaseAndDestroy()}{releaseAndDestroy()} are always safe
    to call once the frame is submitted, regardless of the status of the
    underlying native resources (which may still be in use by the GPU - but
    that is taken care of internally).
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

    Unlike APIs like OpenGL, upload and copy type of commands cannot be mixed
    with draw commands. The typical renderer will involve a sequence similar to
    the following: \c{(re)build resources} - \c{begin frame} - \c{record
    uploads and copies} - \c{start renderpass} - \c{record draw calls} - \c{end
    renderpass} - \c{end frame}. Recording copy type of operations happens via
    QRhiResourceUpdateBatch. Such operations are committed typically on
    \l{QRhiCommandBuffer::beginPass()}{beginPass()}.

    When working with legacy rendering engines designed for OpenGL, the
    migration to QRhi often involves redesigning from having a single \c render
    step (that performs copies and uploads, clears buffers, and issues draw
    calls, all mixed together) to a clearly separated, two phase \c prepare -
    \c render setup where the \c render step only starts a renderpass and
    records draw calls, while all resource creation and queuing of updates,
    uploads and copies happens beforehand, in the \c prepare step.
Laszlo Agocs's avatar
Laszlo Agocs committed
188 189 190

    \section3 Resource reuse

191 192 193
    From the user's point of view a QRhiResource is reusable immediately after
    calling QRhiResource::release(). With the exception of swapchains, calling
    \c build() on an already built object does an implicit \c release(). This
Laszlo Agocs's avatar
Laszlo Agocs committed
194
    provides a handy shortcut to reuse a QRhiResource instance with different
195
    parameters, with a new native graphics object underneath.
Laszlo Agocs's avatar
Laszlo Agocs committed
196 197 198

    The importance of reusing the same object lies in the fact that some
    objects reference other objects: for example, a QRhiShaderResourceBindings
Laszlo Agocs's avatar
Laszlo Agocs committed
199 200 201 202 203 204 205 206 207
    can reference QRhiBuffer, QRhiTexture, and QRhiSampler instances. If in a
    later frame 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.
Laszlo Agocs's avatar
Laszlo Agocs committed
208 209 210 211 212

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

213
        srb = rhi->newShaderResourceBindings()
Laszlo Agocs's avatar
Laszlo Agocs committed
214 215 216 217 218 219 220
        srb->setBindings({
            QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf)
        });
        srb->build();

        ...

221
        // now in a later frame we need to grow the buffer to a larger size
Laszlo Agocs's avatar
Laszlo Agocs committed
222 223 224 225 226 227 228 229
        ubuf->setSize(512);
        ubuf->build(); // same as ubuf->release(); ubuf->build();

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

    \section3 Pooled objects

230 231 232 233 234 235 236 237 238
    In addition to resources, there are pooled objects as well, such as,
    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().
Laszlo Agocs's avatar
Laszlo Agocs committed
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 286

    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.

287
    \section3 Threading
288

289 290 291 292 293
    A QRhi instance and the associated resources can be created and used on any
    thread but all usage must be limited to that one single thread. When
    rendering to multiple QWindows in an application, having a dedicated thread
    and QRhi instance for each window is often advisable, as this can eliminate
    issues with unexpected throttling caused by presenting to multiple windows.
294

Laszlo Agocs's avatar
gl: rsh  
Laszlo Agocs committed
295 296 297 298
    When it comes to externally created native objects, such as OpenGL contexts
    passed in via QRhiGles2NativeHandles, it is up to the application to ensure
    they are not misused by other threads.

299 300 301 302 303 304
    Resources are not shareable between QRhi instances. This is an intentional
    choice since QRhi hides most queue, command buffer, and resource
    synchronization related tasks, and provides no API for them. Safe and
    efficient concurrent use of graphics resources from multiple threads is
    tied deeply to those concepts, however, and is thus a topic that is
    currently out of scope, but may be introduced in the future.
Laszlo Agocs's avatar
Laszlo Agocs committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
 */

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

356 357
    \value MultisampleTexture Indicates that textures with a sample count larger
    than 1 are supported.
358

359 360
    \value MultisampleRenderBuffer Indicates that renderbuffers with a sample
    count larger than 1 are supported.
361

362
    \value DebugMarkers Indicates that debug marker groups (and so
363 364
    QRhiCommandBuffer::debugMarkBegin()) are supported.

365 366
    \value Timestamps Indicates that command buffer timestamps are supported.
    Relevant for QRhiProfiler::gpuFrameTimes().
367

368
    \value Instancing Indicates that instanced drawing is supported.
369

370 371
    \value CustomInstanceStepRate Indicates that instance step rates other than
    1 are supported.
372

373 374
    \value PrimitiveRestart Indicates that restarting the assembly of
    primitives when encountering an index value of 0xFFFF
375
    (\l{QRhiCommandBuffer::IndexUInt16}{IndexUInt16}) or 0xFFFFFFFF
376 377 378 379 380
    (\l{QRhiCommandBuffer::IndexUInt32}{IndexUInt32}) is enabled, for certain
    primitive topologies at least. QRhi will try to enable this with all
    backends, but in some cases it will not be supported. Dynamically
    controlling primitive restart is not possible since with some APIs
    primitive restart with a fixed index is always on. Applications must assume
381 382 383 384 385 386
    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}.
387 388 389 390 391

    \value GeometryShaders Indicates that geometry shaders are supported.

    \value TessellationShaders Indicates that tessellation control and
    evaluation shaders are supported.
392 393 394 395 396 397 398

    \value NonDynamicUniformBuffers Indicates that creating buffers with the
    usage \l{QRhiBuffer::UniformBuffer}{UniformBuffer} and the types
    \l{QRhiBuffer::Immutable}{Immutable} or \l{QRhiBuffer::Static}{Static} is
    supported. When reported as unsupported, uniform (constant) buffers must be
    created as \l{QRhiBuffer::Dynamic}{Dynamic}. (which is recommended
    regardless)
399 400 401 402 403 404

    \value NonFourAlignedEffectiveIndexBufferOffset Indicates that effective
    index buffer offsets (\c{indexOffset + firstIndex * indexComponentSize})
    that are not 4 byte aligned are supported. When not supported, attempting
    to issue a \l{QRhiCommandBuffer::drawIndexed()}{drawIndexed()} with a
    non-aligned effective offset may lead to unspecified behavior.
405 406 407

    \value NPOTTextureRepeat Indicates that the \l{QRhiSampler::Repeat}{Repeat}
    mode is supported for textures with a non-power-of-two size.
408 409 410 411 412 413

    \value RedOrAlpha8IsRed Indicates that the
    \l{QRhiTexture::RED_OR_ALPHA8}{RED_OR_ALPHA8} format maps to a one
    component 8-bit \c red format. This is the case for all backends except
    OpenGL, where \c{GL_ALPHA}, a one component 8-bit \c alpha format, is used
    instead. This is relevant for shader code that samples from the texture.
Laszlo Agocs's avatar
Laszlo Agocs committed
414 415
 */

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
/*!
    \enum QRhi::BeginFrameFlag
    Flag values for QRhi::beginFrame()
 */

/*!
    \enum QRhi::EndFrameFlag
    Flag values for QRhi::endFrame()

    \value SkipPresent Specifies that no present command is to be queued or no
    swapBuffers call is to be made. This way no image is presented. Generating
    multiple frames with all having this flag set is not recommended (except,
    for example, for benchmarking purposes - but keep in mind that backends may
    behave differently when it comes to waiting for command completion without
    presenting so the results are not comparable between them)
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
433
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
434
    \enum QRhi::ResourceLimit
Laszlo Agocs's avatar
Laszlo Agocs committed
435 436 437 438 439 440 441 442 443 444 445
    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
446 447 448 449 450 451

    \value MaxColorAttachments The maximum number of color attachments for a
    QRhiTextureRenderTarget, in case multiple render targets are supported. When
    MRT is not supported, the value is 1. Otherwise this is typically 8, but
    watch out for the fact that OpenGL only mandates 4 as the minimum, and that
    is what some OpenGL ES implementations provide.
Laszlo Agocs's avatar
Laszlo Agocs committed
452 453 454 455 456
 */

/*!
    \class QRhiInitParams
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
457
    \brief Base class for backend-specific initialization parameters.
458 459

    Contains fields that are relevant to all backends.
Laszlo Agocs's avatar
Laszlo Agocs committed
460 461 462 463 464
 */

/*!
    \class QRhiColorClearValue
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
465
    \brief Specifies a clear color for a color buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
466 467
 */

468 469 470
/*!
    Constructs a color clear value with \c{(0, 0, 0, 1)} (opaque black).
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
471 472 473 474 475
QRhiColorClearValue::QRhiColorClearValue()
    : m_rgba(0, 0, 0, 1)
{
}

476 477 478 479
/*!
    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
480 481 482 483 484
QRhiColorClearValue::QRhiColorClearValue(const QVector4D &c)
    : m_rgba(c)
{
}

485 486 487 488
/*!
    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
489 490 491 492 493
QRhiColorClearValue::QRhiColorClearValue(float r, float g, float b, float a)
    : m_rgba(r, g, b, a)
{
}

494
/*!
495
    \return \c true if the colors in the two QRhiColorClearValue objects \a a
496 497 498 499 500 501 502 503 504 505
    and \a b are equal.

    \relates QRhiColorClearValue
 */
bool operator==(const QRhiColorClearValue &a, const QRhiColorClearValue &b) Q_DECL_NOTHROW
{
    return a.rgba() == b.rgba();
}

/*!
506
    \return \c false if the colors in the two QRhiColorClearValue objects \a a
507 508 509 510 511 512 513 514 515 516
    and \a b are equal; otherwise returns \c true.

    \relates QRhiColorClearValue
*/
bool operator!=(const QRhiColorClearValue &a, const QRhiColorClearValue &b) Q_DECL_NOTHROW
{
    return !(a == b);
}

/*!
517
    \return the hash value for \a v, using \a seed to seed the calculation.
518 519 520 521 522 523 524 525 526

    \relates QRhiColorClearValue
 */
uint qHash(const QRhiColorClearValue &v, uint seed) Q_DECL_NOTHROW
{
    const QVector4D c = v.rgba();
    return qFloor((c.x() + c.y() + c.z() + c.w()) * 1000) + seed;
}

527 528 529 530 531 532 533 534 535 536 537 538 539 540
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QRhiColorClearValue &v)
{
    QDebugStateSaver saver(dbg);
    const QVector4D c = v.rgba();
    dbg.nospace() << "QRhiColorClearValue(r=" << c.x()
                  << " g=" << c.y()
                  << " b=" << c.z()
                  << " a=" << c.w()
                  << ')';
    return dbg;
}
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
541 542 543
/*!
    \class QRhiDepthStencilClearValue
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
544
    \brief Specifies clear values for a depth or stencil buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
545 546
 */

547 548 549 550
/*!
    Constructs a depth/stencil clear value with depth clear value 1.0f and
    stencil clear value 0.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
551 552 553 554 555 556
QRhiDepthStencilClearValue::QRhiDepthStencilClearValue()
    : m_d(1),
      m_s(0)
{
}

557 558 559 560
/*!
    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
561 562 563 564 565 566
QRhiDepthStencilClearValue::QRhiDepthStencilClearValue(float d, quint32 s)
    : m_d(d),
      m_s(s)
{
}

567
/*!
568
    \return \c true if the values in the two QRhiDepthStencilClearValue objects
569 570 571 572 573 574 575 576 577 578 579
    \a a and \a b are equal.

    \relates QRhiDepthStencilClearValue
 */
bool operator==(const QRhiDepthStencilClearValue &a, const QRhiDepthStencilClearValue &b) Q_DECL_NOTHROW
{
    return a.depthClearValue() == b.depthClearValue()
            && a.stencilClearValue() == b.stencilClearValue();
}

/*!
580
    \return \c false if the values in the two QRhiDepthStencilClearValue
581 582 583 584 585 586 587 588 589 590
    objects \a a and \a b are equal; otherwise returns \c true.

    \relates QRhiDepthStencilClearValue
*/
bool operator!=(const QRhiDepthStencilClearValue &a, const QRhiDepthStencilClearValue &b) Q_DECL_NOTHROW
{
    return !(a == b);
}

/*!
591
    \return the hash value for \a v, using \a seed to seed the calculation.
592 593 594 595 596 597 598 599

    \relates QRhiDepthStencilClearValue
 */
uint qHash(const QRhiDepthStencilClearValue &v, uint seed) Q_DECL_NOTHROW
{
    return seed * (qFloor(v.depthClearValue() * 100) + v.stencilClearValue());
}

600 601 602 603 604 605 606 607 608 609 610
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QRhiDepthStencilClearValue &v)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "QRhiDepthStencilClearValue(depth-clear=" << v.depthClearValue()
                  << " stencil-clear=" << v.stencilClearValue()
                  << ')';
    return dbg;
}
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
611 612 613
/*!
    \class QRhiViewport
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
614
    \brief Specifies a viewport rectangle.
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632

    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
633 634
 */

635 636 637 638 639 640
/*!
    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
641 642 643 644 645 646 647
QRhiViewport::QRhiViewport()
    : m_rect(0, 0, 1280, 720),
      m_minDepth(0),
      m_maxDepth(1)
{
}

648 649 650 651 652 653 654 655
/*!
    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
656 657 658 659 660 661 662
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)
{
}

663
/*!
664
    \return \c true if the values in the two QRhiViewport objects
665 666 667 668 669 670 671 672 673 674 675 676
    \a a and \a b are equal.

    \relates QRhiViewport
 */
bool operator==(const QRhiViewport &a, const QRhiViewport &b) Q_DECL_NOTHROW
{
    return a.viewport() == b.viewport()
            && a.minDepth() == b.minDepth()
            && a.maxDepth() == b.maxDepth();
}

/*!
677
    \return \c false if the values in the two QRhiViewport
678 679 680 681 682 683 684 685 686 687
    objects \a a and \a b are equal; otherwise returns \c true.

    \relates QRhiViewport
*/
bool operator!=(const QRhiViewport &a, const QRhiViewport &b) Q_DECL_NOTHROW
{
    return !(a == b);
}

/*!
688
    \return the hash value for \a v, using \a seed to seed the calculation.
689 690 691 692 693 694 695 696 697

    \relates QRhiViewport
 */
uint qHash(const QRhiViewport &v, uint seed) Q_DECL_NOTHROW
{
    const QVector4D r = v.viewport();
    return seed + r.x() + r.y() + r.z() + r.w() + qFloor(v.minDepth() * 100) + qFloor(v.maxDepth() * 100);
}

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QRhiViewport &v)
{
    QDebugStateSaver saver(dbg);
    const QVector4D r = v.viewport();
    dbg.nospace() << "QRhiViewport(bottom-left-x=" << r.x()
                  << " bottom-left-y=" << r.y()
                  << " width=" << r.z()
                  << " height=" << r.w()
                  << " minDepth=" << v.minDepth()
                  << " maxDepth=" << v.maxDepth()
                  << ')';
    return dbg;
}
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
714 715 716
/*!
    \class QRhiScissor
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
717
    \brief Specifies a scissor rectangle.
718 719 720 721 722

    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
723
    \note QRhi assumes OpenGL-style scissor coordinates, meaning x and y are
724 725 726
    bottom-left.

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

729 730 731
/*!
    Constructs an empty scissor.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
732 733 734 735
QRhiScissor::QRhiScissor()
{
}

736 737 738 739 740 741
/*!
    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
742 743 744 745
QRhiScissor::QRhiScissor(int x, int y, int w, int h)
    : m_rect(x, y, w, h)
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
746

747
/*!
748
    \return \c true if the values in the two QRhiScissor objects
749 750 751 752 753 754 755 756 757 758
    \a a and \a b are equal.

    \relates QRhiScissor
 */
bool operator==(const QRhiScissor &a, const QRhiScissor &b) Q_DECL_NOTHROW
{
    return a.scissor() == b.scissor();
}

/*!
759
    \return \c false if the values in the two QRhiScissor
760 761 762 763 764 765 766 767 768 769
    objects \a a and \a b are equal; otherwise returns \c true.

    \relates QRhiScissor
*/
bool operator!=(const QRhiScissor &a, const QRhiScissor &b) Q_DECL_NOTHROW
{
    return !(a == b);
}

/*!
770
    \return the hash value for \a v, using \a seed to seed the calculation.
771 772 773 774 775 776 777 778 779

    \relates QRhiScissor
 */
uint qHash(const QRhiScissor &v, uint seed) Q_DECL_NOTHROW
{
    const QVector4D r = v.scissor();
    return seed + r.x() + r.y() + r.z() + r.w();
}

780 781 782 783 784 785 786 787 788 789 790 791 792 793
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QRhiScissor &s)
{
    QDebugStateSaver saver(dbg);
    const QVector4D r = s.scissor();
    dbg.nospace() << "QRhiScissor(bottom-left-x=" << r.x()
                  << " bottom-left-y=" << r.y()
                  << " width=" << r.z()
                  << " height=" << r.w()
                  << ')';
    return dbg;
}
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
794
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
795
    \class QRhiVertexInputBinding
Laszlo Agocs's avatar
Laszlo Agocs committed
796
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
797
    \brief Describes a vertex input binding.
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

    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
816
        inputLayout.setBindings({
817 818
            { 3 * sizeof(float) },
            { 2 * sizeof(float) }
Laszlo Agocs's avatar
Laszlo Agocs committed
819
        });
820 821 822
    \endcode

    Only the stride is interesting here since instancing is not used. The
Laszlo Agocs's avatar
Laszlo Agocs committed
823
    binding number is given by the index of the QRhiVertexInputBinding
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    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
844 845
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
846
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
847
    \enum QRhiVertexInputBinding::Classification
Laszlo Agocs's avatar
Laszlo Agocs committed
848 849 850 851 852 853
    Describes the input data classification.

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

854 855 856
/*!
    Constructs an empty vertex input binding description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
857 858 859 860
QRhiVertexInputBinding::QRhiVertexInputBinding()
{
}

861 862 863 864 865 866 867
/*!
    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
868 869 870 871 872 873 874
QRhiVertexInputBinding::QRhiVertexInputBinding(quint32 stride, Classification cls, int stepRate)
    : m_stride(stride),
      m_classification(cls),
      m_instanceStepRate(stepRate)
{
}

875
/*!
876
    \return \c true if the values in the two QRhiVertexInputBinding objects
877 878 879 880 881 882 883 884 885 886 887 888
    \a a and \a b are equal.

    \relates QRhiVertexInputBinding
 */
bool operator==(const QRhiVertexInputBinding &a, const QRhiVertexInputBinding &b) Q_DECL_NOTHROW
{
    return a.stride() == b.stride()
            && a.classification() == b.classification()
            && a.instanceStepRate() == b.instanceStepRate();
}

/*!
889
    \return \c false if the values in the two QRhiVertexInputBinding
890 891 892 893 894 895 896 897 898 899
    objects \a a and \a b are equal; otherwise returns \c true.

    \relates QRhiVertexInputBinding
*/
bool operator!=(const QRhiVertexInputBinding &a, const QRhiVertexInputBinding &b) Q_DECL_NOTHROW
{
    return !(a == b);
}

/*!
900
    \return the hash value for \a v, using \a seed to seed the calculation.
901 902 903 904 905 906 907 908

    \relates QRhiVertexInputBinding
 */
uint qHash(const QRhiVertexInputBinding &v, uint seed) Q_DECL_NOTHROW
{
    return seed + v.stride() + v.classification();
}

909 910 911 912 913 914 915 916 917 918 919 920
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QRhiVertexInputBinding &b)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "QRhiVertexInputBinding(stride=" << b.stride()
                  << " cls=" << b.classification()
                  << " step-rate=" << b.instanceStepRate()
                  << ')';
    return dbg;
}
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
921
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
922
    \class QRhiVertexInputAttribute
Laszlo Agocs's avatar
Laszlo Agocs committed
923
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
924
    \brief Describes a single vertex input element.
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946

    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
947
        inputLayout.setBindings({
948 949
            { 3 * sizeof(float) },
            { 2 * sizeof(float) }
Laszlo Agocs's avatar
Laszlo Agocs committed
950 951 952 953 954
        });
        inputLayout.setAttributes({
            { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
            { 1, 1, QRhiVertexInputAttribute::Float2, 0 }
        });
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    \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
972
        inputLayout.setBindings({
973
            { 5 * sizeof(float) }
Laszlo Agocs's avatar
Laszlo Agocs committed
974 975 976 977 978
        });
        inputLayout.setAttributes({
            { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
            { 0, 1, QRhiVertexInputAttribute::Float2, 3 * sizeof(float) }
        });
979 980 981 982 983 984 985 986 987
    \endcode

    and then:

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

    \sa QRhiCommandBuffer::setVertexInput()
Laszlo Agocs's avatar
Laszlo Agocs committed
988 989
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
990
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
991
    \enum QRhiVertexInputAttribute::Format
Laszlo Agocs's avatar
Laszlo Agocs committed
992 993 994 995 996 997 998 999 1000 1001 1002
    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
 */

1003 1004 1005
/*!
    Constructs an empty vertex input attribute description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1006 1007 1008 1009
QRhiVertexInputAttribute::QRhiVertexInputAttribute()
{
}

1010 1011 1012 1013
/*!
    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
1014 1015 1016 1017 1018 1019 1020 1021
QRhiVertexInputAttribute::QRhiVertexInputAttribute(int binding, int location, Format format, quint32 offset)
    : m_binding(binding),
      m_location(location),
      m_format(format),
      m_offset(offset)
{
}

1022
/*!
1023
    \return \c true if the values in the two QRhiVertexInputAttribute objects
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    \a a and \a b are equal.

    \relates QRhiVertexInputAttribute
 */
bool operator==(const QRhiVertexInputAttribute &a, const QRhiVertexInputAttribute &b) Q_DECL_NOTHROW
{
    return a.binding() == b.binding()
            && a.location() == b.location()
            && a.format() == b.format()
            && a.offset() == b.offset();
}

/*!
1037
    \return \c false if the values in the two QRhiVertexInputAttribute
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    objects \a a and \a b are equal; otherwise returns \c true.

    \relates QRhiVertexInputAttribute
*/
bool operator!=(const QRhiVertexInputAttribute &a, const QRhiVertexInputAttribute &b) Q_DECL_NOTHROW
{
    return !(a == b);
}

/*!
1048
    \return the hash value for \a v, using \a seed to seed the calculation.
1049 1050 1051 1052 1053 1054 1055 1056

    \relates QRhiVertexInputAttribute
 */
uint qHash(const QRhiVertexInputAttribute &v, uint seed) Q_DECL_NOTHROW
{
    return seed + v.binding() + v.location() + v.format() + v.offset();
}

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QRhiVertexInputAttribute &a)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "QRhiVertexInputAttribute(binding=" << a.binding()
                  << " location=" << a.location()
                  << " format=" << a.format()
                  << " offset=" << a.offset()
                  << ')';
    return dbg;
}
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
1070 1071 1072 1073
/*!
    \class QRhiVertexInputLayout
    \inmodule QtRhi
    \brief Describes the layout of vertex inputs consumed by a vertex shader.
1074 1075 1076

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

1079 1080 1081
/*!
    Constructs an empty vertex input layout description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1082 1083 1084 1085
QRhiVertexInputLayout::QRhiVertexInputLayout()
{
}

1086
/*!
1087
    \return \c true if the values in the two QRhiVertexInputLayout objects
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    \a a and \a b are equal.

    \relates QRhiVertexInputLayout
 */
bool operator==(const QRhiVertexInputLayout &a, const QRhiVertexInputLayout &b) Q_DECL_NOTHROW
{
    return a.bindings() == b.bindings()
            && a.attributes() == b.attributes();
}

/*!
1099
    \return \c false if the values in the two QRhiVertexInputLayout
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
    objects \a a and \a b are equal; otherwise returns \c true.

    \relates QRhiVertexInputLayout
*/
bool operator!=(const QRhiVertexInputLayout &a, const QRhiVertexInputLayout &b) Q_DECL_NOTHROW
{
    return !(a == b);
}

/*!
1110
    \return the hash value for \a v, using \a seed to seed the calculation.
1111 1112 1113 1114 1115 1116 1117 1118

    \relates QRhiVertexInputLayout
 */
uint qHash(const QRhiVertexInputLayout &v, uint seed) Q_DECL_NOTHROW
{
    return qHash(v.bindings(), seed) + qHash(v.attributes(), seed);
}

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QRhiVertexInputLayout &v)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "QRhiVertexInputLayout(bindings=" << v.bindings()
                  << " attributes=" << v.attributes()
                  << ')';
    return dbg;
}
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
1130 1131 1132
/*!
    \class QRhiGraphicsShaderStage
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
1133
    \brief Specifies the type and the shader code for a shader stage in the graphics pipeline.
1134

1135 1136 1137 1138
    \note Some backends only support a subset of the stages. Use
    QRhi::isFeatureSupported() to query for support at runtime. For example,
    Metal has no geometry shader support, while the OpenGL 2.x backend only
    supports the vertex and fragment stages.
Laszlo Agocs's avatar
Laszlo Agocs committed
1139 1140
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1141 1142 1143 1144 1145 1146
/*!
    \enum QRhiGraphicsShaderStage::Type
    Specifies the type of the shader stage.

    \value Vertex Vertex stage
    \value Fragment Fragment (pixel) stage
1147
    \value Geometry Geometry stage
Laszlo Agocs's avatar
Laszlo Agocs committed
1148 1149 1150 1151
    \value TessellationControl Tessellation control (hull) stage
    \value TessellationEvaluation Tessellation evaluation (domain) stage
 */

1152 1153 1154
/*!
    Constructs an empty shader stage description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1155 1156 1157
QRhiGraphicsShaderStage::QRhiGraphicsShaderStage()
{
}
1158

1159 1160 1161
/*!
    Constructs a shader stage description with the \a type of the stage and the
    \a shader.
1162 1163 1164 1165 1166

    The shader variant \a v defaults to QBakedShaderKey::StandardShader. A
    QBakedShader pack contains multiple source and binary versions of a shader.
    In addition, it can also contain variants of the shader with slightly
    modified code. \a v can then be used to select the desired variant.
1167
 */
1168
QRhiGraphicsShaderStage::QRhiGraphicsShaderStage(Type type, const QBakedShader &shader, QBakedShaderKey::ShaderVariant v)
Laszlo Agocs's avatar
Laszlo Agocs committed
1169
    : m_type(type),
1170 1171
      m_shader(shader),
      m_shaderVariant(v)
Laszlo Agocs's avatar
Laszlo Agocs committed
1172 1173
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1174

1175
/*!
1176
    \return \c true if the values in the two QRhiGraphicsShaderStage objects
1177 1178 1179 1180 1181 1182 1183
    \a a and \a b are equal.

    \relates QRhiGraphicsShaderStage
 */
bool operator==(const QRhiGraphicsShaderStage &a, const QRhiGraphicsShaderStage &b) Q_DECL_NOTHROW
{
    return a.type() == b.type()
1184 1185
            && a.shader() == b.shader()
            && a.shaderVariant() == b.shaderVariant();
1186 1187 1188
}

/*!
1189
    \return \c false if the values in the two QRhiGraphicsShaderStage
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    objects \a a and \a b are equal; otherwise returns \c true.

    \relates QRhiGraphicsShaderStage
*/
bool operator!=(const QRhiGraphicsShaderStage &a, const QRhiGraphicsShaderStage &b) Q_DECL_NOTHROW
{
    return !(a == b);
}

/*!
1200
    \return the hash value for \a v, using \a seed to seed the calculation.
1201 1202 1203 1204 1205

    \relates QRhiGraphicsShaderStage
 */
uint qHash(const QRhiGraphicsShaderStage &v, uint seed) Q_DECL_NOTHROW
{
1206
    return v.type() + qHash(v.shader(), seed) + v.shaderVariant();
1207 1208
}

1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QRhiGraphicsShaderStage &s)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "QRhiGraphicsShaderStage(type=" << s.type()
                  << " shader=" << s.shader()
                  << " variant=" << s.shaderVariant()
                  << ')';
    return dbg;
}
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
1221
/*!
Laszlo Agocs's avatar
Laszlo Agocs committed
1222
    \class QRhiColorAttachment
Laszlo Agocs's avatar
Laszlo Agocs committed
1223
    \inmodule QtRhi
1224 1225 1226
    \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
1227
    former, when texture() is set, is used in most cases.
1228

Laszlo Agocs's avatar
Laszlo Agocs committed
1229 1230
    \note texture() and renderBuffer() cannot be both set (be non-null at the
    same time).
1231 1232 1233 1234 1235 1236 1237 1238

    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
1239
    When targeting a non-multisample texture, the layer() and level()
1240 1241 1242
    indicate the targeted layer (face index \c{0-5} for cubemaps) and mip
    level.

Laszlo Agocs's avatar
Laszlo Agocs committed
1243
    When texture() or renderBuffer() is multisample, resolveTexture() can be
1244 1245 1246 1247 1248 1249 1250
    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
1251 1252
    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
1253 1254
 */

1255 1256 1257
/*!
    Constructs an empty color attachment description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1258 1259 1260 1261
QRhiColorAttachment::QRhiColorAttachment()
{
}

1262 1263 1264 1265
/*!
    Constructs a color attachment description that specifies \a texture as the
    associated color buffer.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1266 1267 1268 1269 1270
QRhiColorAttachment::QRhiColorAttachment(QRhiTexture *texture)
    : m_texture(texture)
{
}

1271 1272 1273 1274
/*!
    Constructs a color attachment description that specifies \a renderBuffer as
    the associated color buffer.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
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).
 */

1293 1294 1295
/*!
    Constructs an empty texture render target description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1296 1297 1298 1299
QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription()
{
}

1300 1301 1302 1303
/*!
    Constructs a texture render target description with one attachment
    described by \a colorAttachment.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1304 1305 1306 1307 1308
QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription(const QRhiColorAttachment &colorAttachment)
{
    m_colorAttachments.append(colorAttachment);
}

1309 1310 1311 1312 1313
/*!
    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
1314 1315 1316 1317 1318 1319 1320
QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription(const QRhiColorAttachment &colorAttachment,
                                                                       QRhiRenderBuffer *depthStencilBuffer)
    : m_depthStencilBuffer(depthStencilBuffer)
{
    m_colorAttachments.append(colorAttachment);
}

1321 1322 1323 1324 1325 1326
/*!
    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
Laszlo Agocs's avatar
Laszlo Agocs committed
1327
    or QRhiTexture::D32F.
1328
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
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
1342 1343 1344
    former is only allowed for uncompressed textures with a format that can be
    mapped to QImage, while the latter is only supported for floating point and
    compressed textures.
Laszlo Agocs's avatar
Laszlo Agocs committed
1345

1346
    \note image() and data() cannot be both set at the same time.
Laszlo Agocs's avatar
Laszlo Agocs committed
1347 1348 1349 1350 1351 1352

    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
1353 1354 1355
    the size of the source image() must match the subresource. For floating
    point and compressed textures sufficient amount of data must be provided in
    data().
Laszlo Agocs's avatar
Laszlo Agocs committed
1356 1357 1358 1359

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

1360 1361
    sourceTopLeft() is supported only for uncompressed, non-floating point
    textures, and specifies the top-left corner of the source rectangle.
Laszlo Agocs's avatar
Laszlo Agocs committed
1362 1363 1364 1365 1366

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

1367 1368 1369
/*!
    Constructs an empty mip level description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1370 1371 1372 1373
QRhiTextureMipLevel::QRhiTextureMipLevel()
{
}

1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
/*!
    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
1386 1387 1388 1389 1390
QRhiTextureMipLevel::QRhiTextureMipLevel(const QImage &image)
    : m_image(image)
{
}

1391
/*!
1392 1393 1394
    Constructs a mip level description suitable for textures with a format that
    does not map to QImage. The floating point or compressed data is specified
    in \a data.
1395
 */
1396 1397
QRhiTextureMipLevel::QRhiTextureMipLevel(const QByteArray &data)
    : m_data(data)
Laszlo Agocs's avatar
Laszlo Agocs committed
1398 1399 1400 1401 1402 1403 1404 1405 1406
{
}

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

1407 1408 1409
/*!
    Constructs an empty texture layer description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1410 1411 1412 1413
QRhiTextureLayer::QRhiTextureLayer()
{
}

1414 1415 1416 1417
/*!
    Constructs a texture layer description with the specified list of \a
    mipImages.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1418 1419 1420 1421 1422
QRhiTextureLayer::QRhiTextureLayer(const QVector<QRhiTextureMipLevel> &mipImages)
    : m_mipImages(mipImages)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1423 1424 1425
/*!
    \class QRhiTextureUploadDescription
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
1426
    \brief Describes a texture upload operation.
1427

1428 1429 1430 1431 1432 1433 1434 1435
    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.

1436 1437
    \note Cubemaps have one layer for each of the six faces in the order +X,
    -X, +Y, -Y, +Z, -Z.
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

    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
1464 1465
 */

1466 1467 1468
/*!
    Constructs an empty texture upload description.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1469 1470 1471
QRhiTextureUploadDescription::QRhiTextureUploadDescription()
{
}
1472

1473 1474 1475 1476
/*!
    Constructs a texture upload description with the specified list of \a
    layers.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1477 1478 1479 1480
QRhiTextureUploadDescription::QRhiTextureUploadDescription(const QVector<QRhiTextureLayer> &layers)
    : m_layers(layers)
{
}
Laszlo Agocs's avatar
Laszlo Agocs committed
1481 1482 1483 1484

/*!
    \class QRhiTextureCopyDescription
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
1485
    \brief Describes a texture-to-texture copy operation.