Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qquickrhiitem.cpp
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6#include <QtQuick/private/qsgrhisupport_p.h>
7
9
10/*!
11 \class QQuickRhiItem
12 \inmodule QtQuick
13 \since 6.7
14
15 \brief The QQuickRhiItem class is a portable alternative to
16 QQuickFramebufferObject that is not tied to OpenGL, but rather allows
17 integrating rendering with the QRhi APIs with Qt Quick.
18
19 QQuickRhiItem is effectively the counterpart of \l QRhiWidget in the world of
20 Qt Quick. Both of these are meant to be subclassed, and they both enable
21 recording QRhi-based rendering that targets an offscreen color buffer. The
22 resulting 2D image is then composited with the rest of the Qt Quick scene.
23
24 \note While QQuickRhiItem is a public Qt API, the QRhi family of classes in
25 the Qt Gui module, including QShader and QShaderDescription, offer limited
26 compatibility guarantees. There are no source or binary compatibility
27 guarantees for these classes, meaning the API is only guaranteed to work
28 with the Qt version the application was developed against. Source
29 incompatible changes are however aimed to be kept at a minimum and will
30 only be made in minor releases (6.7, 6.8, and so on). \c{qquickrhiitem.h}
31 does not directly include any QRhi-related headers. To use those classes
32 when implementing a QQuickRhiItem subclass, link to
33 \c{Qt::GuiPrivate} (if using CMake), and include the appropriate headers
34 with the \c rhi prefix, for example \c{#include <rhi/qrhi.h>}.
35
36 QQuickRhiItem is a replacement for the legacy \l QQuickFramebufferObject
37 class. The latter is inherently tied to OpenGL / OpenGL ES, whereas
38 QQuickRhiItem works with the QRhi classes, allowing to run the same
39 rendering code with Vulkan, Metal, Direct 3D 11/12, and OpenGL / OpenGL ES.
40 Conceptually and functionally they are very close, and migrating from
41 QQuickFramebufferObject to QQuickRhiItem is straightforward.
42 QQuickFramebufferObject continues to be available to ensure compatibility
43 for existing application code that works directly with the OpenGL API.
44
45 \note QQuickRhiItem will not be functional when using the \c software
46 adaptation of the Qt Quick scene graph.
47
48 On most platforms, the scene graph rendering, and thus the rendering
49 performed by the QQuickRhiItem will occur on a \l {Scene Graph and
50 Rendering}{dedicated thread}. For this reason, the QQuickRhiItem class
51 enforces a strict separation between the item implementation (the
52 QQuickItem subclass) and the actual rendering logic. All item logic, such
53 as properties and UI-related helper functions exposed to QML must be
54 located in the QQuickRhiItem subclass. Everything that relates to rendering
55 must be located in the QQuickRhiItemRenderer class. To avoid race
56 conditions and read/write issues from two threads it is important that the
57 renderer and the item never read or write shared variables. Communication
58 between the item and the renderer should primarily happen via the
59 QQuickRhiItem::synchronize() function. This function will be called on the
60 render thread while the GUI thread is blocked. Using queued connections or
61 events for communication between item and renderer is also possible.
62
63 Applications must subclass both QQuickRhiItem and QQuickRhiItemRenderer.
64 The pure virtual createRenderer() function must be reimplemented to return
65 a new instance of the QQuickRhiItemRenderer subclass.
66
67 As with QRhiWidget, QQuickRhiItem automatically managed the color buffer,
68 which is a 2D texture (QRhiTexture) normally, or a QRhiRenderBuffer when
69 multisampling is in use. (some 3D APIs differentiate between textures and
70 renderbuffers, while with some others the underlying native resource is the
71 same; renderbuffers are used mainly to allow multisampling with OpenGL ES
72 3.0)
73
74 The size of the texture will by default adapt to the size of the item (with
75 the \l{QQuickWindow::effectiveDevicePixelRatio()}{device pixel ratio} taken
76 into account). If the item size changes, the texture is recreated with the
77 correct size. If a fixed size is preferred, set \l fixedColorBufferWidth and
78 \l fixedColorBufferHeight to non-zero values.
79
80 QQuickRhiItem is a \l{QSGTextureProvider}{texture provider} and can be used
81 directly in \l {ShaderEffect}{ShaderEffects} and other classes that consume
82 texture providers.
83
84 While not a primary use case, QQuickRhiItem also allows incorporating
85 rendering code that directly uses a 3D graphics API such as Vulkan, Metal,
86 Direct 3D, or OpenGL. See \l QRhiCommandBuffer::beginExternal() for details
87 on recording native commands within a QRhi render pass, as well as
88 \l QRhiTexture::createFrom() for a way to wrap an existing native texture and
89 then use it with QRhi in a subsequent render pass. See also
90 \l QQuickGraphicsConfiguration regarding configuring the native 3D API
91 environment (e.g. device extensions) and note that the \l QQuickWindow can be
92 associated with a custom \l QVulkanInstance by calling
93 \l QWindow::setVulkanInstance() early enough.
94
95 \note QQuickRhiItem always uses the same QRhi instance the QQuickWindow
96 uses (and by extension, the same OpenGL context, Vulkan device, etc.). To
97 choose which underlying 3D graphics API is used, call
98 \l{QQuickWindow::setGraphicsApi()}{setGraphicsApi()} on the QQuickWindow
99 early enough. Changing it is not possible once the scene graph has
100 initialized, and all QQuickRhiItem instances in the scene will render using
101 the same 3D API.
102
103 \section1 A simple example
104
105 Take the following subclass of QQuickRhiItem. It is shown here in complete
106 form. It renders a single triangle with a perspective projection, where the
107 triangle is rotated based on the \c angle property of the custom item.
108 (meaning it can be driven for example with animations such as
109 \l NumberAnimation from QML)
110
111 \snippet qquickrhiitem/qquickrhiitem_intro.cpp 0
112
113 It is notable that this simple class is almost exactly the same as the code
114 shown in the \l QRhiWidget introduction. The vertex and fragment shaders are
115 the same as well. These are provided as Vulkan-style GLSL source code and
116 must be processed first by the Qt shader infrastructure first. This is
117 achieved either by running the \c qsb command-line tool manually, or by
118 using the \l qt_add_shaders() function in CMake.
119 The QQuickRhiItem loads these pre-processed \c{.qsb}
120 files that are shipped with the application. See \l{Qt Shader Tools} for
121 more information about Qt's shader translation infrastructure.
122
123 \c{color.vert}
124
125 \snippet qquickrhiitem/qquickrhiitem_intro.vert 0
126
127 \c{color.frag}
128
129 \snippet qquickrhiitem/qquickrhiitem_intro.frag 0
130
131 Once exposed to QML (note the \c QML_NAMED_ELEMENT), our custom item can be
132 instantiated in any scene. (after importing the appropriate \c URI specified
133 for \l qt_add_qml_module() in the CMake project)
134
135 \code
136 ExampleRhiItem {
137 anchors.fill: parent
138 anchors.margins: 10
139 NumberAnimation on angle { from: 0; to: 360; duration: 5000; loops: Animation.Infinite }
140 }
141 \endcode
142
143 See \l{Scene Graph - RHI Texture Item} for a more complex example.
144
145 \sa QQuickRhiItemRenderer, {Scene Graph - RHI Texture Item}, QRhi, {Scene Graph and Rendering}
146 */
147
148/*!
149 \class QQuickRhiItemRenderer
150 \inmodule QtQuick
151 \since 6.7
152
153 \brief A QQuickRhiItemRenderer implements the rendering logic of a
154 QQuickRhiItem.
155
156 \sa QQuickRhiItem, QRhi
157 */
158
160 : m_item(item)
161{
162 m_window = m_item->window();
163 connect(m_window, &QQuickWindow::beforeRendering, this, &QQuickRhiItemNode::render,
164 Qt::DirectConnection);
165 connect(m_window, &QQuickWindow::screenChanged, this, [this]() {
166 if (m_window->effectiveDevicePixelRatio() != m_dpr)
167 m_item->update();
168 }, Qt::DirectConnection);
169}
170
171QSGTexture *QQuickRhiItemNode::texture() const
172{
173 return m_sgTexture.get();
174}
175
177{
178 // owns either m_colorTexture or m_resolveTexture
179 m_sgTexture.reset();
180
181 m_colorTexture = nullptr;
182 m_resolveTexture = nullptr;
183
184 m_msaaColorBuffer.reset();
185}
186
188{
189 m_renderTarget.reset();
190 m_renderPassDescriptor.reset();
191 m_depthStencilBuffer.reset();
192}
193
195{
196 if (!m_rhi) {
197 m_rhi = m_window->rhi();
198 if (!m_rhi) {
199 qWarning("No QRhi found for window %p, QQuickRhiItem will not be functional", m_window);
200 return;
201 }
202 }
203
204 m_dpr = m_window->effectiveDevicePixelRatio();
205 const int minTexSize = m_rhi->resourceLimit(QRhi::TextureSizeMin);
206 const int maxTexSize = m_rhi->resourceLimit(QRhi::TextureSizeMax);
207
208 QQuickRhiItemPrivate *itemD = m_item->d_func();
209 QSize newSize = QSize(itemD->fixedTextureWidth, itemD->fixedTextureHeight);
210 if (newSize.isEmpty())
211 newSize = (QSizeF(m_item->width(), m_item->height()) * m_dpr).toSize();
212
213 newSize.setWidth(qMin(maxTexSize, qMax(minTexSize, newSize.width())));
214 newSize.setHeight(qMin(maxTexSize, qMax(minTexSize, newSize.height())));
215
216 if (m_colorTexture) {
217 if (m_colorTexture->format() != itemD->rhiTextureFormat
218 || m_colorTexture->sampleCount() != itemD->samples)
219 {
222 }
223 }
224
225 if (m_msaaColorBuffer) {
226 if (m_msaaColorBuffer->backingFormat() != itemD->rhiTextureFormat
227 || m_msaaColorBuffer->sampleCount() != itemD->samples)
228 {
231 }
232 }
233
234 if (m_sgTexture && m_sgTexture->hasAlphaChannel() != itemD->blend) {
237 }
238
239 if (!m_colorTexture && itemD->samples <= 1) {
240 if (!m_rhi->isTextureFormatSupported(itemD->rhiTextureFormat)) {
241 qWarning("QQuickRhiItem: The requested texture format (%d) is not supported by the "
242 "underlying 3D graphics API implementation", int(itemD->rhiTextureFormat));
243 }
244 m_colorTexture = m_rhi->newTexture(itemD->rhiTextureFormat, newSize, itemD->samples,
245 QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource);
246 if (!m_colorTexture->create()) {
247 qWarning("Failed to create backing texture for QQuickRhiItem");
248 delete m_colorTexture;
249 m_colorTexture = nullptr;
250 return;
251 }
252 }
253
254 if (itemD->samples > 1) {
255 if (!m_msaaColorBuffer) {
256 if (!m_rhi->isFeatureSupported(QRhi::MultisampleRenderBuffer)) {
257 qWarning("QQuickRhiItem: Multisample renderbuffers are reported as unsupported; "
258 "sample count %d will not work as expected", itemD->samples);
259 }
260 if (!m_rhi->isTextureFormatSupported(itemD->rhiTextureFormat)) {
261 qWarning("QQuickRhiItem: The requested texture format (%d) is not supported by the "
262 "underlying 3D graphics API implementation", int(itemD->rhiTextureFormat));
263 }
264 m_msaaColorBuffer.reset(m_rhi->newRenderBuffer(QRhiRenderBuffer::Color, newSize, itemD->samples,
265 {}, itemD->rhiTextureFormat));
266 if (!m_msaaColorBuffer->create()) {
267 qWarning("Failed to create multisample color buffer for QQuickRhiItem");
268 m_msaaColorBuffer.reset();
269 return;
270 }
271 }
272 if (!m_resolveTexture) {
273 m_resolveTexture = m_rhi->newTexture(itemD->rhiTextureFormat, newSize, 1,
274 QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource);
275 if (!m_resolveTexture->create()) {
276 qWarning("Failed to create resolve texture for QQuickRhiItem");
277 delete m_resolveTexture;
278 m_resolveTexture = nullptr;
279 return;
280 }
281 }
282 } else if (m_resolveTexture) {
283 m_resolveTexture->deleteLater();
284 m_resolveTexture = nullptr;
285 }
286
287 if (m_colorTexture && m_colorTexture->pixelSize() != newSize) {
288 m_colorTexture->setPixelSize(newSize);
289 if (!m_colorTexture->create())
290 qWarning("Failed to rebuild texture for QQuickRhiItem after resizing");
291 }
292
293 if (m_msaaColorBuffer && m_msaaColorBuffer->pixelSize() != newSize) {
294 m_msaaColorBuffer->setPixelSize(newSize);
295 if (!m_msaaColorBuffer->create())
296 qWarning("Failed to rebuild multisample color buffer for QQuickRhiitem after resizing");
297 }
298
299 if (m_resolveTexture && m_resolveTexture->pixelSize() != newSize) {
300 m_resolveTexture->setPixelSize(newSize);
301 if (!m_resolveTexture->create())
302 qWarning("Failed to rebuild resolve texture for QQuickRhiItem after resizing");
303 }
304
305 if (!m_sgTexture) {
306 QQuickWindow::CreateTextureOptions options;
307 if (itemD->blend)
308 options |= QQuickWindow::TextureHasAlphaChannel;
309 // the QSGTexture takes ownership of the QRhiTexture
310 m_sgTexture.reset(m_window->createTextureFromRhiTexture(m_colorTexture ? m_colorTexture : m_resolveTexture,
311 options));
312 setTexture(m_sgTexture.get());
313 }
314
315 if (itemD->autoRenderTarget) {
316 const QSize pixelSize = m_colorTexture ? m_colorTexture->pixelSize()
317 : m_msaaColorBuffer->pixelSize();
318 if (!m_depthStencilBuffer) {
319 m_depthStencilBuffer.reset(m_rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, pixelSize, itemD->samples,
320 QSGRhiSupport::depthStencilBufferFlags()));
321 if (!m_depthStencilBuffer->create()) {
322 qWarning("Failed to create depth-stencil buffer for QQuickRhiItem");
324 return;
325 }
326 } else if (m_depthStencilBuffer->pixelSize() != pixelSize) {
327 m_depthStencilBuffer->setPixelSize(pixelSize);
328 if (!m_depthStencilBuffer->create()) {
329 qWarning("Failed to rebuild depth-stencil buffer for QQuickRhiItem with new size");
330 return;
331 }
332 }
333 if (!m_renderTarget) {
334 QRhiColorAttachment color0;
335 if (m_colorTexture)
336 color0.setTexture(m_colorTexture);
337 else
338 color0.setRenderBuffer(m_msaaColorBuffer.get());
339 if (itemD->samples > 1)
340 color0.setResolveTexture(m_resolveTexture);
341 QRhiTextureRenderTargetDescription rtDesc(color0, m_depthStencilBuffer.get());
342 m_renderTarget.reset(m_rhi->newTextureRenderTarget(rtDesc));
343 m_renderPassDescriptor.reset(m_renderTarget->newCompatibleRenderPassDescriptor());
344 m_renderTarget->setRenderPassDescriptor(m_renderPassDescriptor.get());
345 if (!m_renderTarget->create()) {
346 qWarning("Failed to create render target for QQuickRhiitem");
348 return;
349 }
350 }
351 } else {
353 }
354
355 if (newSize != itemD->effectiveTextureSize) {
356 itemD->effectiveTextureSize = newSize;
357 emit m_item->effectiveColorBufferSizeChanged();
358 }
359
360 QRhiCommandBuffer *cb = queryCommandBuffer();
361 if (cb)
362 m_renderer->initialize(cb);
363
364 m_renderer->synchronize(m_item);
365}
366
368{
369 QRhiSwapChain *swapchain = m_window->swapChain();
370 QSGRendererInterface *rif = m_window->rendererInterface();
371
372 // Handle both cases: on-screen QQuickWindow vs. off-screen QQuickWindow
373 // e.g. by using QQuickRenderControl to redirect into a texture.
374 QRhiCommandBuffer *cb = swapchain ? swapchain->currentFrameCommandBuffer()
375 : static_cast<QRhiCommandBuffer *>(
376 rif->getResource(m_window, QSGRendererInterface::RhiRedirectCommandBuffer));
377
378 if (!cb) {
379 qWarning("QQuickRhiItem: Neither swapchain nor redirected command buffer are available.");
380 return nullptr;
381 }
382
383 return cb;
384}
385
386void QQuickRhiItemNode::render()
387{
388 // called before Qt Quick starts recording its main render pass
389
390 if (!isValid() || !m_renderPending)
391 return;
392
393 QRhiCommandBuffer *cb = queryCommandBuffer();
394 if (!cb)
395 return;
396
397 m_renderPending = false;
398 m_renderer->render(cb);
399
400 markDirty(QSGNode::DirtyMaterial);
401 emit textureChanged();
402}
403
404/*!
405 Constructs a new QQuickRhiItem with the given \a parent.
406 */
407QQuickRhiItem::QQuickRhiItem(QQuickItem *parent)
408 : QQuickItem(*new QQuickRhiItemPrivate, parent)
409{
410 setFlag(ItemHasContents);
411}
412
413/*!
414 * \internal
415 */
416QQuickRhiItem::QQuickRhiItem(QQuickRhiItemPrivate &dd, QQuickItem *parent)
417 : QQuickItem(dd, parent)
418{
419 setFlag(ItemHasContents);
420}
421
422/*!
423 Destructor.
424*/
425QQuickRhiItem::~QQuickRhiItem()
426{
427}
428
429/*!
430 \internal
431 */
432QSGNode *QQuickRhiItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
433{
434 // Changing to an empty size should not involve destroying and then later
435 // recreating the node, because we do not know how expensive the user's
436 // renderer setup is. Rather, keep the node if it already exist, and clamp
437 // all accesses to width and height. Hence the unusual !oldNode condition here.
438 if (!oldNode && (width() <= 0 || height() <= 0))
439 return nullptr;
440
441 Q_D(QQuickRhiItem);
442 QQuickRhiItemNode *n = static_cast<QQuickRhiItemNode *>(oldNode);
443 if (!n) {
444 if (!d->node)
445 d->node = new QQuickRhiItemNode(this);
446 if (!d->node->hasRenderer()) {
447 QQuickRhiItemRenderer *r = createRenderer();
448 if (r) {
449 r->node = d->node;
450 d->node->setRenderer(r);
451 } else {
452 qWarning("No QQuickRhiItemRenderer was created; the item will not render");
453 delete d->node;
454 d->node = nullptr;
455 return nullptr;
456 }
457 }
458 n = d->node;
459 }
460
461 n->sync();
462
463 if (!n->isValid()) {
464 delete n;
465 d->node = nullptr;
466 return nullptr;
467 }
468
469 if (window()->rhi()->isYUpInFramebuffer()) {
470 n->setTextureCoordinatesTransform(d->mirrorVertically
471 ? QSGSimpleTextureNode::NoTransform
472 : QSGSimpleTextureNode::MirrorVertically);
473 } else {
474 n->setTextureCoordinatesTransform(d->mirrorVertically
475 ? QSGSimpleTextureNode::MirrorVertically
476 : QSGSimpleTextureNode::NoTransform);
477 }
478 n->setFiltering(d->smooth ? QSGTexture::Linear : QSGTexture::Nearest);
479 n->setRect(0, 0, qMax(qreal(0), width()), qMax(qreal(0), height()));
480
481 n->scheduleUpdate();
482
483 return n;
484}
485
486/*!
487 \reimp
488 */
489bool QQuickRhiItem::event(QEvent *e)
490{
491 return QQuickItem::event(e);
492}
493
494/*!
495 \reimp
496 */
497void QQuickRhiItem::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
498{
499 QQuickItem::geometryChange(newGeometry, oldGeometry);
500 if (newGeometry.size() != oldGeometry.size())
501 update();
502}
503
504/*!
505 \reimp
506 */
507void QQuickRhiItem::releaseResources()
508{
509 // called on the gui thread if the item is removed from scene
510
511 Q_D(QQuickRhiItem);
512 d->node = nullptr;
513}
514
515void QQuickRhiItem::invalidateSceneGraph()
516{
517 // called on the render thread when the scenegraph is invalidated
518
519 Q_D(QQuickRhiItem);
520 d->node = nullptr;
521}
522
523/*!
524 \reimp
525 */
526bool QQuickRhiItem::isTextureProvider() const
527{
528 return true;
529}
530
531/*!
532 \reimp
533 */
534QSGTextureProvider *QQuickRhiItem::textureProvider() const
535{
536 if (QQuickItem::isTextureProvider()) // e.g. if Item::layer::enabled == true
537 return QQuickItem::textureProvider();
538
539 Q_D(const QQuickRhiItem);
540 if (!d->node) // create a node to have a provider, the texture will be null but that's ok
541 d->node = new QQuickRhiItemNode(const_cast<QQuickRhiItem *>(this));
542
543 return d->node;
544}
545
546/*!
547 \property QQuickRhiItem::sampleCount
548
549 This property controls for sample count for multisample antialiasing.
550 By default the value is \c 1 which means MSAA is disabled.
551
552 Valid values are 1, 4, 8, and sometimes 16 and 32.
553 \l QRhi::supportedSampleCounts() can be used to query the supported sample
554 counts at run time, but typically applications should request 1 (no MSAA),
555 4x (normal MSAA) or 8x (high MSAA).
556
557 \note Setting a new value implies that all QRhiGraphicsPipeline objects
558 created by the renderer must use the same sample count from then on.
559 Existing QRhiGraphicsPipeline objects created with a different sample count
560 must not be used anymore. When the value changes, all color and
561 depth-stencil buffers are destroyed and recreated automatically, and
562 \l {QQuickRhiItemRenderer::}{initialize()} is invoked again. However, when
563 isAutoRenderTargetEnabled() is \c false, it will be up to the application to
564 manage this with regards to the depth-stencil buffer or additional color
565 buffers.
566
567 Changing the sample count from the default 1 to a higher value implies that
568 \l {QQuickRhiItemRenderer::}{colorTexture()} becomes \nullptr and
569 \l {QQuickRhiItemRenderer::}{msaaColorBuffer()} starts returning a
570 valid object. Switching back to 1 (or 0), implies the opposite: in the next
571 call to initialize() msaaColorBuffer() is going to return \nullptr, whereas
572 colorTexture() becomes once again valid. In addition,
573 \l {QQuickRhiItemRenderer::}{resolveTexture()}
574 returns a valid (non-multisample) QRhiTexture whenever the sample count is
575 greater than 1 (i.e., MSAA is in use).
576
577 \sa QQuickRhiItemRenderer::msaaColorBuffer(),
578 QQuickRhiItemRenderer::resolveTexture()
579 */
580
581int QQuickRhiItem::sampleCount() const
582{
583 Q_D(const QQuickRhiItem);
584 return d->samples;
585}
586
587void QQuickRhiItem::setSampleCount(int samples)
588{
589 Q_D(QQuickRhiItem);
590 if (d->samples == samples)
591 return;
592
593 d->samples = samples;
594 emit sampleCountChanged();
595 update();
596}
597
598/*!
599 \enum QQuickRhiItem::TextureFormat
600 Specifies the format of the backing texture to which the QQuickRhiItem renders.
601
602 \value RGBA8 See QRhiTexture::RGBA8. This is the default.
603 \value RGBA16F See QRhiTexture::RGBA16F.
604 \value RGBA32F See QRhiTexture::RGBA32F.
605 \value RGB10A2 See QRhiTexture::RGB10A2.
606
607 \sa QRhiTexture
608 */
609
610/*!
611 \property QQuickRhiItem::colorBufferFormat
612
613 This property controls the texture format for the texture used as the color
614 buffer. The default value is TextureFormat::RGBA8. QQuickRhiItem supports
615 rendering to a subset of the formats supported by \l QRhiTexture. Only
616 formats that are reported as supported from
617 \l QRhi::isTextureFormatSupported() should be specified, rendering will not be
618 functional otherwise.
619
620 \note Setting a new format when the item and its renderer are already
621 initialized and have rendered implies that all QRhiGraphicsPipeline objects
622 created by the renderer may become unusable, if the associated
623 QRhiRenderPassDescriptor is now incompatible due to the different texture
624 format. Similarly to changing
625 \l sampleCount dynamically, this means that initialize() or render()
626 implementations must then take care of releasing the existing pipelines and
627 creating new ones.
628 */
629
630QQuickRhiItem::TextureFormat QQuickRhiItem::colorBufferFormat() const
631{
632 Q_D(const QQuickRhiItem);
633 return d->itemTextureFormat;
634}
635
636void QQuickRhiItem::setColorBufferFormat(TextureFormat format)
637{
638 Q_D(QQuickRhiItem);
639 if (d->itemTextureFormat == format)
640 return;
641
642 d->itemTextureFormat = format;
643 switch (format) {
644 case TextureFormat::RGBA8:
645 d->rhiTextureFormat = QRhiTexture::RGBA8;
646 break;
647 case TextureFormat::RGBA16F:
648 d->rhiTextureFormat = QRhiTexture::RGBA16F;
649 break;
650 case TextureFormat::RGBA32F:
651 d->rhiTextureFormat = QRhiTexture::RGBA32F;
652 break;
653 case TextureFormat::RGB10A2:
654 d->rhiTextureFormat = QRhiTexture::RGB10A2;
655 break;
656 }
657 emit colorBufferFormatChanged();
658 update();
659}
660
661/*!
662 \return the current automatic depth-stencil buffer and render target management setting.
663
664 By default this value is \c true.
665
666 \sa setAutoRenderTarget()
667 */
668bool QQuickRhiItem::isAutoRenderTargetEnabled() const
669{
670 Q_D(const QQuickRhiItem);
671 return d->autoRenderTarget;
672}
673
674/*!
675 Controls if a depth-stencil QRhiRenderBuffer and a QRhiTextureRenderTarget
676 is created and maintained automatically by the item. The default value is
677 \c true. Call this function early on, for example from the derived class'
678 constructor, with \a enabled set to \c false to disable this.
679
680 In automatic mode, the size and sample count of the depth-stencil buffer
681 follows the color buffer texture's settings. In non-automatic mode,
682 renderTarget() and depthStencilBuffer() always return \nullptr and it is
683 then up to the application's implementation of initialize() to take care of
684 setting up and managing these objects.
685 */
686void QQuickRhiItem::setAutoRenderTarget(bool enabled)
687{
688 Q_D(QQuickRhiItem);
689 if (d->autoRenderTarget == enabled)
690 return;
691
692 d->autoRenderTarget = enabled;
693 emit autoRenderTargetChanged();
694 update();
695}
696
697/*!
698 \property QQuickRhiItem::mirrorVertically
699
700 This property controls if texture UVs are flipped when drawing the textured
701 quad. It has no effect on the contents of the offscreen color buffer and
702 the rendering implemented by the QQuickRhiItemRenderer.
703
704 The default value is \c false.
705 */
706
707bool QQuickRhiItem::isMirrorVerticallyEnabled() const
708{
709 Q_D(const QQuickRhiItem);
710 return d->mirrorVertically;
711}
712
713void QQuickRhiItem::setMirrorVertically(bool enable)
714{
715 Q_D(QQuickRhiItem);
716 if (d->mirrorVertically == enable)
717 return;
718
719 d->mirrorVertically = enable;
720 emit mirrorVerticallyChanged();
721 update();
722}
723
724/*!
725 \property QQuickRhiItem::fixedColorBufferWidth
726
727 The fixed width, in pixels, of the item's associated texture or
728 renderbuffer. Relevant when a fixed color buffer size is desired that does
729 not depend on the item's size. This size has no effect on the geometry of
730 the item (its size and placement within the scene), which means the
731 texture's content will appear stretched (scaled up) or scaled down onto the
732 item's area.
733
734 For example, setting a size that is exactly twice the item's (pixel) size
735 effectively performs 2x supersampling (rendering at twice the resolution and
736 then implicitly scaling down when texturing the quad corresponding to the
737 item in the scene). On the other hand, setting a size that is half of the
738 item's pixel size effectively achieves rendering at half resolution and then
739 upscaling the results.
740
741 By default the value is \c 0. A value of 0 means that texture's size
742 follows the item's size. (\c{texture size} = \c{item size} * \c{device
743 pixel ratio}).
744
745 \note The device pixel ratio (the system compositor's scale factor) can have
746 a big impact on performance, since a scale factor of 2 (200%) means
747 rendering at twice the resolution, so twice of what the developer and UI
748 designer perceives as the item's size, and then effectively downscaling the
749 content, similarly to what happens when setting this property to twice the
750 item's pixel size on a system where the device pixel ratio is 1. Therefore,
751 this property is expected to be rarely used with sizes bigger than the
752 item's pixel size, since many modern desktop systems have neither the need
753 nor have the performance budget for it, when a larger than 1 device pixel
754 ratio is used anyway by the system. Instead, the main use case for this
755 property is to set a smaller size, in order to render at a reasonable
756 smaller resolution instead of blindly following the item (and perhaps
757 window) geometry, however big that may be.
758 */
759int QQuickRhiItem::fixedColorBufferWidth() const
760{
761 Q_D(const QQuickRhiItem);
762 return d->fixedTextureWidth;
763}
764
765void QQuickRhiItem::setFixedColorBufferWidth(int width)
766{
767 Q_D(QQuickRhiItem);
768 if (d->fixedTextureWidth == width)
769 return;
770
771 d->fixedTextureWidth = width;
772 emit fixedColorBufferWidthChanged();
773 update();
774}
775
776/*!
777 \property QQuickRhiItem::fixedColorBufferHeight
778
779 The fixed height, in pixels, of the item's associated texture. Relevant when
780 a fixed texture size is desired that does not depend on the item's size.
781 This size has no effect on the geometry of the item (its size and placement
782 within the scene), which means the texture's content will appear stretched
783 (scaled up) or scaled down onto the item's area.
784
785 By default the value is \c 0. A value of 0 means that texture's size
786 follows the item's size. (\c{texture size} = \c{item size} * \c{device
787 pixel ratio}).
788
789 See \l fixedColorBufferWidth for more information on the use cases for
790 setting a fixed width and height.
791 */
792
793int QQuickRhiItem::fixedColorBufferHeight() const
794{
795 Q_D(const QQuickRhiItem);
796 return d->fixedTextureHeight;
797}
798
799void QQuickRhiItem::setFixedColorBufferHeight(int height)
800{
801 Q_D(QQuickRhiItem);
802 if (d->fixedTextureHeight == height)
803 return;
804
805 d->fixedTextureHeight = height;
806 emit fixedColorBufferHeightChanged();
807 update();
808}
809
810/*!
811 \property QQuickRhiItem::effectiveColorBufferSize
812
813 This property exposes the size, in pixels, of the underlying color buffer
814 (the QRhiTexture or QRhiRenderBuffer). It is provided for use on the GUI
815 (main) thread, in QML bindings or JavaScript.
816
817 \note QQuickRhiItemRenderer implementations, operating on the scene graph
818 render thread, should not use this property. Those should rather query the
819 size from the
820 \l{QQuickRhiItemRenderer::renderTarget()}{render target}.
821
822 \note The value becomes available asynchronously from the main thread's
823 perspective in the sense that the value changes when rendering happens on
824 the render thread. This means that this property is useful mainly in QML
825 bindings. Application code must not assume that the value is up to date
826 already when the QQuickRhiItem object is constructed.
827
828 This is a read-only property.
829 */
830
831QSize QQuickRhiItem::effectiveColorBufferSize() const
832{
833 Q_D(const QQuickRhiItem);
834 return d->effectiveTextureSize;
835}
836
837/*!
838 \property QQuickRhiItem::alphaBlending
839
840 Controls if blending is always enabled when drawing the quad textured with
841 the content generated by the QQuickRhiItem and its renderer.
842
843 The default value is \c false. This is for performance reasons: if
844 semi-transparency is not involved, because the QQuickRhiItemRenderer clears
845 to an opaque color and never renders fragments with alpha smaller than 1,
846 then there is no point in enabling blending.
847
848 If the QQuickRhiItemRenderer subclass renders with semi-transparency involved,
849 set this property to true.
850
851 \note Under certain conditions blending is still going to happen regardless
852 of the value of this property. For example, if the item's
853 \l{QQuickItem::opacity}{opacity} (more precisely, the combined opacity
854 inherited from the parent chain) is smaller than 1, blending will be
855 automatically enabled even when this property is set to false.
856
857 \note The Qt Quick scene graph relies on and expect pre-multiplied alpha.
858 For example, if the intention is to clear the background in the renderer to
859 an alpha value of 0.5, then make sure to multiply the red, green, and blue
860 clear color values with 0.5 as well. Otherwise the blending results will be
861 incorrect.
862 */
863
864bool QQuickRhiItem::alphaBlending() const
865{
866 Q_D(const QQuickRhiItem);
867 return d->blend;
868}
869
870void QQuickRhiItem::setAlphaBlending(bool enable)
871{
872 Q_D(QQuickRhiItem);
873 if (d->blend == enable)
874 return;
875
876 d->blend = enable;
877 emit alphaBlendingChanged();
878 update();
879}
880
881/*!
882 Constructs a new renderer.
883
884 This function is called on the rendering thread during the scene graph sync
885 phase when the GUI thread is blocked.
886
887 \sa QQuickRhiItem::createRenderer()
888 */
889QQuickRhiItemRenderer::QQuickRhiItemRenderer()
890{
891}
892
893/*!
894 The Renderer is automatically deleted when the scene graph resources for
895 the QQuickRhiItem item are cleaned up.
896
897 This function is called on the rendering thread.
898
899 Under certain conditions it is normal and expected that the renderer object
900 is destroyed and then recreated. This is because the renderer's lifetime
901 effectively follows the underlying scene graph node. For example, when
902 changing the parent of a QQuickRhiItem object so that it then belongs to a
903 different \l QQuickWindow, the scene graph nodes are all dropped and
904 recreated due to the window change. This will also involve dropping and
905 creating a new QQuickRhiItemRenderer.
906
907 Unlike \l QRhiWidget, QQuickRhiItemRenderer has no need to implement
908 additional code paths for releasing (or early-relasing) graphics resources
909 created via QRhi. It is sufficient to release everything in the destructor,
910 or rely on smart pointers.
911 */
912QQuickRhiItemRenderer::~QQuickRhiItemRenderer()
913{
914}
915
916/*!
917 Call this function when the content of the offscreen color buffer should be
918 updated. (i.e. to request that render() is called again; the call will
919 happen at a later point, and note that updates are typically throttled to
920 the presentation rate)
921
922 This function can be called from render() to schedule an update.
923
924 \note This function should be used from inside the renderer. To update
925 the item on the GUI thread, use QQuickRhiItem::update().
926 */
927void QQuickRhiItemRenderer::update()
928{
929 if (node)
930 node->scheduleUpdate();
931}
932
933/*!
934 \return the current QRhi object.
935
936 Must only be called from initialize() and render().
937 */
938QRhi *QQuickRhiItemRenderer::rhi() const
939{
940 return node ? node->m_rhi : nullptr;
941}
942
943/*!
944 \return the texture serving as the color buffer for the item.
945
946 Must only be called from initialize() and render().
947
948 Unlike the depth-stencil buffer and the QRhiRenderTarget, this texture is
949 always available and is managed by the QQuickRhiItem, independent of the
950 value of \l {QQuickRhiItem::}{isAutoRenderTargetEnabled}.
951
952 \note When \l {QQuickRhiItem::}{sampleCount} is larger than 1, and so
953 multisample antialiasing is enabled, the return value is \nullptr. Instead,
954 query the \l QRhiRenderBuffer by calling msaaColorBuffer().
955
956 \note The backing texture size and sample count can also be queried via the
957 QRhiRenderTarget returned from renderTarget(). This can be more convenient
958 and compact than querying from the QRhiTexture or QRhiRenderBuffer, because
959 it works regardless of multisampling is in use or not.
960
961 \sa msaaColorBuffer(), depthStencilBuffer(), renderTarget(), resolveTexture()
962 */
963QRhiTexture *QQuickRhiItemRenderer::colorTexture() const
964{
965 return node ? node->m_colorTexture : nullptr;
966}
967
968/*!
969 \return the renderbuffer serving as the multisample color buffer for the item.
970
971 Must only be called from initialize() and render().
972
973 When \l {QQuickRhiItem::}{sampleCount} is larger than 1, and so multisample
974 antialising is enabled, the returned QRhiRenderBuffer has a matching sample
975 count and serves as the color buffer. Graphics pipelines used to render
976 into this buffer must be created with the same sample count, and the
977 depth-stencil buffer's sample count must match as well. The multisample
978 content is expected to be resolved into the texture returned from
979 resolveTexture(). When \l {QQuickRhiItem::}{isAutoRenderTargetEnabled} is
980 \c true, renderTarget() is set up automatically to do this, by setting up
981 msaaColorBuffer() as the
982 \l{QRhiColorAttachment::renderBuffer()}{renderbuffer} of color attachment 0
983 and resolveTexture() as its
984 \l{QRhiColorAttachment::resolveTexture()}{resolveTexture}.
985
986 When MSAA is not in use, the return value is \nullptr. Use colorTexture()
987 instead then.
988
989 Depending on the underlying 3D graphics API, there may be no practical
990 difference between multisample textures and color renderbuffers with a
991 sample count larger than 1 (QRhi may just map both to the same native
992 resource type). Some older APIs however may differentiate between textures
993 and renderbuffers. In order to support OpenGL ES 3.0, where multisample
994 renderbuffers are available, but multisample textures are not, QQuickRhiItem
995 always performs MSAA by using a multisample QRhiRenderBuffer as the color
996 attachment (and never a multisample QRhiTexture).
997
998 \note The backing texture size and sample count can also be queried via the
999 QRhiRenderTarget returned from renderTarget(). This can be more convenient
1000 and compact than querying from the QRhiTexture or QRhiRenderBuffer, because
1001 it works regardless of multisampling is in use or not.
1002
1003 \sa colorTexture(), depthStencilBuffer(), renderTarget(), resolveTexture()
1004 */
1005QRhiRenderBuffer *QQuickRhiItemRenderer::msaaColorBuffer() const
1006{
1007 return node ? node->m_msaaColorBuffer.get() : nullptr;
1008}
1009
1010/*!
1011 \return the non-multisample texture to which the multisample content is resolved.
1012
1013 The result is \nullptr when multisample antialiasing is not enabled.
1014
1015 Must only be called from initialize() and render().
1016
1017 With MSAA enabled, this is the texture that gets used by the item's
1018 underlying scene graph node when texturing a quad in the main render pass
1019 of Qt Quick. However, the QQuickRhiItemRenderer's rendering must target the
1020 (multisample) QRhiRenderBuffer returned from msaaColorBuffer(). When \l
1021 {QQuickRhiItem::}{isAutoRenderTargetEnabled} is \c true, this is taken care
1022 of by the QRhiRenderTarget returned from renderTarget(). Otherwise, it is
1023 up to the subclass code to correctly configure a render target object with
1024 both the color buffer and resolve textures.
1025
1026 \sa colorTexture()
1027 */
1028QRhiTexture *QQuickRhiItemRenderer::resolveTexture() const
1029{
1030 return node ? node->m_resolveTexture : nullptr;
1031}
1032
1033/*!
1034 \return the depth-stencil buffer used by the item's rendering.
1035
1036 Must only be called from initialize() and render().
1037
1038 Available only when \l {QQuickRhiItem::}{isAutoRenderTargetEnabled} is \c
1039 true. Otherwise the returned value is \nullptr and it is up the
1040 reimplementation of initialize() to create and manage a depth-stencil
1041 buffer and a QRhiTextureRenderTarget.
1042
1043 \sa colorTexture(), renderTarget()
1044 */
1045QRhiRenderBuffer *QQuickRhiItemRenderer::depthStencilBuffer() const
1046{
1047 return node ? node->m_depthStencilBuffer.get() : nullptr;
1048}
1049
1050/*!
1051 \return the render target object that must be used with
1052 \l QRhiCommandBuffer::beginPass() in reimplementations of render().
1053
1054 Must only be called from initialize() and render().
1055
1056 Available only when \l {QQuickRhiItem::}{isAutoRenderTargetEnabled} is \c
1057 true. Otherwise the returned value is \nullptr and it is up the
1058 reimplementation of initialize() to create and manage a depth-stencil
1059 buffer and a QRhiTextureRenderTarget.
1060
1061 When creating \l{QRhiGraphicsPipeline}{graphics pipelines}, a
1062 QRhiRenderPassDescriptor is needed. This can be queried from the returned
1063 QRhiTextureRenderTarget by calling
1064 \l{QRhiTextureRenderTarget::renderPassDescriptor()}{renderPassDescriptor()}.
1065
1066 \note The returned QRhiTextureRenderTarget always reports a
1067 \l{QRhiTextureRenderTarget::}{devicePixelRatio()} of \c 1.
1068 This is because only swapchains and the associated window have a concept of
1069 device pixel ratio, not textures, and the render target here always refers
1070 to a texture. If the on-screen scale factor is relevant for rendering,
1071 query and store it via the item's
1072 \c{window()->effectiveDevicePixelRatio()} in \l synchronize().
1073 When doing so, always prefer using \l{QQuickWindow::}{effectiveDevicePixelRatio()}
1074 over the base class' \l{QWindow::}{devicePixelRatio()}.
1075
1076 \sa colorTexture(), depthStencilBuffer(), QQuickWindow::effectiveDevicePixelRatio()
1077 */
1078QRhiRenderTarget *QQuickRhiItemRenderer::renderTarget() const
1079{
1080 return node ? node->m_renderTarget.get() : nullptr;
1081}
1082
1083/*!
1084 \fn QQuickRhiItemRenderer *QQuickRhiItem::createRenderer()
1085
1086 Reimplement this function to create and return a new instance of a
1087 QQuickRhiItemRenderer subclass.
1088
1089 This function will be called on the rendering thread while the GUI thread
1090 is blocked.
1091 */
1092
1093/*!
1094 \fn void QQuickRhiItemRenderer::initialize(QRhiCommandBuffer *cb)
1095
1096 Called when the item is initialized for the first time, when the
1097 associated texture's size, format, or sample count changes, or when the
1098 QRhi or texture change for any reason. The function is expected to
1099 maintain (create if not yet created, adjust and rebuild if the size has
1100 changed) the graphics resources used by the rendering code in render().
1101
1102 To query the QRhi, QRhiTexture, and other related objects, call rhi(),
1103 colorTexture(), depthStencilBuffer(), and renderTarget().
1104
1105 When the item size changes, the QRhi object, the color buffer texture,
1106 and the depth stencil buffer objects are all the same instances (so the
1107 getters return the same pointers) as before, but the color and
1108 depth/stencil buffers will likely have been rebuilt, meaning the
1109 \l{QRhiTexture::pixelSize()}{size} and the underlying native texture
1110 resource may be different than in the last invocation.
1111
1112 Reimplementations should also be prepared that the QRhi object and the
1113 color buffer texture may change between invocations of this function. For
1114 example, when the item is reparented so that it belongs to a new
1115 QQuickWindow, the the QRhi and all related resources managed by the
1116 QQuickRhiItem will be different instances than before in the subsequent
1117 call to this function. Is is then important that all existing QRhi
1118 resources previously created by the subclass are destroyed because they
1119 belong to the previous QRhi that should not be used anymore.
1120
1121 When \l {QQuickRhiItem::}{isAutoRenderTargetEnabled} is \c true, which is
1122 the default, a depth-stencil QRhiRenderBuffer and a QRhiTextureRenderTarget
1123 associated with the colorTexture() (or msaaColorBuffer()) and the
1124 depth-stencil buffer are created and managed automatically.
1125 Reimplementations of initialize() and render() can query those objects via
1126 depthStencilBuffer() and renderTarget(). When \l
1127 {QQuickRhiItem::}{isAutoRenderTargetEnabled} is set to \c false, these
1128 objects are no longer created and managed automatically. Rather, it will be
1129 up the the initialize() implementation to create buffers and set up the
1130 render target as it sees fit. When manually managing additional color or
1131 depth-stencil attachments for the render target, their size and sample
1132 count must always follow the size and sample count of colorTexture() (or
1133 msaaColorBuffer()), otherwise rendering or 3D API validation errors may
1134 occur.
1135
1136 The subclass-created graphics resources are expected to be released in the
1137 destructor implementation of the subclass.
1138
1139 \a cb is the QRhiCommandBuffer for the current frame. The function is
1140 called with a frame being recorded, but without an active render pass. The
1141 command buffer is provided primarily to allow enqueuing
1142 \l{QRhiCommandBuffer::resourceUpdate()}{resource updates} without deferring
1143 to render().
1144
1145 This function is called on the render thread, if there is one.
1146
1147 \sa render()
1148 */
1149
1150/*!
1151 \fn void QQuickRhiItemRenderer::synchronize(QQuickRhiItem *item)
1152
1153 This function is called on the render thread, if there is one, while the
1154 main/GUI thread is blocked. It is called from
1155 \l{QQuickItem::updatePaintNode()}{the \a {item}'s synchronize step},
1156 and allows reading and writing data belonging to the main and render
1157 threads. Typically property values stored in the QQuickRhiItem are copied
1158 into the QQuickRhiItemRenderer, so that they can be safely read afterwards
1159 in render() when the render and main threads continue to work in parallel.
1160
1161 \sa initialize(), render()
1162 */
1163
1164/*!
1165 \fn void QQuickRhiItemRenderer::render(QRhiCommandBuffer *cb)
1166
1167 Called when the backing color buffer's contents needs updating.
1168
1169 There is always at least one call to initialize() before this function is
1170 called.
1171
1172 To request updates, call \l QQuickItem::update() when calling from QML or
1173 from C++ code on the main/GUI thread (e.g. when in a property setter), or
1174 \l update() when calling from within a QQuickRhiItemRenderer callback.
1175 Calling QQuickRhiItemRenderer's update() from within
1176 render() will lead to triggering updates continuously.
1177
1178 \a cb is the QRhiCommandBuffer for the current frame. The function is
1179 called with a frame being recorded, but without an active render pass.
1180
1181 This function is called on the render thread, if there is one.
1182
1183 \sa initialize(), synchronize()
1184 */
1185
1186QT_END_NAMESPACE
1187
1188#include "moc_qquickrhiitem.cpp"
1189#include "moc_qquickrhiitem_p.cpp"
QRhiTexture * m_colorTexture
QQuickRhiItem * m_item
QRhiCommandBuffer * queryCommandBuffer()
bool isValid() const
QRhiTexture * m_resolveTexture
\inmodule QtQuick
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:606
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:650
Combined button and popup list for selecting options.