Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QRhi Class Reference

\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h More...

#include <qrhi.h>

+ Collaboration diagram for QRhi:

Public Types

enum  Implementation {
  Null , Vulkan , OpenGLES2 , D3D11 ,
  Metal , D3D12
}
 Describes which graphics API-specific backend gets used by a QRhi instance. More...
 
enum  Flag {
  EnableDebugMarkers = 1 << 0 , PreferSoftwareRenderer = 1 << 1 , EnablePipelineCacheDataSave = 1 << 2 , EnableTimestamps = 1 << 3 ,
  SuppressSmokeTestWarnings = 1 << 4
}
 Describes what special features to enable. More...
 
enum  FrameOpResult { FrameOpSuccess = 0 , FrameOpError , FrameOpSwapChainOutOfDate , FrameOpDeviceLost }
 Describes the result of operations that can have a soft failure. More...
 
enum  Feature {
  MultisampleTexture = 1 , MultisampleRenderBuffer , DebugMarkers , Timestamps ,
  Instancing , CustomInstanceStepRate , PrimitiveRestart , NonDynamicUniformBuffers ,
  NonFourAlignedEffectiveIndexBufferOffset , NPOTTextureRepeat , RedOrAlpha8IsRed , ElementIndexUint ,
  Compute , WideLines , VertexShaderPointSize , BaseVertex ,
  BaseInstance , TriangleFanTopology , ReadBackNonUniformBuffer , ReadBackNonBaseMipLevel ,
  TexelFetch , RenderToNonBaseMipLevel , IntAttributes , ScreenSpaceDerivatives ,
  ReadBackAnyTextureFormat , PipelineCacheDataLoadSave , ImageDataStride , RenderBufferImport ,
  ThreeDimensionalTextures , RenderTo3DTextureSlice , TextureArrays , Tessellation ,
  GeometryShader , TextureArrayRange , NonFillPolygonMode , OneDimensionalTextures ,
  OneDimensionalTextureMipmaps , HalfAttributes , RenderToOneDimensionalTexture , ThreeDimensionalTextureMipmaps ,
  MultiView , TextureViewFormat , ResolveDepthStencil
}
 Flag values to indicate what features are supported by the backend currently in use. More...
 
enum  BeginFrameFlag
 Flag values for QRhi::beginFrame() More...
 
enum  EndFrameFlag { SkipPresent = 1 << 0 }
 Flag values for QRhi::endFrame() More...
 
enum  ResourceLimit {
  TextureSizeMin = 1 , TextureSizeMax , MaxColorAttachments , FramesInFlight ,
  MaxAsyncReadbackFrames , MaxThreadGroupsPerDimension , MaxThreadsPerThreadGroup , MaxThreadGroupX ,
  MaxThreadGroupY , MaxThreadGroupZ , TextureArraySizeMax , MaxUniformBufferRange ,
  MaxVertexInputs , MaxVertexOutputs
}
 Describes the resource limit to query. More...
 
using CleanupCallback = std::function<void(QRhi *)>
 

Public Member Functions

 ~QRhi ()
 Destructor.
 
Implementation backend () const
 
const char * backendName () const
 
QRhiDriverInfo driverInfo () const
 
QThreadthread () const
 
void addCleanupCallback (const CleanupCallback &callback)
 Registers a callback that is invoked either when the QRhi is destroyed, or when runCleanup() is called.
 
void addCleanupCallback (const void *key, const CleanupCallback &callback)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Registers callback to be invoked either when the QRhi is destroyed or when runCleanup() is called.
 
void removeCleanupCallback (const void *key)
 Deregisters the callback with key.
 
void runCleanup ()
 Invokes all registered cleanup functions.
 
QRhiGraphicsPipelinenewGraphicsPipeline ()
 
QRhiComputePipelinenewComputePipeline ()
 
QRhiShaderResourceBindingsnewShaderResourceBindings ()
 
