- Qt 6.7
- Qt GUI
- C++ Classes
- QRhi
- Qt 6.7.1 Reference Documentation

# QRhi Class

Accelerated 2D/3D graphics API abstraction. More...

Header: | #include <QRhi>
CMake: | find_package(Qt6 REQUIRED COMPONENTS Gui) target_link_libraries(mytarget PRIVATE Qt6::Gui)
qmake: | QT += gui
Since: | Qt 6.6

- List of all members, including inherited members
- QRhi is part of Rendering in 3D.

## Public Types

enum | BeginFrameFlag { }
flags | BeginFrameFlags
enum | EndFrameFlag { SkipPresent }
flags | EndFrameFlags
enum | Feature { MultisampleTexture, MultisampleRenderBuffer, DebugMarkers, Timestamps, Instancing, …, MultiView }
enum | Flag { EnableDebugMarkers, EnableTimestamps, PreferSoftwareRenderer, EnablePipelineCacheDataSave, SuppressSmokeTestWarnings }
flags | Flags
enum | FrameOpResult { FrameOpSuccess, FrameOpError, FrameOpSwapChainOutOfDate, FrameOpDeviceLost }
enum | Implementation { Null, Vulkan, OpenGLES2, D3D11, D3D12, Metal }
enum | ResourceLimit { TextureSizeMin, TextureSizeMax, MaxColorAttachments, FramesInFlight, MaxAsyncReadbackFrames, …, MaxVertexOutputs }

## Public Functions

| ~QRhi()
void | addCleanupCallback(const QRhi::CleanupCallback &callback)
void | addCleanupCallback(const void *key, const QRhi::CleanupCallback &callback)
QRhi::Implementation | backend() const
const char * | backendName() const
QRhi::FrameOpResult | beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags = {})
QRhi::FrameOpResult | beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags = {})
QMatrix4x4 | clipSpaceCorrMatrix() const
int | currentFrameSlot() const
QRhiDriverInfo | driverInfo() const
QRhi::FrameOpResult | endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags = {})
QRhi::FrameOpResult | endOffscreenFrame(QRhi::EndFrameFlags flags = {})
QRhi::FrameOpResult | finish()
bool | isClipDepthZeroToOne() const
bool | isDeviceLost() const
bool | isFeatureSupported(QRhi::Feature feature) const
bool | isRecordingFrame() const
bool | isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags = {}) const
bool | isYUpInFramebuffer() const
bool | isYUpInNDC() const
bool | makeThreadLocalNativeContextCurrent()
const QRhiNativeHandles * | nativeHandles()
QRhiBuffer * | newBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
QRhiComputePipeline * | newComputePipeline()
QRhiGraphicsPipeline * | newGraphicsPipeline()
QRhiRenderBuffer * | newRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, int sampleCount = 1, QRhiRenderBuffer::Flags flags = {}, QRhiTexture::Format backingFormatHint = QRhiTexture::UnknownFormat)
QRhiSampler * | newSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter, QRhiSampler::Filter mipmapMode, QRhiSampler::AddressMode addressU, QRhiSampler::AddressMode addressV, QRhiSampler::AddressMode addressW = QRhiSampler::Repeat)
QRhiShaderResourceBindings * | newShaderResourceBindings()
QRhiSwapChain * | newSwapChain()
QRhiTexture * | newTexture(QRhiTexture::Format format, const QSize &pixelSize, int sampleCount = 1, QRhiTexture::Flags flags = {})
QRhiTexture * | newTexture(QRhiTexture::Format format, int width, int height, int depth, int sampleCount = 1, QRhiTexture::Flags flags = {})
QRhiTexture * | newTextureArray(QRhiTexture::Format format, int arraySize, const QSize &pixelSize, int sampleCount = 1, QRhiTexture::Flags flags = {})
QRhiTextureRenderTarget * | newTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc, QRhiTextureRenderTarget::Flags flags = {})
QRhiResourceUpdateBatch * | nextResourceUpdateBatch()
QByteArray | pipelineCacheData()
void | releaseCachedResources()
void | removeCleanupCallback(const void *key)
int | resourceLimit(QRhi::ResourceLimit limit) const
void | runCleanup()
void | setPipelineCacheData(const QByteArray &data)
QRhiStats | statistics() const
QList<int> | supportedSampleCounts() const
QThread * | thread() const
int | ubufAligned(int v) const
int | ubufAlignment() const

## Static Public Members

const char * | backendName(QRhi::Implementation impl)
QRhi * | create(QRhi::Implementation impl, QRhiInitParams *params, QRhi::Flags flags = {}, QRhiNativeHandles *importDevice = nullptr)
int | mipLevelsForSize(const QSize &size)
bool | probe(QRhi::Implementation impl, QRhiInitParams *params)
QSize | sizeForMipLevel(int mipLevel, const QSize &baseLevelSize)
QRhiSwapChainProxyData | updateSwapChainProxyData(QRhi::Implementation impl, QWindow *window)

## Related Non-Members

`(since 6.7)` | QRhiShaderResourceBindingSet

## Detailed Description

The Qt Rendering Hardware Interface is an abstraction for hardware accelerated graphics APIs, such as, OpenGL, OpenGL ES, Direct3D, Metal, and Vulkan.

Warning: The QRhi family of classes in the Qt Gui module, including QShader and QShaderDescription, offer limited compatibility guarantees. There are no source or binary compatibility guarantees for these classes, meaning the API is only guaranteed to work with the Qt version the application was developed against. Source incompatible changes are however aimed to be kept at a minimum and will only be made in minor releases (6.7, 6.8, and so on). To use these classes in an application, link to `Qt::GuiPrivate` (if using CMake), and include the headers with the `rhi` prefix, for example `#include <rhi/qrhi.h>`.

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, Direct3D on Windows).

The available backends currently are:

- OpenGL 2.1 / OpenGL ES 2.0 or newer. Some extensions and newer core specification features are utilized when present, for example to enable multisample framebuffers or compute shaders. Operating in core profile contexts is supported as well. If necessary, applications can query the feature flags at runtime to check for features that are not supported in the OpenGL context backing the QRhi. The OpenGL backend builds on QOpenGLContext, QOpenGLFunctions, and the related cross-platform infrastructure of the Qt GUI module.
- Direct3D 11.1 or newer, with Shader Model 5.0 or newer. When the D3D runtime has no support for 11.1 features or Shader Model 5.0, initialization using an accelerated graphics device will fail, but using the software adapter is still an option.
- Direct3D 12 on Windows 10 version 1703 and newer, with Shader Model 5.0 or newer. Qt requires ID3D12Device2 to be present, hence the requirement for at least version 1703 of Windows 10. The D3D12 device is by default created with specifying a minimum feature level of `D3D_FEATURE_LEVEL_11_0`.
- Metal 1.2 or newer.
- Vulkan 1.0 or newer, optionally utilizing some Vulkan 1.1 level features.
- Null, a "dummy" backend that issues no graphics calls at all.

In order to allow shader code to be written once in Qt applications and libraries, all shaders are expected to be written in a single language which is then compiled into SPIR-V. Versions for various shading language are then generated from that, together with reflection information (inputs, outputs, shader resources). This is then packed into easily and efficiently serializable QShader instances. The compilers and tools to generate such shaders are not part of QRhi and the Qt GUI module, but the core classes for using such shaders, QShader and QShaderDescription, are. The APIs and tools for performing compilation and translation are part of the Qt Shader Tools module.

See the RHI Window Example for an introductory example of creating a portable, cross-platform application that performs accelerated 3D rendering onto a QWindow using QRhi.

### An Impression of the API

To provide a quick look at the API with a short yet complete example that does not involve window-related setup, the following is a complete, runnable cross-platform application that renders 20 frames off-screen, and then saves the generated images to files after reading back the texture contents from the GPU. For an example that renders on-screen, which then involves setting up a QWindow and a swapchain, refer to the RHI Window Example.

For brevity, the initialization of the QRhi is done based on the platform: the sample code here chooses Direct 3D 12 on Windows, Metal on macOS and iOS, and Vulkan otherwise. OpenGL and Direct 3D 11 are never used by this application, but support for those could be introduced with a few additional lines.

     #include <QGuiApplication>
     #include <QImage>
     #include <QFile>
     #include <rhi/qrhi.h>

     int main(int argc, char **argv)
     {
         QGuiApplication app(argc, argv);

     #if QT_CONFIG(vulkan)
         QVulkanInstance inst;
     #endif
         std::unique_ptr<QRhi> rhi;
     #if defined(Q_OS_WIN)
         QRhiD3D12InitParams params;
         rhi.reset(QRhi::create(QRhi::D3D12, &params));
     #elif defined(Q_OS_MACOS) || defined(Q_OS_IOS)
         QRhiMetalInitParams params;
         rhi.reset(QRhi::create(QRhi::Metal, &params));
     #elif QT_CONFIG(vulkan)
         inst.setExtensions(QRhiVulkanInitParams::preferredInstanceExtensions());
         if (inst.create()) {
             QRhiVulkanInitParams params;
             params.inst = &inst;
             rhi.reset(QRhi::create(QRhi::Vulkan, &params));
         } else {
             qFatal("Failed to create Vulkan instance");
         }
     #endif
         if (rhi)
             qDebug() << rhi->backendName() << rhi->driverInfo();
         else
             qFatal("Failed to initialize RHI");

         float rotation = 0.0f;
         float opacity = 1.0f;
         int opacityDir = 1;

         std::unique_ptr<QRhiTexture> tex(rhi->newTexture(QRhiTexture::RGBA8,
                                                          QSize(1280, 720),
                                                          1,
                                                          QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource));
         tex->create();
         std::unique_ptr<QRhiTextureRenderTarget> rt(rhi->newTextureRenderTarget({ tex.get() }));
         std::unique_ptr<QRhiRenderPassDescriptor> rp(rt->newCompatibleRenderPassDescriptor());
         rt->setRenderPassDescriptor(rp.get());
         rt->create();

         QMatrix4x4 viewProjection = rhi->clipSpaceCorrMatrix();
         viewProjection.perspective(45.0f, 1280 / 720.f, 0.01f, 1000.0f);
         viewProjection.translate(0, 0, -4);

         static float vertexData[] = { // Y up, CCW
             0.0f,   0.5f,     1.0f, 0.0f, 0.0f,
             -0.5f, -0.5f,     0.0f, 1.0f, 0.0f,
             0.5f,  -0.5f,     0.0f, 0.0f, 1.0f,
         };

         std::unique_ptr<QRhiBuffer> vbuf(rhi->newBuffer(QRhiBuffer::Immutable,
                                                         QRhiBuffer::VertexBuffer,
                                                         sizeof(vertexData)));
         vbuf->create();

         std::unique_ptr<QRhiBuffer> ubuf(rhi->newBuffer(QRhiBuffer::Dynamic,
                                                         QRhiBuffer::UniformBuffer,
                                                         64 + 4));
         ubuf->create();

         std::unique_ptr<QRhiShaderResourceBindings> srb(rhi->newShaderResourceBindings());
         srb->setBindings({
             QRhiShaderResourceBinding::uniformBuffer(0,
                                                      QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage,
                                                      ubuf.get())
         });
         srb->create();

         std::unique_ptr<QRhiGraphicsPipeline> ps(rhi->newGraphicsPipeline());
         QRhiGraphicsPipeline::TargetBlend premulAlphaBlend;
         premulAlphaBlend.enable = true;
         ps->setTargetBlends({ premulAlphaBlend });
         static auto getShader = [](const QString &name) {
             QFile f(name);
             return f.open(QIODevice::ReadOnly) ? QShader::fromSerialized(f.readAll()) : QShader();
         };
         ps->setShaderStages({
             { QRhiShaderStage::Vertex, getShader(QLatin1String("color.vert.qsb")) },
             { QRhiShaderStage::Fragment, getShader(QLatin1String("color.frag.qsb")) }
         });
         QRhiVertexInputLayout inputLayout;
         inputLayout.setBindings({
             { 5 * sizeof(float) }
         });
         inputLayout.setAttributes({
             { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
             { 0, 1, QRhiVertexInputAttribute::Float3, 2 * sizeof(float) }
         });
         ps->setVertexInputLayout(inputLayout);
         ps->setShaderResourceBindings(srb.get());
         ps->setRenderPassDescriptor(rp.get());
         ps->create();

         QRhiCommandBuffer *cb;
         for (int frame = 0; frame < 20; ++frame) {
             rhi->beginOffscreenFrame(&cb);

             QRhiResourceUpdateBatch *u = rhi->nextResourceUpdateBatch();
             if (frame == 0)
                 u->uploadStaticBuffer(vbuf.get(), vertexData);

             QMatrix4x4 mvp = viewProjection;
             mvp.rotate(rotation, 0, 1, 0);
             u->updateDynamicBuffer(ubuf.get(), 0, 64, mvp.constData());
             rotation += 5.0f;

             u->updateDynamicBuffer(ubuf.get(), 64, 4, &opacity);
             opacity += opacityDir * 0.2f;
             if (opacity < 0.0f || opacity > 1.0f) {
                 opacityDir *= -1;
                 opacity = qBound(0.0f, opacity, 1.0f);
             }

             cb->beginPass(rt.get(), Qt::green, { 1.0f, 0 }, u);
             cb->setGraphicsPipeline(ps.get());
             cb->setViewport({ 0, 0, 1280, 720 });
             cb->setShaderResources();
             const QRhiCommandBuffer::VertexInput vbufBinding(vbuf.get(), 0);
             cb->setVertexInput(0, 1, &vbufBinding);
             cb->draw(3);
             QRhiReadbackResult readbackResult;
             u = rhi->nextResourceUpdateBatch();
             u->readBackTexture({ tex.get() }, &readbackResult);
             cb->endPass(u);

             rhi->endOffscreenFrame();

             QImage image(reinterpret_cast<const uchar *>(readbackResult.data.constData()),
                          readbackResult.pixelSize.width(),
                          readbackResult.pixelSize.height(),
                          QImage::Format_RGBA8888_Premultiplied);
             if (rhi->isYUpInFramebuffer())
                 image = image.mirrored();
             image.save(QString::asprintf("frame%d.png", frame));
         }

         return 0;
     }

The result of the application is 20 `PNG` images (frame0.png - frame19.png). These contain a rotating triangle with varying opacity over a green background.

The vertex and fragment shaders are expected to be processed and packaged into `.qsb` files. The Vulkan-compatible GLSL source code is the following:

color.vert

     #version 440

     layout(location = 0) in vec4 position;
     layout(location = 1) in vec3 color;
     layout(location = 0) out vec3 v_color;

     layout(std140, binding = 0) uniform buf {
         mat4 mvp;
         float opacity;
     };

     void main()
     {
         v_color = color;
         gl_Position = mvp * position;
     }

color.frag

     #version 440

     layout(location = 0) in vec3 v_color;
     layout(location = 0) out vec4 fragColor;

     layout(std140, binding = 0) uniform buf {
         mat4 mvp;
         float opacity;
     };

     void main()
     {
         fragColor = vec4(v_color * opacity, opacity);
     }

To manually compile and transpile these shaders to a number of targets (SPIR-V, HLSL, MSL, GLSL) and generate the `.qsb` files the application loads at run time, run `qsb --qt6 color.vert -o color.vert.qsb` and `qsb --qt6 color.frag -o color.frag.qsb`. Alternatively, the Qt Shader Tools module offers build system integration for CMake, the `qt_add_shaders()` CMake function, that can achieve the same at build time.

### Design Fundamentals

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

#### 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 `new` functions of the QRhi, such as, newBuffer(), newTexture(), newTextureRenderTarget(), newSwapChain().

     QRhiBuffer *vbuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
     if (!vbuf->create()) { error(); }
     // ...
     delete vbuf;

- The returned value from functions like newBuffer() is always owned by the caller.
- Just creating an instance of a QRhiResource subclass never allocates or initializes any native resources. That is only done when calling the `create()` function of a subclass, for example, QRhiBuffer::create() or QRhiTexture::create().
- The exceptions are QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor(), QRhiSwapChain::newCompatibleRenderPassDescriptor(), and QRhiRenderPassDescriptor::newCompatibleRenderPassDescriptor(). There is no `create()` operation for these and the returned object is immediately active.
- The resource objects themselves are treated as immutable: once a resource has create() called, changing any parameters via the setters, such as, QRhiTexture::setPixelSize(), has no effect, unless the underlying native resource is released and `create()` is called again. See more about resource reuse in the sections below.
- The underlying native resources are scheduled for releasing by the QRhiResource destructor, or by calling QRhiResource::destroy(). 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 native resources that may still be in use by an in-flight frame.
- Note that this does not mean that a QRhiResource can freely be destroy()'ed or deleted within a frame (that is, in a beginFrame() - endFrame() section). As a general rule, all referenced QRhiResource objects must stay unchanged until the frame is submitted by calling endFrame(). To ease this, QRhiResource::deleteLater() is provided as a convenience.

#### Command buffers and deferred 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, `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 deferred 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 all resources upfront, before starting to record commands for the next frame. Reusing a QRhiResource instance within a frame (by calling `create()` then referencing it again in the same `beginFrame - endFrame` section) should be avoided as it may lead to unexpected results, depending on the backend.

As a general rule, all referenced QRhiResource objects must stay valid and unmodified until the frame is submitted by calling endFrame(). On the other hand, calling destroy() or deleting the QRhiResource are always safe 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).

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:

- (re)create resources
- begin frame
- record/issue uploads and copies
- start recording a render pass
- record draw calls
- end render pass
- end frame

Recording copy type of operations happens via QRhiResourceUpdateBatch. Such operations are committed typically on beginPass().

When working with legacy rendering engines designed for OpenGL, the migration to QRhi often involves redesigning from having a single `render` step (that performs copies and uploads, clears buffers, and issues draw calls, all mixed together) to a clearly separated, two phase `prepare` - `render` setup where the `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 `prepare` step.

QRhi does not at the moment allow freely creating and submitting command buffers. This may be lifted in the future to some extent, in particular if compute support is introduced, but the model of well defined `frame-start` and `frame-end` points, combined with a dedicated, "frame" command buffer, where `frame-end` implies presenting, is going to remain the primary way of operating since this is what fits Qt's various UI technologies best.

#### Threading

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. Conceptually that is then the same as how Qt Quick scene graph's threaded render loop operates when working directly with OpenGL: one thread for each window, one QOpenGLContext for each thread. When moving onto QRhi, QOpenGLContext is replaced by QRhi, making the migration straightforward.

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.

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 to those concepts, however, and is thus a topic that is currently out of scope, but may be introduced in the future.

Note: The Metal backend requires that an autorelease pool is available on the rendering thread, ideally wrapping each iteration of the render loop. This needs no action from the users of QRhi when rendering on the main (gui) thread, but becomes important when a separate, dedicated render thread is used.

#### Resource synchronization

QRhi does not expose APIs for resource barriers or image layout transitions. Such synchronization is done implicitly by the backends, where applicable (for example, Vulkan), by tracking resource usage as necessary. Buffer and image barriers are inserted before render or compute passes transparently to the application.

Note: Resources within a render or compute pass are expected to be bound to a single usage during that pass. For example, a buffer can be used as vertex, index, uniform, or storage buffer, but not a combination of them within a single pass. However, it is perfectly fine to use a buffer as a storage buffer in a compute pass, and then as a vertex buffer in a render pass, for example, assuming the buffer declared both usages upon creation.

Note: Textures have this rule relaxed in certain cases, because using two subresources (typically two different mip levels) of the same texture for different access (one for load, one for store) is supported even within the same pass.

#### Resource reuse

From the user's point of view a QRhiResource is reusable immediately after calling QRhiResource::destroy(). With the exception of swapchains, calling `create()` on an already created object does an implicit `destroy()`. This provides a handy shortcut to reuse a QRhiResource instance with different parameters, with a new native graphics object 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 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::create(), 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.

     QRhiBuffer *ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 256);
     ubuf->create();

     QRhiShaderResourceBindings *srb = rhi->newShaderResourceBindings()
     srb->setBindings({
         QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf)
     });
     srb->create();

     // ...

     // now in a later frame we need to grow the buffer to a larger size
     ubuf->setSize(512);
     ubuf->create(); // same as ubuf->destroy(); ubuf->create();

     // srb needs no changes whatsoever, any references in it to ubuf
     // stay valid. When it comes to internal details, such as that
     // ubuf may now be backed by a completely different native buffer
     // resource, that is is recognized and handled automatically by the
     // next setShaderResources().

QRhiTextureRenderTarget offers the same contract: calling QRhiCommandBuffer::beginPass() is safe even when one of the render target's associated textures or renderbuffers has been rebuilt (by calling `create()` on it) since the creation of the render target object. This allows the application to resize a texture by setting a new pixel size on the QRhiTexture and calling create(), thus creating a whole new native texture resource underneath, without having to update the QRhiTextureRenderTarget as that will be done implicitly in beginPass().

#### Pooled objects

In addition to resources, there are pooled objects as well, such as, QRhiResourceUpdateBatch. An instance is retrieved via a `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:

     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();
     // note the last argument
     cb->beginPass(swapchain->currentFrameRenderTarget(), clearCol, clearDs, resUpdates);

#### Swapchain specifics

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

- It has no `create()` but rather a QRhiSwapChain::createOrResize(). Repeatedly calling this function is not the same as calling QRhiSwapChain::destroy() followed by QRhiSwapChain::createOrResize(). 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.
- An active QRhiSwapChain must be released by calling destroy(), or by destroying the object, before the QWindow's underlying QPlatformWindow, and so the associated native window object, is destroyed. It should not be postponed because releasing the swapchain may become problematic (and with some APIs, like Vulkan, is explicitly disallowed) when the native window is not around anymore, for example because the QPlatformWindow got destroyed upon getting a QWindow::close(). Therefore, releasing the swapchain must happen whenever the targeted QWindow sends the QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed event. If the event does not arrive before the destruction of the QWindow - this can happen when using QCoreApplication::quit() -, then check QWindow::handle() after the event loop exits and invoke the swapchain release when non-null (meaning the underlying native window is still around).

#### 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::nativeTexture(). Most importantly, passing pointers in structs and via setters does not transfer ownership.

### Troubleshooting and Profiling

#### Error reporting

Functions such as QRhi::create() and the resource classes' `create()` member functions (e.g., QRhiBuffer::create()) indicate failure with the return value (`nullptr` or `false`, respectively). When working with QShader, QShader::fromSerialized() returns an invalid QShader (for which isValid() returns `false`) when the data passed to the function cannot be successfully deserialized. Some functions, beginFrame() in particular, may also sometimes report "soft failures", such as FrameOpSwapChainOutOfDate, which do not indicate an unrecoverable error, but rather should be seen as a "try again later" response.

Warnings and errors may get printed at any time to the debug output via qWarning(). It is therefore always advisable to inspect the output of the application.

Additional debug messages can be enabled via the following logging categories. Messages from these categories are not printed by default unless explicitly enabled via QLoggingCategory or the `QT_LOGGING_RULES` environment variable. For better interoperation with Qt Quick, the environment variable `QSG_INFO` also enables these debug prints.

- `qt.rhi.general`

Additionally, applications can query the QRhi backend name and graphics device information from a successfully initialized QRhi. This can then be printed to the user or stored in the application logs even in production builds, if desired.

#### Investigating rendering problems

When the rendering results are not as expected, or the application is experiencing problems, always consider checking with the the native 3D APIs' debug and validation facilities. QRhi itself features limited error checking since replicating the already existing, vast amount of functionality in the underlying layers is not reasonable.

- For Vulkan, controlling the Vulkan Validation Layers is not in the scope of the QRhi, but rather can be achieved by configuring the QVulkanInstance with the appropriate layers. For example, call `instance.setLayers({ "VK_LAYER_KHRONOS_validation" });` before invoking create() on the QVulkanInstance. (note that this assumes that the validation layers are actually installed and available, e.g. from the Vulkan SDK) By default, QVulkanInstance conveniently redirects the Vulkan debug messages to qDebug, meaning the validation messages get printed just like other Qt warnings.
- With Direct 3D 11 and 12, a graphics device with the debug layer enabled can be requested by toggling the `enableDebugLayer` flag in the appropriate init params struct. The messages appear on the debug output, which is visible in Qt Creator's messages panel or via a tool such as DebugView.
- For Metal, controlling Metal Validation is outside of QRhi's scope. Rather, to enable validation, run the application with the environment variable `METAL_DEVICE_WRAPPER_TYPE=1` set, or run the application within XCode. There may also be further settings and environment variable in modern XCode and macOS versions. See for instance this page.

#### Frame captures and performance profiling

A Qt application rendering with QRhi to a window while relying on a 3D API under the hood, is, from the windowing and graphics pipeline perspective at least, no different from any other (non-Qt) applications using the same 3D API. This means that tools and practices for debugging and profiling applications involving 3D graphics, such as games, all apply to such a Qt application as well.

A few examples of tools that can provide insights into the rendering internals of Qt applications that use QRhi, which includes Qt Quick and Qt Quick 3D based projects as well:

- RenderDoc allows taking frame captures and introspecting the recorded commands and pipeline state on Windows and Linux for applications using OpenGL, Vulkan, D3D11, or D3D12. When trying to figure out why some parts of the 3D scene do not show up as expected, RenderDoc is often a fast and efficient way to check the pipeline stages and the related state and discover the missing or incorrect value. It is also a tool that is actively used when developing Qt itself.
- For NVIDIA-based systems, Nsight Graphics provides a graphics debugger tool on Windows and Linux. In addition to investigating the commands in the frame and the pipeline, the vendor-specific tools allow looking at timings and hardware performance information, which is not something simple frame captures can provide.
- For AMD-based systems, the Radeon GPU Profiler can be used to gain deeper insights into the application's rendering and its performance.
- As QRhi supports Direct 3D 12, using PIX, a performance tuning and debugging tool for DirectX 12 games on Windows is an option as well.
- On macOS, the XCode Metal debugger can be used to take and introspect frame captures, to investigate performance details, and debug shaders. In macOS 13 it is also possible to enable an overlay that displays frame rate and other information for any Metal-based window by setting the environment variable `MTL_HUD_ENABLED=1`.

On mobile and embedded platforms, there may be vendor and platform-specific tools, provided by the GPU or SoC vendor, available to perform performance profiling of application using OpenGL ES or Vulkan.

When capturing frames, remember that objects and groups of commands can be named via debug markers, as long as debug markers were enabled for the QRhi, and the graphics API in use supports this. To annotate the command stream, call debugMarkBegin(), debugMarkEnd() and/or debugMarkMsg(). This can be particularly useful in larger frames with multiple render passes. Resources are named by calling setName() before create().

To perform basic timing measurements on the CPU and GPU side within the application, QElapsedTimer and QRhiCommandBuffer::lastCompletedGpuTime() can be used. The latter is only available with select graphics APIs at the moment and requires opting in via the QRhi::EnableTimestamps flag.

#### Resource leak checking

When destroying a QRhi object without properly destroying all buffers, textures, and other resources created from it, warnings about this are printed to the debug output whenever the application is a debug build, or when the `QT_RHI_LEAK_CHECK` environment variable is set to a non-zero value. This is a simple way to discover design issues around resource handling within the application rendering logic. Note however that some platforms and underlying graphics APIs may perform their own allocation and resource leak detection as well, over which Qt will have no direct control. For example, when using Vulkan, the memory allocator may raise failing assertions in debug builds when resources that own graphics memory allocations are not destroyed before the QRhi. In addition, the Vulkan validation layer, when enabled, will issue warnings about native graphics resources that were not released. Similarly, with Direct 3D warnings may get printed about unreleased COM objects when the application does not destroy the QRhi and its resources in the correct order.

See also RHI Window Example, QRhiCommandBuffer, QRhiResourceUpdateBatch, QRhiShaderResourceBindings, QShader, QRhiBuffer, QRhiTexture, QRhiRenderBuffer, QRhiSampler, QRhiTextureRenderTarget, QRhiGraphicsPipeline, QRhiComputePipeline, and QRhiSwapChain.

## Member Type Documentation

### enum QRhi::BeginFrameFlag
flags QRhi::BeginFrameFlags

Flag values for QRhi::beginFrame()

The BeginFrameFlags type is a typedef for QFlags<BeginFrameFlag>. It stores an OR combination of BeginFrameFlag values.

### enum QRhi::EndFrameFlag
flags QRhi::EndFrameFlags

Flag values for QRhi::endFrame()

Constant | Value | Description
--- | --- | ---
`QRhi::SkipPresent` | `1 << 0` | 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)

The EndFrameFlags type is a typedef for QFlags<EndFrameFlag>. It stores an OR combination of EndFrameFlag values.

### enum QRhi::Feature

Flag values to indicate what features are supported by the backend currently in use.

Constant | Value | Description
--- | --- | ---
`QRhi::MultisampleTexture` | `1` | Indicates that textures with a sample count larger than 1 are supported. In practice this feature will be unsupported with OpenGL ES versions older than 3.1, and OpenGL older than 3.0.
`QRhi::MultisampleRenderBuffer` | `2` | Indicates that renderbuffers with a sample count larger than 1 are supported. In practice this feature will be unsupported with OpenGL ES 2.0, and may also be unsupported with OpenGL 2.x unless the relevant extensions are present.
`QRhi::DebugMarkers` | `3` | Indicates that debug marker groups (and so QRhiCommandBuffer::debugMarkBegin()) are supported.
`QRhi::Timestamps` | `4` | Indicates that command buffer timestamps are supported. Relevant for QRhiCommandBuffer::lastCompletedGpuTime(). This can be expected to be supported on Metal, Vulkan, Direct 3D 11 and 12, and OpenGL contexts of version 3.3 or newer. However, with some of these APIs support for timestamp queries is technically optional, and therefore it cannot be guaranteed that this feature is always supported with every implementation of them.
`QRhi::Instancing` | `5` | Indicates that instanced drawing is supported. In practice this feature will be unsupported with OpenGL ES 2.0 and OpenGL 3.2 or older.
`QRhi::CustomInstanceStepRate` | `6` | Indicates that instance step rates other than 1 are supported. In practice this feature will always be unsupported with OpenGL. In addition, running with Vulkan 1.0 without VK_EXT_vertex_attribute_divisor will also lead to reporting false for this feature.
`QRhi::PrimitiveRestart` | `7` | Indicates that restarting the assembly of primitives when encountering an index value of 0xFFFF (IndexUInt16) or 0xFFFFFFFF (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 that whenever this feature is reported as supported, the above mentioned index values `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 LineStrip and TriangleStrip.
`QRhi::NonDynamicUniformBuffers` | `8` | Indicates that creating buffers with the usage UniformBuffer and the types Immutable or Static is supported. When reported as unsupported, uniform (constant) buffers must be created as Dynamic. (which is recommended regardless)
`QRhi::NonFourAlignedEffectiveIndexBufferOffset` | `9` | Indicates that effective index buffer offsets (`indexOffset + firstIndex * indexComponentSize`) that are not 4 byte aligned are supported. When not supported, attempting to issue a drawIndexed() with a non-aligned effective offset may lead to unspecified behavior. Relevant in particular for Metal, where this will be reported as unsupported.
`QRhi::NPOTTextureRepeat` | `10` | Indicates that the Repeat wrap mode and mipmap filtering modes are supported for textures with a non-power-of-two size. In practice this can only be false with OpenGL ES 2.0 implementations without `GL_OES_texture_npot`.
`QRhi::RedOrAlpha8IsRed` | `11` | Indicates that the RED_OR_ALPHA8 format maps to a one component 8-bit `red` format. This is the case for all backends except OpenGL when using either OpenGL ES or a non-core profile context. There `GL_ALPHA`, a one component 8-bit `alpha` format, is used instead. Using the special texture format allows having a single code path for creating textures, leaving it up to the backend to decide the actual format, while the feature flag can be used to pick the appropriate shader variant for sampling the texture.
`QRhi::ElementIndexUint` | `12` | Indicates that 32-bit unsigned integer elements are supported in the index buffer. In practice this is true everywhere except when running on plain OpenGL ES 2.0 implementations without the necessary extension. When false, only 16-bit unsigned elements are supported in the index buffer.
`QRhi::Compute` | `13` | Indicates that compute shaders, image load/store, and storage buffers are supported. OpenGL older than 4.3 and OpenGL ES older than 3.1 have no compute support.
`QRhi::WideLines` | `14` | Indicates that lines with a width other than 1 are supported. When reported as not supported, the line width set on the graphics pipeline state is ignored. This can always be false with some backends (D3D11, D3D12, Metal). With Vulkan, the value depends on the implementation. With OpenGL, wide lines are not supported in core profile contexts.
`QRhi::VertexShaderPointSize` | `15` | Indicates that the size of rasterized points set via `gl_PointSize` in the vertex shader is taken into account. When reported as not supported, drawing points with a size other than 1 is not supported. Setting `gl_PointSize` in the shader is still valid then, but is ignored. (for example, when generating HLSL, the assignment is silently dropped from the generated code) Note that some APIs (Metal, Vulkan) require the point size to be set in the shader explicitly whenever drawing points, even when the size is 1, as they do not automatically default to 1.
`QRhi::BaseVertex` | `16` | Indicates that drawIndexed() supports the `vertexOffset` argument. When reported as not supported, the vertexOffset value in an indexed draw is ignored. In practice this feature will be unsupported with OpenGL and OpenGL ES versions lower than 3.2, and with Metal on older iOS devices, including the iOS Simulator.
`QRhi::BaseInstance` | `17` | Indicates that instanced draw commands support the `firstInstance` argument. When reported as not supported, the firstInstance value is ignored and the instance ID starts from 0. In practice this feature will be unsupported with OpenGL, and with Metal on older iOS devices, including the iOS Simulator.
`QRhi::TriangleFanTopology` | `18` | Indicates that QRhiGraphicsPipeline::setTopology() supports QRhiGraphicsPipeline::TriangleFan. In practice this feature will be unsupported with Metal and Direct 3D 11/12.
`QRhi::ReadBackNonUniformBuffer` | `19` | Indicates that reading buffer contents is supported for QRhiBuffer instances with a usage different than UniformBuffer. In practice this feature will be unsupported with OpenGL ES 2.0.
`QRhi::ReadBackNonBaseMipLevel` | `20` | Indicates that specifying a mip level other than 0 is supported when reading back texture contents. When not supported, specifying a non-zero level in QRhiReadbackDescription leads to returning an all-zero image. In practice this feature will be unsupported with OpenGL ES 2.0.
`QRhi::TexelFetch` | `21` | Indicates that texelFetch() and textureLod() are available in shaders. In practice this will be reported as unsupported with OpenGL ES 2.0 and OpenGL 2.x contexts, because GLSL 100 es and versions before 130 do not support these functions.
`QRhi::RenderToNonBaseMipLevel` | `22` | Indicates that specifying a mip level other than 0 is supported when creating a QRhiTextureRenderTarget with a QRhiTexture as its color attachment. When not supported, create() will fail whenever the target mip level is not zero. In practice this feature will be unsupported with OpenGL ES 2.0.
`QRhi::IntAttributes` | `23` | Indicates that specifying input attributes with signed and unsigned integer types for a shader pipeline is supported. When not supported, build() will succeed but just show a warning message and the values of the target attributes will be broken. In practice this feature will be unsupported with OpenGL ES 2.0 and OpenGL 2.x.
`QRhi::ScreenSpaceDerivatives` | `24` | Indicates that functions such as dFdx(), dFdy(), and fwidth() are supported in shaders. In practice this feature will be unsupported with OpenGL ES 2.0 without the GL_OES_standard_derivatives extension.
`QRhi::ReadBackAnyTextureFormat` | `25` | Indicates that reading back texture contents can be expected to work for any QRhiTexture::Format. Backends other than OpenGL can be expected to return true for this feature. When reported as false, which will typically happen with OpenGL, only the formats QRhiTexture::RGBA8 and QRhiTexture::BGRA8 are guaranteed to be supported for readbacks. In addition, with OpenGL, but not OpenGL ES, reading back the 1 byte per component formats QRhiTexture::R8 and QRhiTexture::RED_OR_ALPHA8 are supported as well. Reading back floating point formats QRhiTexture::RGBA16F and RGBA32F may work too with OpenGL, as long as the implementation provides support for these, but QRhi can give no guarantees, as indicated by this flag.
`QRhi::PipelineCacheDataLoadSave` | `26` | Indicates that the pipelineCacheData() and setPipelineCacheData() functions are functional. When not supported, the functions will not perform any action, the retrieved blob is always empty, and thus no benefits can be expected from retrieving and, during a subsequent run of the application, reloading the pipeline cache content.
`QRhi::ImageDataStride` | `27` | Indicates that specifying a custom stride (row length) for raw image data in texture uploads is supported. When not supported (which can happen when the underlying API is OpenGL ES 2.0 without support for GL_UNPACK_ROW_LENGTH), QRhiTextureSubresourceUploadDescription::setDataStride() must not be used.
`QRhi::RenderBufferImport` | `28` | Indicates that QRhiRenderBuffer::createFrom() is supported. For most graphics APIs this is not sensible because QRhiRenderBuffer encapsulates texture objects internally, just like QRhiTexture. With OpenGL however, renderbuffer object exist as a separate object type in the API, and in certain environments (for example, where one may want to associated a renderbuffer object with an EGLImage object) it is important to allow wrapping an existing OpenGL renderbuffer object with a QRhiRenderBuffer.
`QRhi::ThreeDimensionalTextures` | `29` | Indicates that 3D textures are supported. In practice this feature will be unsupported with OpenGL and OpenGL ES versions lower than 3.0.
`QRhi::RenderTo3DTextureSlice` | `30` | Indicates that rendering to a slice in a 3D texture is supported. This can be unsupported with Vulkan 1.0 due to relying on VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT which is a Vulkan 1.1 feature.
`QRhi::TextureArrays` | `31` | Indicates that texture arrays are supported and QRhi::newTextureArray() is functional. Note that even when texture arrays are not supported, arrays of textures are still available as those are two independent features.
`QRhi::Tessellation` | `32` | Indicates that the tessellation control and evaluation stages are supported. When reported as supported, the topology of a QRhiGraphicsPipeline can be set to Patches, the number of control points can be set via setPatchControlPointCount(), and shaders for tessellation control and evaluation can be specified in the QRhiShaderStage list. Tessellation shaders have portability issues between APIs (for example, translating GLSL/SPIR-V to HLSL is problematic due to the way hull shaders are structured, whereas Metal uses a somewhat different tessellation pipeline than others), and therefore unexpected issues may still arise, even though basic functionality is implemented across all the underlying APIs. For Direct 3D in particular, handwritten HLSL hull and domain shaders must be injected into each QShader for the tessellation control and evaluation stages, respectively, since qsb cannot generate these from SPIR-V. Note that isoline tessellation should be avoided as it will not be supported by all backends. The maximum patch control point count portable between backends is 32.
`QRhi::GeometryShader` | `33` | Indicates that the geometry shader stage is supported. When supported, a geometry shader can be specified in the QRhiShaderStage list. Geometry Shaders are considered an experimental feature in QRhi and can only be expected to be supported with Vulkan, Direct 3D, OpenGL (3.2+) and OpenGL ES (3.2+), assuming the implementation reports it as supported at run time. Geometry shaders have portability issues between APIs, and therefore no guarantees can be given for a universal solution. They will never be supported with Metal. Whereas with Direct 3D a handwritten HLSL geometry shader must be injected into each QShader for the geometry stage since qsb cannot generate this from SPIR-V.
`QRhi::TextureArrayRange` | `34` | Indicates that for texture arrays it is possible to specify a range that is exposed to the shaders. Normally all array layers are exposed and it is up to the shader to select the layer (via the third coordinate passed to texture() when sampling the `sampler2DArray`). When supported, calling QRhiTexture::setArrayRangeStart() and QRhiTexture::setArrayRangeLength() before building or importing the native texture has an effect, and leads to selecting only the specified range from the array. This will be necessary in special cases, such as when working with accelerated video decoding and Direct 3D 11, because a texture array with both `D3D11_BIND_DECODER` and `D3D11_BIND_SHADER_RESOURCE` on it is only usable as a shader resource if a single array layer is selected. Note that all this is applicable only when the texture is used as a QRhiShaderResourceBinding::SampledTexture or QRhiShaderResourceBinding::Texture shader resource, and is not compatible with image load/store. This feature is only available with some backends as it does not map well to all graphics APIs, and it is only meant to provide support for special cases anyhow. In practice the feature can be expected to be supported with Direct3D 11/12 and Vulkan.
`QRhi::NonFillPolygonMode` | `35` | Indicates that setting a PolygonMode other than the default Fill is supported for QRhiGraphicsPipeline. A common use case for changing the mode to Line is to get wireframe rendering. This however is not available as a core OpenGL ES feature, and is optional with Vulkan as well as some mobile GPUs may not offer the feature.
`QRhi::OneDimensionalTextures` | `36` | Indicates that 1D textures are supported. In practice this feature will be unsupported on OpenGL ES.
`QRhi::OneDimensionalTextureMipmaps` | `37` | Indicates that generating 1D texture mipmaps are supported. In practice this feature will be unsupported on backends that do not report support for OneDimensionalTextures, Metal, and Direct 3D 12.
`QRhi::HalfAttributes` | `38` | Indicates that specifying input attributes with half precision (16bit) floating point types for a shader pipeline is supported. When not supported, build() will succeed but just show a warning message and the values of the target attributes will be broken. In practice this feature will be unsupported in some OpenGL ES 2.0 and OpenGL 2.x implementations. Note that while Direct3D 11/12 does support half precision input attributes, it does not support the half3 type. The D3D backends pass half3 attributes as half4. To ensure cross platform compatibility, half3 inputs should be padded to 8 bytes.
`QRhi::RenderToOneDimensionalTexture` | `39` | Indicates that 1D texture render targets are supported. In practice this feature will be unsupported on backends that do not report support for OneDimensionalTextures, and Metal.
`QRhi::ThreeDimensionalTextureMipmaps` | `40` | Indicates that generating 3D texture mipmaps are supported. In practice this feature will be unsupported with Direct 3D 12.
`QRhi::MultiView` | `41` | Indicates that multiview, see e.g. VK_KHR_multiview is supported. With OpenGL ES 2.0, Direct 3D 11, and OpenGL (ES) implementations without `GL_OVR_multiview2` this feature will not be supported. With Vulkan 1.1 and newer, and Direct 3D 12 multiview is typically supported. When reported as supported, creating a QRhiTextureRenderTarget with a QRhiColorAttachment that references a texture array and has multiViewCount set enables recording a render pass that uses multiview rendering. In addition, any QRhiGraphicsPipeline used in that render pass must have the same view count set. Note that multiview is only available in combination with 2D texture arrays. It cannot be used to optimize the rendering into individual textures (e.g. two, for the left and right eyes). Rather, the target of a multiview render pass is always a texture array, automatically rendering to the layer (array element) corresponding to each view. Therefore this feature implies TextureArrays as well. Multiview rendering is not supported in combination with tessellation or geometry shaders. See QRhiColorAttachment::setMultiViewCount() for further details on multiview rendering. This enum value has been introduced in Qt 6.7.

### enum QRhi::Flag
flags QRhi::Flags

Describes what special features to enable.

Constant | Value | Description
--- | --- | ---
`QRhi::EnableDebugMarkers` | `1 << 0` | 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 no-ops. Avoid enabling in production builds as it may involve a small performance impact. Has no effect when the QRhi::DebugMarkers feature is not reported as supported.
`QRhi::EnableTimestamps` | `1 << 3` | Enables GPU timestamp collection. When not set, QRhiCommandBuffer::lastCompletedGpuTime() always returns 0. Enable this only when needed since there may be a small amount of extra work involved (e.g. timestamp queries), depending on the underlying graphics API. Has no effect when the QRhi::Timestamps feature is not reported as supported.
`QRhi::PreferSoftwareRenderer` | `1 << 1` | Indicates that backends should prefer choosing an adapter or physical device that renders in software on the CPU. For example, with Direct3D there is typically a "Basic Render Driver" adapter available with `DXGI_ADAPTER_FLAG_SOFTWARE`. Setting this flag requests the backend to choose that adapter over any other, as long as no specific adapter was forced by other backend-specific means. With Vulkan this maps to preferring physical devices with `VK_PHYSICAL_DEVICE_TYPE_CPU`. When not available, or when it is not possible to decide if an adapter/device is software-based, this flag is ignored. It may also be ignored with graphics APIs that have no concept and means of enumerating adapters/devices.
`QRhi::EnablePipelineCacheDataSave` | `1 << 2` | Enables retrieving the pipeline cache contents, where applicable. When not set, pipelineCacheData() will return an empty blob always. With backends where retrieving and restoring the pipeline cache contents is not supported, the flag has no effect and the serialized cache data is always empty. The flag provides an opt-in mechanism because the cost of maintaining the related data structures is not insignificant with some backends. With Vulkan this feature maps directly to VkPipelineCache, vkGetPipelineCacheData and VkPipelineCacheCreateInfo::pInitialData. With Direct3D 11 there is no real pipline cache, but the results of HLSL->DXBC compilations are stored and can be serialized/deserialized via this mechanism. This allows skipping the time consuming D3DCompile() in future runs of the applications for shaders that come with HLSL source instead of offline pre-compiled bytecode. This can provide a huge boost in startup and load times, if there is a lot of HLSL source compilation happening. With OpenGL the "pipeline cache" is simulated by retrieving and loading shader program binaries (if supported by the driver). With OpenGL there are additional, disk-based caching mechanisms for shader/program binaries provided by Qt. Writing to those may get disabled whenever this flag is set since storing program binaries to multiple caches is not sensible.
`QRhi::SuppressSmokeTestWarnings` | `1 << 4` | Indicates that, with backends where this is relevant, certain, non-fatal QRhi::create() failures should not produce qWarning() calls. For example, with D3D11, passing this flag makes a number of warning messages (that appear due to QRhi::create() failing) to become categorized debug prints instead under the commonly used `qt.rhi.general` logging category. This can be used by engines, such as Qt Quick, that feature fallback logic, i.e. they retry calling create() with a different set of flags (such as, PreferSoftwareRenderer), in order to hide the unconditional warnings from the output that would be printed when the first create() attempt had failed.

The Flags type is a typedef for QFlags<Flag>. It stores an OR combination of Flag values.

### enum QRhi::FrameOpResult

Describes the result of operations that can have a soft failure.

Constant | Value | Description
--- | --- | ---
`QRhi::FrameOpSuccess` | `0` | Success
`QRhi::FrameOpError` | `1` | Unspecified error
`QRhi::FrameOpSwapChainOutOfDate` | `2` | The swapchain is in an inconsistent state internally. This can be recoverable by attempting to repeat the operation (such as, beginFrame()) later.
`QRhi::FrameOpDeviceLost` | `3` | The graphics device was lost. This can be recoverable by attempting to repeat the operation (such as, beginFrame()) after releasing and reinitializing all objects backed by native graphics resources. See isDeviceLost().

### enum QRhi::Implementation

Describes which graphics API-specific backend gets used by a QRhi instance.

Constant | Value
--- | ---
`QRhi::Null` | `0`
`QRhi::Vulkan` | `1`
`QRhi::OpenGLES2` | `2`
`QRhi::D3D11` | `3`
`QRhi::D3D12` | `5`
`QRhi::Metal` | `4`

### enum QRhi::ResourceLimit

Describes the resource limit to query.

Constant | Value | Description
--- | --- | ---
`QRhi::TextureSizeMin` | `1` | 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.
`QRhi::TextureSizeMax` | `2` | 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.
`QRhi::MaxColorAttachments` | `3` | 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.
`QRhi::FramesInFlight` | `4` | The number of frames the backend may keep "in flight": with backends like Vulkan or Metal, it is the responsibility of QRhi to block whenever starting a new frame and finding the CPU is already `N - 1` frames ahead of the GPU (because the command buffer submitted in frame no. `current` - `N` has not yet completed). The value N is what is returned from here, and is typically 2. This can be relevant to applications that integrate rendering done directly with the graphics API, as such rendering code may want to perform double (if the value is 2) buffering for resources, such as, buffers, similarly to the QRhi backends themselves. The current frame slot index (a value running 0, 1, .., N-1, then wrapping around) is retrievable from QRhi::currentFrameSlot(). The value is 1 for backends where the graphics API offers no such low level control over the command submission process. Note that pipelining may still happen even when this value is 1 (some backends, such as D3D11, are designed to attempt to enable this, for instance, by using an update strategy for uniform buffers that does not stall the pipeline), but that is then not controlled by QRhi and so not reflected here in the API.
`QRhi::MaxAsyncReadbackFrames` | `5` | The number of submitted frames (including the one that contains the readback) after which an asynchronous texture or buffer readback is guaranteed to complete upon starting a new frame.
`QRhi::MaxThreadGroupsPerDimension` | `6` | The maximum number of compute work/thread groups that can be dispatched. Effectively the maximum value for the arguments of QRhiCommandBuffer::dispatch(). Typically 65535.
`QRhi::MaxThreadsPerThreadGroup` | `7` | The maximum number of invocations in a single local work group, or in other terminology, the maximum number of threads in a thread group. Effectively the maximum value for the product of `local_size_x`, `local_size_y`, and `local_size_z` in the compute shader. Typical values are 128, 256, 512, 1024, or 1536. Watch out that both OpenGL ES and Vulkan specify only 128 as the minimum required limit for implementations. While uncommon for Vulkan, some OpenGL ES 3.1 implementations for mobile/embedded devices only support the spec-mandated minimum value.
`QRhi::MaxThreadGroupX` | `8` | The maximum size of a work/thread group in the X dimension. Effectively the maximum value of `local_size_x` in the compute shader. Typically 256 or 1024.
`QRhi::MaxThreadGroupY` | `9` | The maximum size of a work/thread group in the Y dimension. Effectively the maximum value of `local_size_y` in the compute shader. Typically 256 or 1024.
`QRhi::MaxThreadGroupZ` | `10` | The maximum size of a work/thread group in the Z dimension. Effectively the maximum value of `local_size_z` in the compute shader. Typically 64 or 256.
`QRhi::TextureArraySizeMax` | `11` | Maximum texture array size. Typically in range 256 - 2048. Attempting to create a texture array with more elements will likely fail.
`QRhi::MaxUniformBufferRange` | `12` | The number of bytes that can be exposed from a uniform buffer to the shaders at once. On OpenGL ES 2.0 and 3.0 implementations this may be as low as 3584 bytes (224 four component, 32 bits per component vectors). Elsewhere the value is typically 16384 (1024 vec4s) or 65536 (4096 vec4s).
`QRhi::MaxVertexInputs` | `13` | The number of input attributes to the vertex shader. The location in a QRhiVertexInputAttribute must be in range `[0, MaxVertexInputs-1]`. The value may be as low as 8 with OpenGL ES 2.0. Elsewhere, typical values are 16, 31, or 32.
`QRhi::MaxVertexOutputs` | `14` | The maximum number of outputs (4 component vector `out` variables) from the vertex shader. The value may be as low as 8 with OpenGL ES 2.0, and 15 with OpenGL ES 3.0 and some Metal devices. Elsewhere, a typical value is 32.

## Member Function Documentation

### `[noexcept]` QRhi::~QRhi()

Destructor. Destroys the backend and releases resources.

### void QRhi::addCleanupCallback(const QRhi::CleanupCallback &callback)

Registers a callback that is invoked either when the QRhi is destroyed, or when runCleanup() is called.

The callback will run with the graphics resource still available, so this provides an opportunity for the application to cleanly release QRhiResource instances belonging to the QRhi. This is particularly useful for managing the lifetime of resources stored in `cache` type of objects, where the cache holds QRhiResources or objects containing QRhiResources.

See also runCleanup() and ~QRhi().

### void QRhi::addCleanupCallback(const void *key, const QRhi::CleanupCallback &callback)

This is an overloaded function.

Registers callback to be invoked either when the QRhi is destroyed or when runCleanup() is called. This overload takes an opaque pointer, key, that is used to ensure that a given callback is registered (and so called) only once.

See also removeCleanupCallback().

### QRhi::Implementation QRhi::backend() const

Returns the backend type for this QRhi.

### const char *QRhi::backendName() const

Returns the backend type as string for this QRhi.

### `[static]` const char *QRhi::backendName(QRhi::Implementation impl)

Returns a friendly name for the backend impl, usually the name of the 3D API in use.

### QRhi::FrameOpResult QRhi::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags = {})

Starts a new frame targeting the next available buffer of swapChain.

A frame consists of resource updates and one or more render and compute passes.

flags can indicate certain special cases.

The high level pattern of rendering into a QWindow using a swapchain:

- Create a swapchain.
- Call QRhiSwapChain::createOrResize() whenever the surface size is different than before.
- Call QRhiSwapChain::destroy() on QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed.
- Then on every frame:

       beginFrame(sc);
       updates = nextResourceUpdateBatch();
       updates->...
       QRhiCommandBuffer *cb = sc->currentFrameCommandBuffer();
       cb->beginPass(sc->currentFrameRenderTarget(), colorClear, dsClear, updates);
       ...
       cb->endPass();
       ... // more passes as necessary
       endFrame(sc);

Returns QRhi::FrameOpSuccess on success, or another QRhi::FrameOpResult value on failure. Some of these should be treated as soft, "try again later" type of errors: When QRhi::FrameOpSwapChainOutOfDate is returned, the swapchain is to be resized or updated by calling QRhiSwapChain::createOrResize(). The application should then attempt to generate a new frame. QRhi::FrameOpDeviceLost means the graphics device is lost but this may also be recoverable by releasing all resources, including the QRhi itself, and then recreating all resources. See isDeviceLost() for further discussion.

See also endFrame(), beginOffscreenFrame(), and isDeviceLost().

### QRhi::FrameOpResult QRhi::beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags = {})

Starts a new offscreen frame. Provides a command buffer suitable for recording rendering commands in cb. flags is used to indicate certain special cases, just like with beginFrame().

Note: The QRhiCommandBuffer stored to *cb is not owned by the caller.

Rendering without a swapchain is possible as well. The typical use case is to use it in completely offscreen applications, e.g. to generate image sequences by rendering and reading back without ever showing a window.

Usage in on-screen applications (so beginFrame, endFrame, beginOffscreenFrame, endOffscreenFrame, beginFrame, ...) is possible too but it does reduce parallelism so it should be done only infrequently.

Offscreen frames do not let the CPU potentially generate another frame while the GPU is still processing the previous one. This has the side effect that if readbacks are scheduled, the results are guaranteed to be available once endOffscreenFrame() returns. That is not the case with frames targeting a swapchain: there the GPU is potentially better utilized, but working with readback operations needs more care from the application because endFrame(), unlike endOffscreenFrame(), does not guarantee that the results from the readback are available at that point.

The skeleton of rendering a frame without a swapchain and then reading the frame contents back could look like the following:

     QRhiReadbackResult rbResult;
     QRhiCommandBuffer *cb;
     rhi->beginOffscreenFrame(&cb);
     cb->beginPass(rt, colorClear, dsClear);
     // ...
     u = nextResourceUpdateBatch();
     u->readBackTexture(rb, &rbResult);
     cb->endPass(u);
     rhi->endOffscreenFrame();
     // image data available in rbResult

See also endOffscreenFrame() and beginFrame().

### QMatrix4x4 QRhi::clipSpaceCorrMatrix() const

Returns a matrix that can be used to allow applications keep using OpenGL-targeted vertex data and perspective projection matrices (such as, the ones generated by QMatrix4x4::perspective()), regardless of the active QRhi backend.

In a typical renderer, once `this_matrix * mvp` is used instead of just `mvp`, vertex data with Y up and viewports with depth range 0 - 1 can be used without considering what backend (and so graphics API) is going to be used at run time. This way branching based on isYUpInNDC() and isClipDepthZeroToOne() can be avoided (although such logic may still become required when implementing certain advanced graphics techniques).

See this page for a discussion of the topic from Vulkan perspective.

### `[static]` QRhi *QRhi::create(QRhi::Implementation impl, QRhiInitParams *params, QRhi::Flags flags = {}, QRhiNativeHandles *importDevice = nullptr)

Returns a new QRhi instance with a backend for the graphics API specified by impl with the specified flags.

params must point to an instance of one of the backend-specific subclasses of QRhiInitParams, such as, QRhiVulkanInitParams, QRhiMetalInitParams, QRhiD3D11InitParams, QRhiD3D12InitParams, QRhiGles2InitParams. See these classes for examples on creating a QRhi.

QRhi by design does not implement any fallback logic: if the specified API cannot be initialized, create() will fail, with warnings printed on the debug output by the backends. The clients of QRhi, for example Qt Quick, may however provide additional logic that allow falling back to an API different than what was requested, depending on the platform. If the intention is just to test if initialization would succeed when calling create() at later point, it is preferable to use probe() instead of create(), because with some backends probing can be implemented in a more lightweight manner as opposed to create(), which performs full initialization of the infrastructure and is wasteful if that QRhi instance is then thrown immediately away.

importDevice allows using an already existing graphics device, without QRhi creating its own. When not null, this parameter must point to an instance of one of the subclasses of QRhiNativeHandles: QRhiVulkanNativeHandles, QRhiD3D11NativeHandles, QRhiD3D12NativeHandles, QRhiMetalNativeHandles, QRhiGles2NativeHandles. The exact details and semantics depend on the backand and the underlying graphics API.

See also probe().

### int QRhi::currentFrameSlot() const

Returns the current frame slot index while recording a frame. Unspecified when called outside an active frame (that is, when isRecordingFrame() is `false`).

With backends like Vulkan or Metal, it is the responsibility of the QRhi backend to block whenever starting a new frame and finding the CPU is already `FramesInFlight - 1` frames ahead of the GPU (because the command buffer submitted in frame no. `current` - `FramesInFlight` has not yet completed).

Resources that tend to change between frames (such as, the native buffer object backing a QRhiBuffer with type QRhiBuffer::Dynamic) exist in multiple versions, so that each frame, that can be submitted while a previous one is still being processed, works with its own copy, thus avoiding the need to stall the pipeline when preparing the frame. (The contents of a resource that may still be in use in the GPU should not be touched, but simply always waiting for the previous frame to finish would reduce GPU utilization and ultimately, performance and efficiency.)

Conceptually this is somewhat similar to copy-on-write schemes used by some C++ containers and other types. It may also be similar to what an OpenGL or Direct 3D 11 implementation performs internally for certain type of objects.

In practice, such double (or triple) buffering resources is realized in the Vulkan, Metal, and similar QRhi backends by having a fixed number of native resource (such as, VkBuffer) `slots` behind a QRhiResource. That can then be indexed by a frame slot index running 0, 1, .., FramesInFlight-1, and then wrapping around.

All this is managed transparently to the users of QRhi. However, applications that integrate rendering done directly with the graphics API may want to perform a similar double or triple buffering of their own graphics resources. That is then most easily achieved by knowing the values of the maximum number of in-flight frames (retrievable via resourceLimit()) and the current frame (slot) index (returned by this function).

See also isRecordingFrame(), beginFrame(), and endFrame().

### QRhiDriverInfo QRhi::driverInfo() const

Returns metadata for the graphics device used by this successfully initialized QRhi instance.

### QRhi::FrameOpResult QRhi::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags = {})

Ends, commits, and presents a frame that was started in the last beginFrame() on swapChain.

Double (or triple) buffering is managed internally by the QRhiSwapChain and QRhi.

flags can optionally be used to change the behavior in certain ways. Passing QRhi::SkipPresent skips queuing the Present command or calling swapBuffers.

Returns QRhi::FrameOpSuccess on success, or another QRhi::FrameOpResult value on failure. Some of these should be treated as soft, "try again later" type of errors: When QRhi::FrameOpSwapChainOutOfDate is returned, the swapchain is to be resized or updated by calling QRhiSwapChain::createOrResize(). The application should then attempt to generate a new frame. QRhi::FrameOpDeviceLost means the graphics device is lost but this may also be recoverable by releasing all resources, including the QRhi itself, and then recreating all resources. See isDeviceLost() for further discussion.

See also beginFrame() and isDeviceLost().

### QRhi::FrameOpResult QRhi::endOffscreenFrame(QRhi::EndFrameFlags flags = {})

Ends, submits, and waits for the offscreen frame.

flags is not currently used.

See also beginOffscreenFrame().

### QRhi::FrameOpResult QRhi::finish()

Waits for any work on the graphics queue (where applicable) to complete, then executes all deferred operations, like completing readbacks and resource releases. Can be called inside and outside of a frame, but not inside a pass. Inside a frame it implies submitting any work on the command buffer.

Note: Avoid this function. One case where it may be needed is when the results of an enqueued readback in a swapchain-based frame are needed at a fixed given point and so waiting for the results is desired.

### bool QRhi::isClipDepthZeroToOne() const

Returns `true` if the underlying graphics API uses depth range [0, 1] in clip space.

In practice this is `false` for OpenGL only, because OpenGL uses a post-projection depth range of [-1, 1]. (not to be confused with the NDC-to-window mapping controlled by glDepthRange(), which uses a range of [0, 1], unless overridden by the QRhiViewport) In some OpenGL versions glClipControl() could be used to change this, but the OpenGL backend of QRhi does not use that function as it is not available in OpenGL ES or OpenGL versions lower than 4.5.

Note: clipSpaceCorrMatrix() includes the corresponding adjustment in its returned matrix. Therefore, many users of QRhi do not need to take any further measures apart from pre-multiplying their projection matrices with clipSpaceCorrMatrix(). However, some graphics techniques, such as, some types of shadow mapping, involve working with and outputting depth values in the shaders. These will need to query and take the value of this function into account as appropriate.

### bool QRhi::isDeviceLost() const

Returns true if the graphics device was lost.

The loss of the device is typically detected in beginFrame(), endFrame() or QRhiSwapChain::createOrResize(), depending on the backend and the underlying native APIs. The most common is endFrame() because that is where presenting happens. With some backends QRhiSwapChain::createOrResize() can also fail due to a device loss. Therefore this function is provided as a generic way to check if a device loss was detected by a previous operation.

When the device is lost, no further operations should be done via the QRhi. Rather, all QRhi resources should be released, followed by destroying the QRhi. A new QRhi can then be attempted to be created. If successful, all graphics resources must be reinitialized. If not, try again later, repeatedly.

While simple applications may decide to not care about device loss, on the commonly used desktop platforms a device loss can happen due to a variety of reasons, including physically disconnecting the graphics adapter, disabling the device or driver, uninstalling or upgrading the graphics driver, or due to errors that lead to a graphics device reset. Some of these can happen under perfectly normal circumstances as well, for example the upgrade of the graphics driver to a newer version is a common task that can happen at any time while a Qt application is running. Users may very well expect applications to be able to survive this, even when the application is actively using an API like OpenGL or Direct3D.

Qt's own frameworks built on top of QRhi, such as, Qt Quick, can be expected to handle and take appropriate measures when a device loss occurs. If the data for graphics resources, such as textures and buffers, are still available on the CPU side, such an event may not be noticeable on the application level at all since graphics resources can seamlessly be reinitialized then. However, applications and libraries working directly with QRhi are expected to be prepared to check and handle device loss situations themselves.

Note: With OpenGL, applications may need to opt-in to context reset notifications by setting QSurfaceFormat::ResetNotification on the QOpenGLContext. This is typically done by enabling the flag in QRhiGles2InitParams::format. Keep in mind however that some systems may generate context resets situations even when this flag is not set.

### bool QRhi::isFeatureSupported(QRhi::Feature feature) const

Returns `true` if the specified feature is supported

### bool QRhi::isRecordingFrame() const

Returns true when there is an active frame, meaning there was a beginFrame() (or beginOffscreenFrame()) with no corresponding endFrame() (or endOffscreenFrame()) yet.

See also currentFrameSlot(), beginFrame(), and endFrame().

### bool QRhi::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags = {}) const

Returns `true` if the specified texture format modified by flags is supported.

The query is supported both for uncompressed and compressed formats.

### bool QRhi::isYUpInFramebuffer() const

Returns `true` if the underlying graphics API has the Y axis pointing up in framebuffers and images.

In practice this is `true` for OpenGL only.

### bool QRhi::isYUpInNDC() const

Returns `true` if the underlying graphics API has the Y axis pointing up in its normalized device coordinate system.

In practice this is `false` for Vulkan only.

Note: clipSpaceCorrMatrix() includes the corresponding adjustment (to make Y point up) in its returned matrix.

### bool QRhi::makeThreadLocalNativeContextCurrent()

With OpenGL this makes the OpenGL context current on the current thread. The function has no effect with other backends.

Calling this function is relevant typically in Qt framework code, when one has to ensure external OpenGL code provided by the application can still run like it did before with direct usage of OpenGL, as long as the QRhi is using the OpenGL backend.

Returns false when failed, similarly to QOpenGLContext::makeCurrent(). When the operation failed, isDeviceLost() can be called to determine if there was a loss of context situation. Such a check is equivalent to checking via QOpenGLContext::isValid().

See also QOpenGLContext::makeCurrent() and QOpenGLContext::isValid().

### `[static]` int QRhi::mipLevelsForSize(const QSize &size)

Returns the number of mip levels for a given size.

### const QRhiNativeHandles *QRhi::nativeHandles()

Returns a pointer to the backend-specific collection of native objects for the device, context, and similar concepts used by the backend.

Cast to QRhiVulkanNativeHandles, QRhiD3D11NativeHandles, QRhiD3D12NativeHandles, QRhiGles2NativeHandles, or QRhiMetalNativeHandles as appropriate.

Note: No ownership is transferred, neither for the returned pointer nor for any native objects.

### QRhiBuffer *QRhi::newBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)

Returns a new buffer with the specified type, usage, and size.

Note: Some usage and type combinations may not be supported by all backends. See UsageFlags and the feature flags.

Note: Backends may choose to allocate buffers bigger than size. This is done transparently to applications, so there are no special restrictions on the value of size. QRhiBuffer::size() will always report back the value that was requested in size.

See also QRhiResource::destroy().

### QRhiComputePipeline *QRhi::newComputePipeline()

Returns a new compute pipeline resource.

Note: Compute is only available when the Compute feature is reported as supported.

See also QRhiResource::destroy().

### QRhiGraphicsPipeline *QRhi::newGraphicsPipeline()

Returns a new graphics pipeline resource.

See also QRhiResource::destroy().

### QRhiRenderBuffer *QRhi::newRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize, int sampleCount = 1, QRhiRenderBuffer::Flags flags = {}, QRhiTexture::Format backingFormatHint = QRhiTexture::UnknownFormat)

Returns a new renderbuffer with the specified type, pixelSize, sampleCount, and flags.

When backingFormatHint is set to a texture format other than QRhiTexture::UnknownFormat, it may be used by the backend to decide what format to use for the storage backing the renderbuffer.

Note: backingFormatHint becomes relevant typically when multisampling and floating point texture formats are involved: rendering into a multisample QRhiRenderBuffer and then resolving into a non-RGBA8 QRhiTexture implies (with some graphics APIs) that the storage backing the QRhiRenderBuffer uses the matching non-RGBA8 format. That means that passing a format like QRhiTexture::RGBA32F is important, because backends will typically opt for QRhiTexture::RGBA8 by default, which would then break later on due to attempting to set up RGBA8->RGBA32F multisample resolve in the color attachment(s) of the QRhiTextureRenderTarget.

See also QRhiResource::destroy().

### QRhiSampler *QRhi::newSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter, QRhiSampler::Filter mipmapMode, QRhiSampler::AddressMode addressU, QRhiSampler::AddressMode addressV, QRhiSampler::AddressMode addressW = QRhiSampler::Repeat)

Returns a new sampler with the specified magnification filter magFilter, minification filter minFilter, mipmapping mode mipmapMode, and the addressing (wrap) modes addressU, addressV, and addressW.

Note: Setting mipmapMode to a value other than `None` implies that images for all relevant mip levels will be provided either via texture uploads or by calling generateMips() on the texture that is used with this sampler. Attempting to use the sampler with a texture that has no data for all relevant mip levels will lead to rendering errors, with the exact behavior dependent on the underlying graphics API.

See also QRhiResource::destroy().

### QRhiShaderResourceBindings *QRhi::newShaderResourceBindings()

Returns a new shader resource binding collection resource.

See also QRhiResource::destroy().

### QRhiSwapChain *QRhi::newSwapChain()

Returns a new swapchain.

See also QRhiResource::destroy() and QRhiSwapChain::createOrResize().

### QRhiTexture *QRhi::newTexture(QRhiTexture::Format format, const QSize &pixelSize, int sampleCount = 1, QRhiTexture::Flags flags = {})

Returns a new 1D or 2D texture with the specified format, pixelSize, sampleCount, and flags.

A 1D texture array must have QRhiTexture::OneDimensional set in flags. This function will implicitly set this flag if the pixelSize height is 0.

Note: format specifies the requested internal and external format, meaning the data to be uploaded to the texture will need to be in a compatible format, while the native texture may (but is not guaranteed to, in case of OpenGL at least) use this format internally.

Note: 1D textures are only functional when the OneDimensionalTextures feature is reported as supported at run time. Further, mipmaps on 1D textures are only functional when the OneDimensionalTextureMipmaps feature is reported at run time.

See also QRhiResource::destroy().

### QRhiTexture *QRhi::newTexture(QRhiTexture::Format format, int width, int height, int depth, int sampleCount = 1, QRhiTexture::Flags flags = {})

Returns a new 1D, 2D or 3D texture with the specified format, width, height, depth, sampleCount, and flags.

This overload is suitable for 3D textures because it allows specifying depth. A 3D texture must have QRhiTexture::ThreeDimensional set in flags, but using this overload that can be omitted because the flag is set implicitly whenever depth is greater than 0. For 1D, 2D and cube textures depth should be set to 0.

A 1D texture must have QRhiTexture::OneDimensional set in flags. This overload will implicitly set this flag if both height and depth are 0.

Note: 3D textures are only functional when the ThreeDimensionalTextures feature is reported as supported at run time.

Note: 1D textures are only functional when the OneDimensionalTextures feature is reported as supported at run time. Further, mipmaps on 1D textures are only functional when the OneDimensionalTextureMipmaps feature is reported at run time.

This is an overloaded function.

### QRhiTexture *QRhi::newTextureArray(QRhiTexture::Format format, int arraySize, const QSize &pixelSize, int sampleCount = 1, QRhiTexture::Flags flags = {})

Returns a new 1D or 2D texture array with the specified format, arraySize, pixelSize, sampleCount, and flags.

This function implicitly sets QRhiTexture::TextureArray in flags.

A 1D texture array must have QRhiTexture::OneDimensional set in flags. This function will implicitly set this flag if the pixelSize height is 0.

Note: Do not confuse texture arrays with arrays of textures. A QRhiTexture created by this function is usable with 1D or 2D array samplers in the shader, for example: `layout(binding = 1) uniform sampler2DArray texArr;`. Arrays of textures refers to a list of textures that are exposed to the shader via QRhiShaderResourceBinding::sampledTextures() and a count > 1, and declared in the shader for example like this: `layout(binding = 1) uniform sampler2D textures[4];`

Note: This is only functional when the TextureArrays feature is reported as supported at run time.

Note: 1D textures are only functional when the OneDimensionalTextures feature is reported as supported at run time. Further, mipmaps on 1D textures are only functional when the OneDimensionalTextureMipmaps feature is reported at run time.

See also newTexture().

### QRhiTextureRenderTarget *QRhi::newTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc, QRhiTextureRenderTarget::Flags flags = {})

Returns a new texture render target with color and depth/stencil attachments given in desc, and with the specified flags.

See also QRhiResource::destroy().

### QRhiResourceUpdateBatch *QRhi::nextResourceUpdateBatch()

Returns an available, empty batch to which copy type of operations can be recorded.

Note: the return value is not owned by the caller and must never be destroyed. Instead, the batch is returned the pool for reuse by passing it to QRhiCommandBuffer::beginPass(), QRhiCommandBuffer::endPass(), or QRhiCommandBuffer::resourceUpdate(), or by calling QRhiResourceUpdateBatch::destroy() on it.

Note: Can be called outside beginFrame() - endFrame() as well since a batch instance just collects data on its own, it does not perform any operations.

Due to not being tied to a frame being recorded, the following sequence is valid for example:

     rhi->beginFrame(swapchain);
     QRhiResourceUpdateBatch *u = rhi->nextResourceUpdateBatch();
     u->uploadStaticBuffer(buf, data);
     // ... do not commit the batch
     rhi->endFrame();
     // u stays valid (assuming buf stays valid as well)
     rhi->beginFrame(swapchain);
     swapchain->currentFrameCommandBuffer()->resourceUpdate(u);
     // ... draw with buf
     rhi->endFrame();

Warning: The maximum number of batches per QRhi is 64. When this limit is reached, the function will return null until a batch is returned to the pool.

### QByteArray QRhi::pipelineCacheData()

Returns a binary data blob with data collected from the QRhiGraphicsPipeline and QRhiComputePipeline successfully created during the lifetime of this QRhi.

By saving and then, in subsequent runs of the same application, reloading the cache data, pipeline and shader creation times can potentially be reduced. What exactly the cache and its serialized version includes is not specified, is always specific to the backend used, and in some cases also dependent on the particular implementation of the graphics API.

When the PipelineCacheDataLoadSave is reported as unsupported, the returned QByteArray is empty.

When the EnablePipelineCacheDataSave flag was not specified when calling create(), the returned QByteArray may be empty, even when the PipelineCacheDataLoadSave feature is supported.

When the returned data is non-empty, it is always specific to the Qt version and QRhi backend. In addition, in some cases there is a strong dependency to the graphics device and the exact driver version used. QRhi takes care of adding the appropriate header and safeguards that ensure that the data can always be passed safely to setPipelineCacheData(), therefore attempting to load data from a run on another version of a driver will be handled safely and gracefully.

Note: Calling releaseCachedResources() may, depending on the backend, clear the pipeline data collected. A subsequent call to this function may then not return any data.

See EnablePipelineCacheDataSave for further details about this feature.

Note: Minimize the number of calls to this function. Retrieving the blob is not always a cheap operation, and therefore this function should only be called at a low frequency, ideally only once e.g. when closing the application.

See also setPipelineCacheData(), create(), and isFeatureSupported().

### `[static]` bool QRhi::probe(QRhi::Implementation impl, QRhiInitParams *params)

Returns true if create() can be expected to succeed when called the given impl and params.

For some backends this is equivalent to calling create(), checking its return value, and then destroying the resulting QRhi.

For others, in particular with Metal, there may be a specific probing implementation, which allows testing in a more lightweight manner without polluting the debug output with warnings upon failures.

See also create().

### void QRhi::releaseCachedResources()

Attempts to release resources in the backend's caches. This can include both CPU and GPU resources. Only memory and resources that can be recreated automatically are in scope. As an example, if the backend's QRhiGraphicsPipeline implementation maintains a cache of shader compilation results, calling this function leads to emptying that cache, thus potentially freeing up memory and graphics resources.

Calling this function makes sense in resource constrained environments, where at a certain point there is a need to ensure minimal resource usage, at the expense of performance.

### void QRhi::removeCleanupCallback(const void *key)

Deregisters the callback with key. If no cleanup callback was registered with key, the function does nothing. Callbacks registered without a key cannot be removed.

See also addCleanupCallback().

### int QRhi::resourceLimit(QRhi::ResourceLimit limit) const

Returns the value for the specified resource limit.

The values are expected to be queried by the backends upon initialization, meaning calling this function is a light operation.

### void QRhi::runCleanup()

Invokes all registered cleanup functions. The list of cleanup callbacks it then cleared. Normally destroying the QRhi does this automatically, but sometimes it can be useful to trigger cleanup in order to release all cached, non-essential resources.

See also addCleanupCallback().

### void QRhi::setPipelineCacheData(const QByteArray &data)

Loads data into the pipeline cache, when applicable.

When the PipelineCacheDataLoadSave is reported as unsupported, the function is safe to call, but has no effect.

The blob returned by pipelineCacheData() is always specific to the Qt version, the QRhi backend, and, in some cases, also to the graphics device, and a given version of the graphics driver. QRhi takes care of adding the appropriate header and safeguards that ensure that the data can always be passed safely to this function. If there is a mismatch, e.g. because the driver has been upgraded to a newer version, or because the data was generated from a different QRhi backend, a warning is printed and data is safely ignored.

With Vulkan, this maps directly to VkPipelineCache. Calling this function creates a new Vulkan pipeline cache object, with its initial data sourced from data. The pipeline cache object is then used by all subsequently created QRhiGraphicsPipeline and QRhiComputePipeline objects, thus accelerating, potentially, the pipeline creation.

With other APIs there is no real pipeline cache, but they may provide a cache with bytecode from shader compilations (D3D) or program binaries (OpenGL). In applications that perform a lot of shader compilation from source at run time this can provide a significant boost in subsequent runs if the "pipeline cache" is pre-seeded from an earlier run using this function.

Note: QRhi cannot give any guarantees that data has an effect on the pipeline and shader creation performance. With APIs like Vulkan, it is up to the driver to decide if data is used for some purpose, or if it is ignored.

See EnablePipelineCacheDataSave for further details about this feature.

Note: This mechanism offered by QRhi is independent of the drivers' own internal caching mechanism, if any. This means that, depending on the graphics API and its implementation, the exact effects of retrieving and then reloading data are not predictable. Improved performance may not be visible at all in case other caching mechanisms outside of Qt's control are already active.

Note: Minimize the number of calls to this function. Loading the blob is not always a cheap operation, and therefore this function should only be called at a low frequency, ideally only once e.g. when starting the application.

See also pipelineCacheData() and isFeatureSupported().

### `[static]` QSize QRhi::sizeForMipLevel(int mipLevel, const QSize &baseLevelSize)

Returns the texture image size for a given mipLevel, calculated based on the level 0 size given in baseLevelSize.

### QRhiStats QRhi::statistics() const

Gathers and returns statistics about the timings and allocations of graphics resources.

Data about memory allocations is only available with some backends, where such operations are under Qt's control. With graphics APIs where there is no lower level control over resource memory allocations, this will never be supported and all relevant fields in the results are 0.

With Vulkan in particular, the values are valid always, and are queried from the underlying memory allocator library. This gives an insight into the memory requirements of the active buffers and textures.

The same is true for Direct 3D 12. In addition to the memory allocator library's statistics, here the result also includes a `totalUsageBytes` field which reports the total size including additional resources that are not under the memory allocator library's control (swapchain buffers, descriptor heaps, etc.), as reported by DXGI.

The values correspond to all types of memory used, combined. (i.e. video + system in case of a discreet GPU)

Additional data, such as the total time in milliseconds spent in graphics and compute pipeline creation (which usually involves shader compilation or cache lookups, and potentially expensive processing) is available with most backends.

Note: The elapsed times for operations such as pipeline creation may be affected by various factors. The results should not be compared between different backends since the concept of "pipelines" and what exactly happens under the hood during, for instance, a call to QRhiGraphicsPipeline::create(), differ greatly between graphics APIs and their implementations.

Note: Additionally, many drivers will likely employ various caching strategies for shaders, programs, pipelines. (independently of Qt's own similar facilities, such as setPipelineCacheData() or the OpenGL-specific program binary disk cache). Because such internal behavior is transparent to the API client, Qt and QRhi have no knowledge or control over the exact caching strategy, persistency, invalidation of the cached data, etc. When reading timings, such as the time spent on pipeline creation, the potential presence and unspecified behavior of driver-level caching mechanisms should be kept in mind.

### QList<int> QRhi::supportedSampleCounts() const

Returns the list of supported sample counts.

A typical example would be (1, 2, 4, 8).

With some backend this list of supported values is fixed in advance, while with some others the (physical) device properties indicate what is supported at run time.

See also QRhiRenderBuffer::setSampleCount(), QRhiTexture::setSampleCount(), QRhiGraphicsPipeline::setSampleCount(), and QRhiSwapChain::setSampleCount().

### QThread *QRhi::thread() const

Returns the thread on which the QRhi was initialized.

### int QRhi::ubufAligned(int v) const

Returns the value (typically an offset) v aligned to the uniform buffer alignment given by by ubufAlignment().

### int QRhi::ubufAlignment() const

Returns the minimum uniform buffer offset alignment in bytes. This is typically 256.

Attempting to bind a uniform buffer region with an offset not aligned to this value will lead to failures depending on the backend and the underlying graphics API.

See also ubufAligned().

### `[static]` QRhiSwapChainProxyData QRhi::updateSwapChainProxyData(QRhi::Implementation impl, QWindow *window)

Generates and returns a QRhiSwapChainProxyData struct containing opaque data specific to the backend and graphics API specified by impl. window is the QWindow a swapchain is targeting.

The returned struct can be passed to QRhiSwapChain::setProxyData(). This makes sense in threaded rendering systems: this static function is expected to be called on the main (gui) thread, unlike all QRhi operations, then transferred to the thread working with the QRhi and QRhiSwapChain and passed on to the swapchain. This allows doing native platform queries that are only safe to be called on the main thread, for example to query the CAMetalLayer from a NSView, and then passing on the data to the QRhiSwapChain living on the rendering thread. With the Metal example, doing the view.layer access on a dedicated rendering thread causes a warning in the Xcode Thread Checker. With the data proxy mechanism, this is avoided.

When threads are not involved, generating and passing on the QRhiSwapChainProxyData is not required: backends are guaranteed to be able to query whatever is needed on their own, and if everything lives on the main (gui) thread, that should be sufficient.

Note: impl should match what the QRhi is created with. For example, calling with QRhi::Metal on a non-Apple platform will not generate any useful data.

## Related Non-Members

### `[alias, since 6.7]` QRhiShaderResourceBindingSet

Synonym for QRhiShaderResourceBindings.

This typedef was introduced in Qt 6.7.