QRhiBuffernewBuffer (QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
 
QRhiRenderBuffernewRenderBuffer (QRhiRenderBuffer::Type type, const QSize &pixelSize, int sampleCount=1, QRhiRenderBuffer::Flags flags={}, QRhiTexture::Format backingFormatHint=QRhiTexture::UnknownFormat)
 
QRhiTexturenewTexture (QRhiTexture::Format format, const QSize &pixelSize, int sampleCount=1, QRhiTexture::Flags flags={})
 
QRhiTexturenewTexture (QRhiTexture::Format format, int width, int height, int depth, int sampleCount=1, QRhiTexture::Flags flags={})
 
QRhiTexturenewTextureArray (QRhiTexture::Format format, int arraySize, const QSize &pixelSize, int sampleCount=1, QRhiTexture::Flags flags={})
 
QRhiSamplernewSampler (QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter, QRhiSampler::Filter mipmapMode, QRhiSampler::AddressMode addressU, QRhiSampler::AddressMode addressV, QRhiSampler::AddressMode addressW=QRhiSampler::Repeat)
 
QRhiTextureRenderTargetnewTextureRenderTarget (const QRhiTextureRenderTargetDescription &desc, QRhiTextureRenderTarget::Flags flags={})
 
QRhiSwapChainnewSwapChain ()
 
FrameOpResult beginFrame (QRhiSwapChain *swapChain, BeginFrameFlags flags={})
 Starts a new frame targeting the next available buffer of swapChain.
 
FrameOpResult endFrame (QRhiSwapChain *swapChain, EndFrameFlags flags={})
 Ends, commits, and presents a frame that was started in the last beginFrame() on swapChain.
 
bool isRecordingFrame () const
 
int currentFrameSlot () const
 
FrameOpResult beginOffscreenFrame (QRhiCommandBuffer **cb, BeginFrameFlags flags={})
 Starts a new offscreen frame.
 
FrameOpResult endOffscreenFrame (EndFrameFlags flags={})
 Ends, submits, and waits for the offscreen frame.
 
QRhi::FrameOpResult finish ()
 Waits for any work on the graphics queue (where applicable) to complete, then executes all deferred operations, like completing readbacks and resource releases.
 
QRhiResourceUpdateBatchnextResourceUpdateBatch ()
 
QList< int > supportedSampleCounts () const
 
int ubufAlignment () const
 
int ubufAligned (int v) const
 
bool isYUpInFramebuffer () const
 
bool isYUpInNDC () const
 
bool isClipDepthZeroToOne () const
 
QMatrix4x4 clipSpaceCorrMatrix () const
 
bool isTextureFormatSupported (QRhiTexture::Format format, QRhiTexture::Flags flags={}) const
 
bool isFeatureSupported (QRhi::Feature feature) const
 
int resourceLimit (ResourceLimit limit) const
 
const QRhiNativeHandlesnativeHandles ()
 
bool makeThreadLocalNativeContextCurrent ()
 With OpenGL this makes the OpenGL context current on the current thread.
 
void releaseCachedResources ()
 Attempts to release resources in the backend's caches.
 
bool isDeviceLost () const
 
QByteArray pipelineCacheData ()
 
void setPipelineCacheData (const QByteArray &data)
 Loads data into the pipeline cache, when applicable.
 
QRhiStats statistics () const
 Gathers and returns statistics about the timings and allocations of graphics resources.
 

Static Public Member Functions

static QRhicreate (Implementation impl, QRhiInitParams *params, Flags flags={}, QRhiNativeHandles *importDevice=nullptr)
 
static bool probe (Implementation impl, QRhiInitParams *params)
 
static const char * backendName (Implementation impl)
 
static int mipLevelsForSize (const QSize &size)
 
static QSize sizeForMipLevel (int mipLevel, const QSize &baseLevelSize)
 
static QRhiSwapChainProxyData updateSwapChainProxyData (Implementation impl, QWindow *window)
 Generates and returns a QRhiSwapChainProxyData struct containing opaque data specific to the backend and graphics API specified by impl.
 

Static Public Attributes

static constexpr int MAX_MIP_LEVELS = 16
 

Protected Member Functions

 QRhi ()
 

Related Symbols

(Note that these are not member symbols.)

 QRhiShaderResourceBindingSet
 

Detailed Description

\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h

Since
6.6

Accelerated 2D/3D graphics API abstraction.

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

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:

\list

  • 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 \l{QRhi::Feature}{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 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.

\endlist

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 \l{RHI Window Example} for an introductory example of creating a portable, cross-platform application that performs accelerated 3D rendering onto a QWindow using QRhi.

Definition at line 1803 of file qrhi.h.

Member Typedef Documentation

◆ CleanupCallback

using QRhi::CleanupCallback = std::function<void(QRhi *)>

Definition at line 1917 of file qrhi.h.

Member Enumeration Documentation

◆ BeginFrameFlag

Flag values for QRhi::beginFrame()

Definition at line 1877 of file qrhi.h.

◆ EndFrameFlag

Flag values for QRhi::endFrame()

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

Enumerator
SkipPresent 

Definition at line 1881 of file qrhi.h.

◆ Feature

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

\value MultisampleTexture 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.

\value MultisampleRenderBuffer 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.

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

\value Timestamps 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.

\value Instancing Indicates that instanced drawing is supported. In practice this feature will be unsupported with OpenGL ES 2.0 and OpenGL 3.2 or older.

\value CustomInstanceStepRate 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.

\value PrimitiveRestart Indicates that restarting the assembly of primitives when encountering an index value of 0xFFFF (\l{QRhiCommandBuffer::IndexUInt16}{IndexUInt16}) or 0xFFFFFFFF (\l{QRhiCommandBuffer::IndexUInt32}{IndexUInt32}) is enabled, for certain primitive topologies at least. QRhi will try to enable this with all backends, but in some cases it will not be supported. Dynamically controlling primitive restart is not possible since with some APIs primitive restart with a fixed index is always on. Applications must assume 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 \l{QRhiGraphicsPipeline::LineStrip}{LineStrip} and \l{QRhiGraphicsPipeline::TriangleStrip}{TriangleStrip}.

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

\value NonFourAlignedEffectiveIndexBufferOffset Indicates that effective index buffer offsets ({indexOffset + firstIndex * indexComponentSize}) that are not 4 byte aligned are supported. When not supported, attempting to issue a \l{QRhiCommandBuffer::drawIndexed()}{drawIndexed()} with a non-aligned effective offset may lead to unspecified behavior. Relevant in particular for Metal, where this will be reported as unsupported.

\value NPOTTextureRepeat Indicates that the \l{QRhiSampler::Repeat}{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}.

\value RedOrAlpha8IsRed Indicates that the \l{QRhiTexture::RED_OR_ALPHA8}{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.

\value ElementIndexUint 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.

\value Compute 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.

\value WideLines 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.

\value VertexShaderPointSize 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.

\value BaseVertex Indicates that \l{QRhiCommandBuffer::drawIndexed()}{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.

\value BaseInstance 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.

\value TriangleFanTopology Indicates that QRhiGraphicsPipeline::setTopology() supports QRhiGraphicsPipeline::TriangleFan. In practice this feature will be unsupported with Metal and Direct 3D 11/12.

\value ReadBackNonUniformBuffer Indicates that \l{QRhiResourceUpdateBatch::readBackBuffer()}{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.

\value ReadBackNonBaseMipLevel 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.

\value TexelFetch 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.

\value RenderToNonBaseMipLevel 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.

\value IntAttributes 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.

\value ScreenSpaceDerivatives 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.

\value ReadBackAnyTextureFormat 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.

\value PipelineCacheDataLoadSave 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.

\value ImageDataStride 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.

\value RenderBufferImport 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.

\value ThreeDimensionalTextures Indicates that 3D textures are supported. In practice this feature will be unsupported with OpenGL and OpenGL ES versions lower than 3.0.

\value RenderTo3DTextureSlice 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.

\value TextureArrays 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.

\value Tessellation Indicates that the tessellation control and evaluation stages are supported. When reported as supported, the topology of a QRhiGraphicsPipeline can be set to \l{QRhiGraphicsPipeline::Patches}{Patches}, the number of control points can be set via \l{QRhiGraphicsPipeline::setPatchControlPointCount()}{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.

\value GeometryShader 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.

\value TextureArrayRange Indicates that for \l{QRhi::newTextureArray()}{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 \l{QRhiTexture::create()}{building} or \l{QRhiTexture::createFrom()}{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.

\value NonFillPolygonMode 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.

\value OneDimensionalTextures Indicates that 1D textures are supported. In practice this feature will be unsupported on OpenGL ES.

\value OneDimensionalTextureMipmaps Indicates that generating 1D texture mipmaps are supported. In practice this feature will be unsupported on backends that do not report support for \l{OneDimensionalTextures}, Metal, and Direct 3D 12.

\value HalfAttributes 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.

\value RenderToOneDimensionalTexture Indicates that 1D texture render targets are supported. In practice this feature will be unsupported on backends that do not report support for \l{OneDimensionalTextures}, and Metal.

\value ThreeDimensionalTextureMipmaps Indicates that generating 3D texture mipmaps are supported. In practice this feature will be unsupported with Direct 3D 12.

\value MultiView Indicates that multiview, see e.g. \l{https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_multiview.html}{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 \l{QRhiColorAttachment::setMultiViewCount()}{multiViewCount} set enables recording a render pass that uses multiview rendering. In addition, any QRhiGraphicsPipeline used in that render pass must have \l{QRhiGraphicsPipeline::setMultiViewCount()}{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 \l 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.

\value TextureViewFormat Indicates that setting a \l{QRhiTexture::setWriteViewFormat()}{view format} on a QRhiTexture is effective. When reported as supported, setting the read (sampling) or write (render target / image load-store) view mode changes the texture's viewing format. When unsupported, setting a view format has no effect. Note that Qt has no knowledge or control over format compatibility or resource view rules in the underlying 3D API and its implementation. Passing in unsuitable, incompatible formats may lead to errors and unspecified behavior. This is provided mainly to allow "casting" rendering into a texture created with an sRGB format to non-sRGB to avoid the unwanted linear->sRGB conversion on shader writes. Other types of casting may or may not be functional, depending on the underlying API. Currently implemented for Vulkan and Direct 3D 12. With D3D12 the feature is available only if CastingFullyTypedFormatSupported is supported, see \l{https://microsoft.github.io/DirectX-Specs/d3d/RelaxedCasting.html} (and note that QRhi always uses fully typed formats for textures.) This enum value has been introduced in Qt 6.8.

\value ResolveDepthStencil Indicates that resolving a multisample depth or depth-stencil texture is supported. Otherwise, \l{QRhiTextureRenderTargetDescription::setDepthResolveTexture()}{setting a depth resolve texture} is not functional and must be avoided. Direct 3D 11 and 12 have no support for resolving depth/depth-stencil formats, and therefore this feature will never be supported with those. Vulkan 1.0 has no API to request resolving a depth-stencil attachment. Therefore, with Vulkan this feature will only be supported with Vulkan 1.2 and up, and on 1.1 implementations with the appropriate extensions present. This feature is provided for the rare case when resolving into a non-multisample depth texture becomes necessary, for example when rendering into an OpenXR-provided depth texture (XR_KHR_composition_layer_depth). This enum value has been introduced in Qt 6.8.

Enumerator
MultisampleTexture 
MultisampleRenderBuffer 
DebugMarkers 
Timestamps 
Instancing 
CustomInstanceStepRate 
PrimitiveRestart 
NonDynamicUniformBuffers 
NonFourAlignedEffectiveIndexBufferOffset 
NPOTTextureRepeat 
RedOrAlpha8IsRed 
ElementIndexUint 
Compute 
WideLines 
VertexShaderPointSize 
BaseVertex 
BaseInstance 
TriangleFanTopology 
ReadBackNonUniformBuffer 
ReadBackNonBaseMipLevel 
TexelFetch 
RenderToNonBaseMipLevel 
IntAttributes 
ScreenSpaceDerivatives 
ReadBackAnyTextureFormat 
PipelineCacheDataLoadSave 
ImageDataStride 
RenderBufferImport 
ThreeDimensionalTextures 
RenderTo3DTextureSlice 
TextureArrays 
Tessellation 
GeometryShader 
TextureArrayRange 
NonFillPolygonMode 
OneDimensionalTextures 
OneDimensionalTextureMipmaps 
HalfAttributes 
RenderToOneDimensionalTexture 
ThreeDimensionalTextureMipmaps 
MultiView 
TextureViewFormat 
ResolveDepthStencil 

Definition at line 1831 of file qrhi.h.

◆ Flag

enum QRhi::Flag

Describes what special features to enable.

\value EnableDebugMarkers Enables debug marker groups. Without this frame debugging features like making debug groups and custom resource name visible in external GPU debugging tools will not be available and functions like QRhiCommandBuffer::debugMarkBegin() will become 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.

\value EnableTimestamps 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.

\value PreferSoftwareRenderer 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.

\value EnablePipelineCacheDataSave 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.

\value SuppressSmokeTestWarnings 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, \l PreferSoftwareRenderer), in order to hide the unconditional warnings from the output that would be printed when the first create() attempt had failed.

Enumerator
EnableDebugMarkers 
PreferSoftwareRenderer 
EnablePipelineCacheDataSave 
EnableTimestamps 
SuppressSmokeTestWarnings 

Definition at line 1815 of file qrhi.h.

◆ FrameOpResult

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

\value FrameOpSuccess Success

\value FrameOpError Unspecified error

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

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

Enumerator
FrameOpSuccess 
FrameOpError 
FrameOpSwapChainOutOfDate 
FrameOpDeviceLost 

Definition at line 1824 of file qrhi.h.

◆ Implementation

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

\value Null \value Vulkan \value OpenGLES2 \value D3D11 \value D3D12 \value Metal

Enumerator
Null 
Vulkan 
OpenGLES2 
D3D11 
Metal 
D3D12 

Definition at line 1806 of file qrhi.h.

◆ ResourceLimit

Describes the resource limit to query.

\value TextureSizeMin Minimum texture width and height. This is typically

  1. The minimum texture size is handled gracefully, meaning attempting to create a texture with an empty size will instead create a texture with the minimum size.

\value TextureSizeMax Maximum texture width and height. This depends on the graphics API and sometimes the platform or implementation as well. Typically the value is in the range 4096 - 16384. Attempting to create textures larger than this is expected to fail.

\value MaxColorAttachments The maximum number of color attachments for a QRhiTextureRenderTarget, in case multiple render targets are supported. When MRT is not supported, the value is 1. Otherwise this is typically 8, but watch out for the fact that OpenGL only mandates 4 as the minimum, and that is what some OpenGL ES implementations provide.

\value FramesInFlight 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.

\value MaxAsyncReadbackFrames The number of \l{QRhi::endFrame()}{submitted} frames (including the one that contains the readback) after which an asynchronous texture or buffer readback is guaranteed to complete upon \l{QRhi::beginFrame()}{starting a new frame}.

\value MaxThreadGroupsPerDimension The maximum number of compute work/thread groups that can be dispatched. Effectively the maximum value for the arguments of QRhiCommandBuffer::dispatch(). Typically 65535.

\value MaxThreadsPerThreadGroup 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.

\value MaxThreadGroupX 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.

\value MaxThreadGroupY 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.

\value MaxThreadGroupZ 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.

\value TextureArraySizeMax Maximum texture array size. Typically in range 256 - 2048. Attempting to \l{QRhi::newTextureArray()}{create a texture array} with more elements will likely fail.

\value MaxUniformBufferRange 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).

\value MaxVertexInputs 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.

\value MaxVertexOutputs 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.

Enumerator
TextureSizeMin 
TextureSizeMax 
MaxColorAttachments 
FramesInFlight 
MaxAsyncReadbackFrames 
MaxThreadGroupsPerDimension 
MaxThreadsPerThreadGroup 
MaxThreadGroupX 
MaxThreadGroupY 
MaxThreadGroupZ 
TextureArraySizeMax 
MaxUniformBufferRange 
MaxVertexInputs 
MaxVertexOutputs 

Definition at line 1886 of file qrhi.h.

Constructor & Destructor Documentation

◆ ~QRhi()

QRhi::~QRhi ( )

Destructor.

Destroys the backend and releases resources.

Definition at line 8431 of file qrhi.cpp.

References QSet< T >::clear(), QRhiImplementation::destroy(), qDeleteAll(), and runCleanup().

+ Here is the call graph for this function:

◆ QRhi()

QRhi::QRhi ( )
protected

Definition at line 8424 of file qrhi.cpp.

Member Function Documentation

◆ addCleanupCallback() [1/2]

void QRhi::addCleanupCallback ( const 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(), ~QRhi()

Definition at line 8809 of file qrhi.cpp.

References QRhiImplementation::addCleanupCallback().

Referenced by QSGGradientCache::cacheForRhi(), QRhiWidgetPrivate::ensureRhi(), and QQuickWidgetPrivate::initializeWithRhi().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ addCleanupCallback() [2/2]

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.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()

Definition at line 8824 of file qrhi.cpp.

References QRhiImplementation::addCleanupCallback().

+ Here is the call graph for this function:

◆ backend()

◆ backendName() [1/2]

const char * QRhi::backendName ( ) const
Returns
the backend type as string for this QRhi.

Definition at line 8683 of file qrhi.cpp.

References backendName().

Referenced by automaticPipelineCacheFileName(), backendName(), QBackingStoreRhiSupport::checkForceRhi(), QRhiWidgetPrivate::ensureRhi(), QOpenXRRuntimeInfo::graphicsApiName(), QOpenGLWidgetPrivate::initialize(), QQuickWidgetPrivate::initializeWithRhi(), QSGRhiSupport::rhiBackendName(), and QQuick3DRenderStats::setRhiContext().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ backendName() [2/2]

const char * QRhi::backendName ( Implementation impl)
static
Returns
a friendly name for the backend impl, usually the name of the 3D API in use.

Definition at line 8660 of file qrhi.cpp.

References D3D11, D3D12, Metal, Null, OpenGLES2, and Vulkan.

◆ beginFrame()

QRhi::FrameOpResult QRhi::beginFrame ( QRhiSwapChain * swapChain,
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:

\list

  • Create a swapchain.
  • Then on every frame: \badcode beginFrame(sc); updates = nextResourceUpdateBatch(); updates->... QRhiCommandBuffer *cb = sc->currentFrameCommandBuffer(); cb->beginPass(sc->currentFrameRenderTarget(), colorClear, dsClear, updates); ... cb->endPass(); ... // more passes as necessary endFrame(sc);

\endlist

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(), isDeviceLost()

Definition at line 10745 of file qrhi.cpp.

References QRhiImplementation::beginFrame(), FrameOpSuccess, QRhiImplementation::inFrame, and qWarning.

Referenced by QSGRenderThread::event(), QBackingStoreDefaultCompositor::flush(), QSGGuiThreadRenderLoop::grab(), and QSGRenderThread::syncAndRender().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ beginOffscreenFrame()

QRhi::FrameOpResult QRhi::beginOffscreenFrame ( QRhiCommandBuffer ** cb,
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:

rhi->beginOffscreenFrame(&cb);
cb->beginPass(rt, colorClear, dsClear);
// ...
u->readBackTexture(rb, &rbResult);
cb->endPass(u);
rhi->endOffscreenFrame();
// image data available in rbResult
\inmodule QtGui
Definition qrhi.h:1651
QRhiResourceUpdateBatch * nextResourceUpdateBatch()
Definition qrhi.cpp:9252
SSL_CTX int(* cb)(SSL *ssl, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
\inmodule QtGui
Definition qrhi.h:1723
See also
endOffscreenFrame(), beginFrame()

Definition at line 10893 of file qrhi.cpp.

References QRhiImplementation::beginOffscreenFrame(), cb, FrameOpSuccess, QRhiImplementation::inFrame, and qWarning.

Referenced by QRhiWidgetPrivate::grabFramebuffer(), QQuickWidgetPrivate::grabFramebuffer(), and QSGRhiSupport::grabOffscreen().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ clipSpaceCorrMatrix()

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 \l{https://matthewwellings.com/blog/the-new-vulkan-coordinate-system/}{this page} for a discussion of the topic from Vulkan perspective.

Definition at line 10091 of file qrhi.cpp.

References QRhiImplementation::clipSpaceCorrMatrix().

Referenced by ExampleRhiWidget::initialize(), ExampleRhiItemRenderer::initialize(), QSSGReflectionMapEntry::renderMips(), DebugDrawPass::renderPrep(), QSSGCustomMaterialSystem::updateUniformsForCustomMaterial(), updateUniformsForDefaultMaterial(), and QSSGParticleRenderer::updateUniformsForParticles().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ create()

QRhi * QRhi::create ( Implementation impl,
QRhiInitParams * params,
Flags flags = {},
QRhiNativeHandles * importDevice = nullptr )
static
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()

Definition at line 8491 of file qrhi.cpp.

References D3D11, D3D12, Metal, Null, OpenGLES2, Q_UNUSED, qWarning, and Vulkan.

Referenced by adjustToPlatformQuirks(), QBackingStoreRhiSupport::create(), QSGRhiSupport::createRhi(), initializeRHI(), QVideoWindowPrivate::initRhi(), AndroidTextureThread::initRhi(), main(), and renderToKTXFileInternal().

+ Here is the caller graph for this function:

◆ currentFrameSlot()

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(), endFrame()

Definition at line 10846 of file qrhi.cpp.

References QRhiImplementation::currentFrameSlot.

Referenced by QSGVideoMaterial::updateTextures().

+ Here is the caller graph for this function:

◆ driverInfo()

QRhiDriverInfo QRhi::driverInfo ( ) const
Returns
metadata for the graphics device used by this successfully initialized QRhi instance.

Definition at line 8784 of file qrhi.cpp.

References QRhiImplementation::driverInfo().

+ Here is the call graph for this function:

◆ endFrame()

QRhi::FrameOpResult QRhi::endFrame ( QRhiSwapChain * swapChain,
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(), isDeviceLost()

Definition at line 10780 of file qrhi.cpp.

References QSet< T >::clear(), QRhiImplementation::endFrame(), FrameOpSuccess, QRhiImplementation::inFrame, qDeleteAll(), and qWarning.

Referenced by QSGRenderThread::event(), QBackingStoreDefaultCompositor::flush(), QSGGuiThreadRenderLoop::grab(), and QSGRenderThread::syncAndRender().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ endOffscreenFrame()

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

Ends, submits, and waits for the offscreen frame.

flags is not currently used.

See also
beginOffscreenFrame()

Definition at line 10912 of file qrhi.cpp.

References QSet< T >::clear(), QRhiImplementation::endOffscreenFrame(), FrameOpSuccess, QRhiImplementation::inFrame, qDeleteAll(), and qWarning.

Referenced by QRhiWidgetPrivate::grabFramebuffer(), QQuickWidgetPrivate::grabFramebuffer(), and QSGRhiSupport::grabOffscreen().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ finish()

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.

Definition at line 10936 of file qrhi.cpp.

References QRhiImplementation::finish().

Referenced by QSGRhiSupport::grabAndBlockInCurrentFrame(), and QSGRhiLayer::toImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isClipDepthZeroToOne()

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.

Definition at line 10069 of file qrhi.cpp.

References QRhiImplementation::isClipDepthZeroToOne().

Referenced by QSSGLayerRenderData::globalRenderProperties(), and RenderHelpers::rhiRenderShadowMap().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isDeviceLost()

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.

Definition at line 10227 of file qrhi.cpp.

References QRhiImplementation::isDeviceLost().

Referenced by QSGRhiSupport::destroyRhi(), QSGRenderThread::handleDeviceLoss(), and QSGRenderThread::syncAndRender().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isFeatureSupported()

bool QRhi::isFeatureSupported ( QRhi::Feature feature) const
Returns
true if the specified feature is supported

Definition at line 10110 of file qrhi.cpp.

References QRhiImplementation::isFeatureSupported().

Referenced by QSGBatchRenderer::Renderer::Renderer(), QSGPlainTexture::commitTextureOperations(), createRhiRenderTargetMultiView(), createRhiRenderTargetWithDepthTexture(), QSGRhiTextureGlyphCache::eightBitFormatIsAlphaSwizzled(), QSGRhiDistanceFieldGlyphCache::eightBitFormatIsAlphaSwizzled(), QRhiWidgetPrivate::ensureTexture(), RenderHelpers::rhiRenderAoTexture(), RenderHelpers::rhiRenderReflectionMap(), QSGRhiDistanceFieldGlyphCache::screenSpaceDerivativesSupported(), QSGDefaultInternalImageNode::supportsWrap(), QQuickRhiItemNode::sync(), and QQuick3DSceneRenderer::synchronize().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isRecordingFrame()

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(), endFrame()

Definition at line 10802 of file qrhi.cpp.

References QRhiImplementation::inFrame.

Referenced by QSGRhiSupport::grabAndBlockInCurrentFrame(), OpaquePass::prep(), TransparentPass::prep(), qImageFromVideoFrame(), QSGRhiAtlasTexture::Texture::removedFromAtlas(), QSSGRenderer::rhiPrepare(), and QSGRenderThread::syncAndRender().

+ Here is the caller graph for this function:

◆ isTextureFormatSupported()

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.

Definition at line 10102 of file qrhi.cpp.

References QRhiImplementation::isTextureFormatSupported().

Referenced by QSSGRenderShadowMap::addShadowMapEntry(), checkParticleSupport(), QSGCompressedTexture::commitTextureOperations(), QSGPlainTexture::commitTextureOperations(), QSGRhiAtlasTexture::Manager::create(), QRhiWidgetPrivate::ensureTexture(), QSSGParticleRenderer::prepareParticlesForModel(), RenderHelpers::rhiPrepareDepthTexture(), QSSGParticleRenderer::rhiPrepareRenderable(), QSGRhiLayer::setFormat(), and QQuickRhiItemNode::sync().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isYUpInFramebuffer()

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.

Definition at line 10030 of file qrhi.cpp.

References QRhiImplementation::isYUpInFramebuffer().

Referenced by QSSGRenderEffect::finalizeShaders(), QBackingStoreDefaultCompositor::flush(), QSSGLayerRenderData::globalRenderProperties(), QSGRhiSupport::grabAndBlockInCurrentFrame(), QRhiWidgetPrivate::grabFramebuffer(), QQuickWidgetPrivate::grabFramebuffer(), QSSGReflectionMapEntry::renderMips(), RenderHelpers::rhiRenderReflectionMap(), RenderHelpers::rhiRenderShadowMap(), and QQuick3DSceneRenderer::synchronize().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isYUpInNDC()

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.

Definition at line 10044 of file qrhi.cpp.

References QRhiImplementation::isYUpInNDC().

Referenced by QBackingStoreDefaultCompositor::flush(), QSSGLayerRenderData::globalRenderProperties(), RenderHelpers::rhiPrepareGrid(), rhiPrepareSkyBox_helper(), and RenderHelpers::rhiRenderShadowMap().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ makeThreadLocalNativeContextCurrent()

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(), QOpenGLContext::isValid()

Definition at line 10158 of file qrhi.cpp.

References QRhiImplementation::makeThreadLocalNativeContextCurrent().

Referenced by QOpenGLCompositorBackingStore::~QOpenGLCompositorBackingStore(), QFFmpeg::VAAPITextureSet::~VAAPITextureSet(), QSGRenderThread::ensureRhi(), QSGGuiThreadRenderLoop::ensureRhi(), QSGRenderThread::event(), QSGGuiThreadRenderLoop::grab(), QSGRenderThread::invalidateGraphics(), QQuickWidgetPrivate::invalidateRenderControl(), QSGRenderLoop::postJob(), QSGRenderThread::sync(), and QSGRenderThread::syncAndRender().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ mipLevelsForSize()

int QRhi::mipLevelsForSize ( const QSize & size)
static
Returns
the number of mip levels for a given size.

Definition at line 10008 of file qrhi.cpp.

References qFloor(), and qMax().

Referenced by QSSGRenderReflectionMap::addReflectionMapEntry(), QSSGBufferManager::registerExtensionResult(), and QSSGReflectionMapEntry::renderMips().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ nativeHandles()

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.

Definition at line 10137 of file qrhi.cpp.

References QRhiImplementation::nativeHandles().

Referenced by AndroidTextureThread::createSurfaceTexture(), findD3D11AdapterID(), QOpenXRGraphicsD3D11::finializeGraphics(), QOpenXRGraphicsD3D12::finializeGraphics(), QOpenXRGraphicsOpenGL::finializeGraphics(), QOpenXRGraphicsOpenGLES::finializeGraphics(), QOpenXRGraphicsVulkan::finializeGraphics(), QT_BEGIN_NAMESPACE::GetD3DDevice(), QOpenGLWidgetPrivate::initialize(), D3D11TextureVideoBuffer::mapTextures(), Q_LOGGING_CATEGORY(), QSGRhiSupport::rifResource(), AVFVideoSinkInterface::setRhi(), QGraphicsFrameCaptureMetal::setRhi(), and QGraphicsFrameCaptureRenderDoc::setRhi().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newBuffer()

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 \l{QRhiBuffer::UsageFlag}{UsageFlags} and \l{QRhi::NonDynamicUniformBuffers}{the feature flags}.
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()

Definition at line 10508 of file qrhi.cpp.

References QRhiImplementation::createBuffer().

Referenced by QSSGRhiBuffer::QSSGRhiBuffer(), TextureCopy::TextureCopy(), QSSGRenderReflectionMap::addReflectionMapEntry(), QSGBatchRenderer::ensureBuffer(), QSSGRhiShaderPipeline::ensureCombinedMainLightsUniformBuffer(), QSSGRhiShaderPipeline::ensureUniformBuffer(), ExampleRhiWidget::initialize(), ExampleRhiItemRenderer::initialize(), QSSGLayerRenderData::prepareInstancing(), qImageFromVideoFrame(), QSSGReflectionMapEntry::renderMips(), DebugDrawPass::renderPrep(), QQuick3DSceneRenderer::renderToRhiTexture(), RenderHelpers::rhiPrepareGrid(), rhiPrepareSkyBox_helper(), RenderHelpers::rhiRenderAoTexture(), and RenderHelpers::rhiRenderShadowMap().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newComputePipeline()

QRhiComputePipeline * QRhi::newComputePipeline ( )
Returns
a new compute pipeline resource.
Note
Compute is only available when the \l{QRhi::Compute}{Compute} feature is reported as supported.
See also
QRhiResource::destroy()

Definition at line 10479 of file qrhi.cpp.

References QRhiImplementation::createComputePipeline().

Referenced by QSSGRhiContextPrivate::computePipeline().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newGraphicsPipeline()

QRhiGraphicsPipeline * QRhi::newGraphicsPipeline ( )
Returns
a new graphics pipeline resource.
See also
QRhiResource::destroy()

Definition at line 10466 of file qrhi.cpp.

References QRhiImplementation::createGraphicsPipeline().

Referenced by QSSGRenderReflectionMap::addReflectionMapEntry(), createGraphicsPipeline(), ExampleRhiWidget::initialize(), ExampleRhiItemRenderer::initialize(), newGraphicsPipeline(), QSSGRhiContextPrivate::pipeline(), and updateTextures().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newRenderBuffer()

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

Definition at line 10535 of file qrhi.cpp.

References QRhiImplementation::createRenderBuffer().

Referenced by allocateRhiReflectionRenderBuffer(), allocateRhiShadowRenderBuffer(), createRhiRenderTarget(), createRhiRenderTargetWithRenderBuffer(), QSGRenderThread::ensureRhi(), QSGGuiThreadRenderLoop::ensureRhi(), QRhiWidgetPrivate::ensureTexture(), QSGRhiSupport::grabOffscreen(), QRhiWidgetPrivate::invokeInitialize(), QQuickRenderTargetPrivate::resolve(), RenderHelpers::rhiPrepareScreenTexture(), QQuickRhiItemNode::sync(), and QQuick3DSceneRenderer::synchronize().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newSampler()

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 \l{QRhiResourceUpdateBatch::uploadTexture()}{texture uploads} or by calling \l{QRhiResourceUpdateBatch::generateMips()}{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()

Definition at line 10665 of file qrhi.cpp.

References QRhiImplementation::createSampler().

Referenced by TextureCopy::TextureCopy(), QSGBatchRenderer::newSampler(), and qImageFromVideoFrame().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newShaderResourceBindings()

QRhiShaderResourceBindings * QRhi::newShaderResourceBindings ( )
Returns
a new shader resource binding collection resource.
See also
QRhiResource::destroy()

Definition at line 10489 of file qrhi.cpp.

References QRhiImplementation::createShaderResourceBindings().

Referenced by TextureCopy::TextureCopy(), QSSGRenderReflectionMap::addReflectionMapEntry(), ExampleRhiWidget::initialize(), ExampleRhiItemRenderer::initialize(), qImageFromVideoFrame(), and QSSGRhiContextPrivate::srb().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newSwapChain()

QRhiSwapChain * QRhi::newSwapChain ( )
Returns
a new swapchain.
See also
QRhiResource::destroy(), QRhiSwapChain::createOrResize()

Definition at line 10693 of file qrhi.cpp.

References QRhiImplementation::createSwapChain().

Referenced by QSGRenderThread::ensureRhi(), QSGGuiThreadRenderLoop::ensureRhi(), and QBackingStoreRhiSupport::swapChainForWindow().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newTexture() [1/2]

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

Definition at line 10562 of file qrhi.cpp.

References QRhiImplementation::createTexture(), QSize::height(), and QRhiTexture::OneDimensional.

Referenced by QAndroidVideoFrameTextures::QAndroidVideoFrameTextures(), QSGCompressedTexture::commitTextureOperations(), QSGPlainTexture::commitTextureOperations(), TextureCopy::copyExternalTexture(), createRhiRenderTarget(), createRhiRenderTargetWithDepthTexture(), QVideoTextureHelper::createTextureFromHandle(), QOpenGLWidgetPrivate::ensureRhiDependentResources(), QRhiWidgetPrivate::ensureTexture(), QSGCompressedAtlasTexture::Atlas::generateTexture(), QSGRhiAtlasTexture::Atlas::generateTexture(), QFFmpeg::MediaCodecTextureConverter::getTextures(), QSGRhiSupport::grabOffscreen(), D3D11TextureVideoBuffer::mapTextures(), QSSGParticleRenderer::prepareParticlesForModel(), qImageFromVideoFrame(), QSGRhiAtlasTexture::Texture::removedFromAtlas(), QOpenXRGraphicsOpenGL::renderTarget(), QOpenXRGraphicsOpenGLES::renderTarget(), QOpenXRGraphicsVulkan::renderTarget(), QQuickRenderTargetPrivate::resolve(), RenderHelpers::rhiPrepareAoTexture(), RenderHelpers::rhiPrepareDepthTexture(), QSSGParticleRenderer::rhiPrepareRenderable(), RenderHelpers::rhiPrepareScreenTexture(), QSGPlainTexture::setTextureFromNativeTexture(), QQuickRhiItemNode::sync(), QQuick3DSceneRenderer::synchronize(), and QVideoTextureHelper::updateTextureWithMap().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newTexture() [2/2]

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.
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 member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 10595 of file qrhi.cpp.

References QRhiImplementation::createTexture(), QRhiTexture::OneDimensional, and QRhiTexture::ThreeDimensional.

+ Here is the call graph for this function:

◆ newTextureArray()

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];}
This is only functional when the TextureArrays feature is reported as supported at run time.
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()

Definition at line 10636 of file qrhi.cpp.

References QRhiImplementation::createTexture(), QSize::height(), QRhiTexture::OneDimensional, and QRhiTexture::TextureArray.

Referenced by createRhiRenderTargetMultiView(), QOpenXRGraphicsOpenGL::renderTarget(), QOpenXRGraphicsOpenGLES::renderTarget(), QOpenXRGraphicsVulkan::renderTarget(), QQuickRenderTargetPrivate::resolve(), RenderHelpers::rhiPrepareAoTexture(), RenderHelpers::rhiPrepareDepthTexture(), and RenderHelpers::rhiPrepareScreenTexture().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ newTextureRenderTarget()

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

Definition at line 10682 of file qrhi.cpp.

References QRhiImplementation::createTextureRenderTarget().

Referenced by QSSGRenderReflectionMap::addReflectionMapEntry(), QSSGRenderShadowMap::addShadowMapEntry(), TextureCopy::copyExternalTexture(), createRhiRenderTarget(), createRhiRenderTargetMultiView(), createRhiRenderTargetWithDepthTexture(), createRhiRenderTargetWithRenderBuffer(), QSGRhiSupport::grabOffscreen(), QRhiWidgetPrivate::invokeInitialize(), qImageFromVideoFrame(), RenderHelpers::rhiPrepareAoTexture(), RenderHelpers::rhiPrepareDepthTexture(), RenderHelpers::rhiPrepareScreenTexture(), QQuickRhiItemNode::sync(), and QQuick3DSceneRenderer::synchronize().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ nextResourceUpdateBatch()

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.
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();
// ... 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();
\inmodule QtGui
Definition qrhi.h:1731
void uploadStaticBuffer(QRhiBuffer *buf, quint32 offset, quint32 size, const void *data)
Enqueues updating a region of a QRhiBuffer buf created with the type QRhiBuffer::Immutable or QRhiBuf...
Definition qrhi.cpp:9011
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
GLenum GLuint GLenum GLsizei const GLchar * buf
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.

Definition at line 9252 of file qrhi.cpp.

References QRhiResourceUpdateBatchPrivate::get(), i, poolSize, qEnvironmentVariableIntValue(), qMax(), qMin(), qWarning, QVarLengthArray< T, Prealloc >::resize(), QVLABaseBase::size(), and QRhiResourceUpdateBatchPrivate::trimOpLists().

Referenced by addOpaqueDepthPrePassBindings(), QBackingStoreDefaultCompositor::flush(), QSGDefaultRenderContext::glyphCacheResourceUpdates(), QSGRhiSupport::grabAndBlockInCurrentFrame(), QRhiWidgetPrivate::grabFramebuffer(), QQuickWidgetPrivate::grabFramebuffer(), ExampleRhiWidget::initialize(), ExampleRhiItemRenderer::initialize(), QSSGBufferManager::loadRenderImage(), QSSGRhiCubeRenderer::prepareCube(), QSSGLayerRenderData::prepareInstancing(), QSSGParticleRenderer::prepareParticlesForModel(), QSSGRhiQuadRenderer::prepareQuad(), QSGBatchRenderer::Renderer::prepareRenderPass(), QSGRhiAtlasTexture::Texture::removedFromAtlas(), ExampleRhiWidget::render(), ExampleRhiItemRenderer::render(), QSSGReflectionMapEntry::renderMips(), DebugDrawPass::renderPrep(), QQuick3DSceneRenderer::renderToRhiTexture(), QSSGCustomMaterialSystem::rhiPrepareRenderable(), QSSGParticleRenderer::rhiPrepareRenderable(), rhiPrepareResourcesForShadowMap(), and QSGRhiLayer::toImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ pipelineCacheData()

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(), isFeatureSupported()

Definition at line 10271 of file qrhi.cpp.

References QRhiImplementation::pipelineCacheData().

+ Here is the call graph for this function:

◆ probe()

bool QRhi::probe ( QRhi::Implementation impl,
QRhiInitParams * params )
static
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()

Definition at line 8577 of file qrhi.cpp.

References create(), Metal, ok, and QRhiMetal::probe().

Referenced by QBackingStoreRhiSupport::create().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ releaseCachedResources()

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.

Definition at line 10175 of file qrhi.cpp.

References QRhiImplementation::releaseCachedResources().

Referenced by QSGBatchRenderer::Renderer::releaseCachedResources().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ removeCleanupCallback()

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

Definition at line 8836 of file qrhi.cpp.

References QRhiImplementation::removeCleanupCallback().

+ Here is the call graph for this function:

◆ resourceLimit()

int QRhi::resourceLimit ( 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.

Definition at line 10121 of file qrhi.cpp.

References QRhiImplementation::resourceLimit().

Referenced by QSGRhiAtlasTexture::Manager::Manager(), QSSGRenderShadowMap::addShadowMapEntry(), QSGPlainTexture::commitTextureOperations(), QRhiWidgetPrivate::ensureTexture(), QSGDefaultRenderContext::initialize(), QSGRhiTextureGlyphCache::maxTextureHeight(), QSGRhiDistanceFieldGlyphCache::maxTextureSize(), QSGRhiTextureGlyphCache::maxTextureWidth(), QQuickRhiItemNode::sync(), and QSGVideoMaterial::updateTextures().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ runCleanup()

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

Definition at line 8849 of file qrhi.cpp.

References QHash< Key, T >::cbegin(), QHash< Key, T >::cend(), QVarLengthArray< T, Prealloc >::clear(), QHash< Key, T >::clear(), and it.

Referenced by ~QRhi().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setPipelineCacheData()

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

Definition at line 10325 of file qrhi.cpp.

References QRhiImplementation::setPipelineCacheData().

+ Here is the call graph for this function:

◆ sizeForMipLevel()

QSize QRhi::sizeForMipLevel ( int mipLevel,
const QSize & baseLevelSize )
static
Returns
the texture image size for a given mipLevel, calculated based on the level 0 size given in baseLevelSize.

Definition at line 10017 of file qrhi.cpp.

References qMax().

+ Here is the call graph for this function:

◆ statistics()

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

Definition at line 10456 of file qrhi.cpp.

References QRhiImplementation::statistics().

+ Here is the call graph for this function:

◆ supportedSampleCounts()

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(), QRhiSwapChain::setSampleCount()

Definition at line 10953 of file qrhi.cpp.

References QRhiImplementation::supportedSampleCounts().

Referenced by QSGRhiSupport::chooseSampleCount(), and QQuick3DSceneRenderer::synchronize().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ thread()

QThread * QRhi::thread ( ) const
Returns
the thread on which the QRhi was \l{QRhi::create()}{initialized}.

Definition at line 8792 of file qrhi.cpp.

Referenced by QSGDefaultRenderContext::compressedTextureForFactory(), QSGDefaultRenderContext::createTexture(), and qImageFromVideoFrame().

+ Here is the caller graph for this function:

◆ ubufAligned()

int QRhi::ubufAligned ( int v) const
Returns
the value (typically an offset) v aligned to the uniform buffer alignment given by by ubufAlignment().

Definition at line 9999 of file qrhi.cpp.

References ubufAlignment().

Referenced by QSSGRenderReflectionMap::addReflectionMapEntry(), QSSGRhiShaderPipeline::addStage(), and QSSGReflectionMapEntry::renderMips().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

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

Definition at line 10968 of file qrhi.cpp.

References QRhiImplementation::ubufAlignment().

Referenced by QSGBatchRenderer::Renderer::Renderer(), and ubufAligned().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ updateSwapChainProxyData()

QRhiSwapChainProxyData QRhi::updateSwapChainProxyData ( QRhi::Implementation impl,
QWindow * window )
static

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.

Definition at line 8636 of file qrhi.cpp.

References Metal, Q_UNUSED, QRhiMetal::updateSwapChainProxyData(), and window().

Referenced by qrhi_objectFromProxyData().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Friends And Related Symbol Documentation

◆ QRhiShaderResourceBindingSet()

Since
6.7

Synonym for QRhiShaderResourceBindings.

Definition at line 1267 of file qrhi.h.

Member Data Documentation

◆ MAX_MIP_LEVELS


The documentation for this class was generated from the following files: