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
qquick3dscenerenderer.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
11#include "qquick3dnode_p.h"
20#include "extensions/qquick3drenderextensions.h"
21#include <QtQuick3DUtils/private/qquick3dprofiler_p.h>
22
23#include <QtQuick3DRuntimeRender/private/qssgrendererutil_p.h>
24#include <QtQuick3DRuntimeRender/private/qssgrenderer_p.h>
25
26#include <QtQuick/private/qquickwindow_p.h>
27#include <QtQuick/private/qsgdefaultrendercontext_p.h>
28#include <QtQuick/private/qsgtexture_p.h>
29#include <QtQuick/private/qsgplaintexture_p.h>
30#include <QtQuick/private/qsgrendernode_p.h>
31
32#include <QtQuick3DRuntimeRender/private/qssgrendereffect_p.h>
33#include <QtQuick3DRuntimeRender/private/qssgrhieffectsystem_p.h>
34#include <QtQuick3DRuntimeRender/private/qssglayerrenderdata_p.h>
35#include <QtQuick3DRuntimeRender/private/qssgrhiquadrenderer_p.h>
36#include <QtQuick3DRuntimeRender/private/qssgrhicontext_p.h>
37#include <QtQuick3DRuntimeRender/private/qssgcputonemapper_p.h>
38#include <QtQuick3DRuntimeRender/private/qssgrenderroot_p.h>
39#include <QtQuick3DRuntimeRender/private/qssgrenderskymaterial_p.h>
40#include <QtQuick3DRuntimeRender/private/qssgrenderuserpass_p.h>
41#include <QtQuick3DRuntimeRender/private/qssgrendercommands_p.h>
42#include <QtQuick3DRuntimeRender/private/qssgrendercomputepass_p.h>
43#include <QtQuick3DRuntimeRender/private/qssgrenderbuffer_p.h>
44
45#include <QtQuick3DUtils/private/qssgutils_p.h>
46#include <QtQuick3DUtils/private/qssgassert_p.h>
47
48
49#include <qtquick3d_tracepoints_p.h>
50
51#include <QtCore/QObject>
52#include <QtCore/qqueue.h>
53
55
56Q_TRACE_PREFIX(qtquick3d,
57 "QT_BEGIN_NAMESPACE"
58 "class QQuick3DViewport;"
59 "QT_END_NAMESPACE"
60)
61
62Q_TRACE_POINT(qtquick3d, QSSG_prepareFrame_entry, int width, int height);
66Q_TRACE_POINT(qtquick3d, QSSG_synchronize_entry, QQuick3DViewport *view3D, const QSize &size, float dpr);
68Q_TRACE_POINT(qtquick3d, QSSG_renderPass_entry, const QString &renderPass);
70
71static bool dumpRenderTimes()
72{
73 static bool val = (qEnvironmentVariableIntValue("QT_QUICK3D_DUMP_RENDERTIMES") > 0);
74 return val;
75}
76
77#if QT_CONFIG(qml_debug)
78
79static inline quint64 statDrawCallCount(const QSSGRhiContextStats &stats)
80{
81 quint64 count = 0;
82 const QSSGRhiContextStats::PerLayerInfo &info(stats.perLayerInfo[stats.layerKey]);
83 for (const auto &pass : info.renderPasses)
84 count += QSSGRhiContextStats::totalDrawCallCountForPass(pass);
85 count += QSSGRhiContextStats::totalDrawCallCountForPass(info.externalRenderPass);
86 return count;
87}
88
89#define STAT_PAYLOAD(stats)
90 (statDrawCallCount(stats) | (quint64(stats.perLayerInfo[stats.layerKey].renderPasses.size()) << 32))
91
92#endif
93
94template <typename In, typename Out>
95static void bfs(In *inExtension, QList<Out *> &outList)
96{
97 QSSG_ASSERT(inExtension, return);
98
99 QQueue<In *> queue { { inExtension } };
100 while (queue.size() > 0) {
101 if (auto cur = queue.dequeue()) {
102 if (auto *ext = static_cast<Out *>(QQuick3DObjectPrivate::get(cur)->spatialNode))
103 outList.push_back(ext);
104 for (auto &chld : cur->childItems())
105 queue.enqueue(qobject_cast<In *>(chld));
106 }
107 }
108}
109
110SGFramebufferObjectNode::SGFramebufferObjectNode()
111 : window(nullptr)
112 , renderer(nullptr)
113 , renderPending(true)
114 , invalidatePending(false)
115 , devicePixelRatio(1)
116{
117 qsgnode_set_description(this, QStringLiteral("fbonode"));
118 setFlag(QSGNode::UsePreprocess, true);
119}
120
122{
123 delete renderer;
124 delete texture();
125}
126
128{
129 renderPending = true;
130 markDirty(DirtyMaterial);
131}
132
134{
135 return QSGSimpleTextureNode::texture();
136}
137
139{
140 render();
141}
142
143// QQuickWindow::update() behaves differently depending on whether it's called from the GUI thread
144// or the render thread.
145// TODO: move this to QQuickWindow::fullUpdate(), if we can't change update()
146static void requestFullUpdate(QQuickWindow *window)
147{
148 if (QThread::currentThread() == QCoreApplication::instance()->thread())
149 window->update();
150 else
151 QCoreApplication::postEvent(window, new QEvent(QEvent::Type(QQuickWindowPrivate::FullUpdateRequest)));
152}
153
155{
156 if (renderPending) {
157 if (renderer->renderStats())
158 renderer->renderStats()->startRender();
159
160 renderPending = false;
161
162 if (renderer->m_sgContext->rhiContext()->isValid()) {
163 QRhiTexture *rhiTexture = renderer->renderToRhiTexture(window);
164 bool needsNewWrapper = false;
165 if (!texture() || (texture()->textureSize() != renderer->surfaceSize()
166 || texture()->rhiTexture() != rhiTexture))
167 {
168 needsNewWrapper = true;
169 }
170 if (needsNewWrapper) {
171 delete texture();
172 QSGPlainTexture *t = new QSGPlainTexture;
173 t->setOwnsTexture(false);
174 t->setHasAlphaChannel(true);
175 t->setTexture(rhiTexture);
176 t->setTextureSize(renderer->surfaceSize());
177 setTexture(t);
178 }
179 }
180
181 markDirty(QSGNode::DirtyMaterial);
182 emit textureChanged();
183
184 if (renderer->renderStats())
185 renderer->renderStats()->endRender(dumpRenderTimes());
186
187 if (renderer->m_requestedFramesCount > 0) {
189 requestFullUpdate(window);
190 renderer->m_requestedFramesCount--;
191 }
192 }
193}
194
196{
197 if (!qFuzzyCompare(window->effectiveDevicePixelRatio(), devicePixelRatio)) {
199 quickFbo->update();
200 }
201}
202
203
204QQuick3DSceneRenderer::QQuick3DSceneRenderer(const std::shared_ptr<QSSGRenderContextInterface> &rci)
206{
207}
208
210{
211 const auto &rhiCtx = m_sgContext->rhiContext();
212 auto *rhi = rhiCtx->rhi();
213 rhi->finish(); // finish active readbacks
214 QSSGRhiContextStats::get(*rhiCtx).cleanupLayerInfo(m_layer);
215 m_sgContext->bufferManager()->releaseResourcesForLayer(m_layer);
216
217 if (m_layer) {
218 // The uniform buffer for the tonemapping/blit quad is keyed on the layer.
219 if (rhiCtx->isValid())
220 QSSGRhiContextPrivate::get(rhiCtx.get())->cleanupDrawCallDataForCid(m_layer);
221
222 // The scene root is created by the scene manager and released by the normal cleanup of
223 // scene nodes. Since we delete the layer at a later point, detach the scene root from the
224 // layer now. QSSGRenderNode::removeChild() ignores a node that is no longer a child of
225 // the layer, so this is safe even if the scene manager has already cleaned up (and
226 // unlinked) the scene root.
227 if (m_sceneRootNode)
228 removeNodeFromLayer(m_sceneRootNode);
229 m_sceneRootNode = nullptr;
230
231 // There might be nodes queued for cleanup that still reference the layer,
232 // so we schedule the layer for cleanup so that it is deleted after the nodes
233 // have been cleaned up.
234 if (winAttacment)
235 winAttacment->queueForCleanup(m_layer);
236 else
237 delete m_layer;
238 m_layer = nullptr;
239 }
240
241 delete m_texture;
242
243 releaseAaDependentRhiResources();
244 delete m_effectSystem;
245}
246
247void QQuick3DSceneRenderer::releaseAaDependentRhiResources()
248{
249 const auto &rhiCtx = m_sgContext->rhiContext();
250 if (!rhiCtx->isValid())
251 return;
252
253 delete m_textureRenderTarget;
254 m_textureRenderTarget = nullptr;
255
256 delete m_textureRenderPassDescriptor;
257 m_textureRenderPassDescriptor = nullptr;
258
259 delete m_depthStencilBuffer;
260 m_depthStencilBuffer = nullptr;
261
262 delete m_multiViewDepthStencilBuffer;
263 m_multiViewDepthStencilBuffer = nullptr;
264
265 delete m_msaaRenderBufferLegacy;
266 m_msaaRenderBufferLegacy = nullptr;
267
268 delete m_msaaRenderTexture;
269 m_msaaRenderTexture = nullptr;
270
271 delete m_msaaMultiViewRenderBuffer;
272 m_msaaMultiViewRenderBuffer = nullptr;
273
274 delete m_ssaaTexture;
275 m_ssaaTexture = nullptr;
276
277 delete m_ssaaTextureToTextureRenderTarget;
278 m_ssaaTextureToTextureRenderTarget = nullptr;
279
280 delete m_ssaaTextureToTextureRenderPassDescriptor;
281 m_ssaaTextureToTextureRenderPassDescriptor = nullptr;
282
283 delete m_temporalAATexture;
284 m_temporalAATexture = nullptr;
285 delete m_temporalAARenderTarget;
286 m_temporalAARenderTarget = nullptr;
287 delete m_temporalAARenderPassDescriptor;
288 m_temporalAARenderPassDescriptor = nullptr;
289
290 delete m_prevTempAATexture;
291 m_prevTempAATexture = nullptr;
292}
293
294// Blend factors are in the form of (frame blend factor, accumulator blend factor)
296 QVector2D(0.500000f, 0.500000f), // 1x
297 QVector2D(0.333333f, 0.666667f), // 2x
298 QVector2D(0.250000f, 0.750000f), // 3x
299 QVector2D(0.200000f, 0.800000f), // 4x
300 QVector2D(0.166667f, 0.833333f), // 5x
301 QVector2D(0.142857f, 0.857143f), // 6x
302 QVector2D(0.125000f, 0.875000f), // 7x
303 QVector2D(0.111111f, 0.888889f), // 8x
304};
305
306static const QVector2D s_TemporalAABlendFactors = { 0.5f, 0.5f };
307
308QRhiTexture *QQuick3DSceneRenderer::renderToRhiTexture(QQuickWindow *qw)
309{
310 if (!m_layer)
311 return nullptr;
312
313 QRhiTexture *currentTexture = m_texture; // the result so far
314
315 if (qw) {
316 if (m_renderStats)
317 m_renderStats->startRenderPrepare();
318
319 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DPrepareFrame);
320
321 QSSGRhiContext *rhiCtx = m_sgContext->rhiContext().get();
322 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
323
324 rhiCtxD->setMainRenderPassDescriptor(m_textureRenderPassDescriptor);
325 rhiCtxD->setRenderTarget(m_textureRenderTarget);
326
327 QRhiCommandBuffer *cb = nullptr;
328 QRhiSwapChain *swapchain = qw->swapChain();
329 if (swapchain) {
330 cb = swapchain->currentFrameCommandBuffer();
331 rhiCtxD->setCommandBuffer(cb);
332 } else {
333 QSGRendererInterface *rif = qw->rendererInterface();
334 cb = static_cast<QRhiCommandBuffer *>(
335 rif->getResource(qw, QSGRendererInterface::RhiRedirectCommandBuffer));
336 if (cb)
337 rhiCtxD->setCommandBuffer(cb);
338 else {
339 qWarning("Neither swapchain nor redirected command buffer are available.");
340 return currentTexture;
341 }
342 }
343
344 // Graphics pipeline objects depend on the MSAA sample count, so the
345 // renderer needs to know the value.
346 rhiCtxD->setMainPassSampleCount(m_msaaRenderBufferLegacy ? m_msaaRenderBufferLegacy->sampleCount() :
347 (m_msaaRenderTexture ? m_msaaRenderTexture->sampleCount() :
348 (m_msaaMultiViewRenderBuffer ? m_msaaMultiViewRenderBuffer->sampleCount() : 1)));
349
350 // mainPassViewCount is left unchanged
351
352 int ssaaAdjustedWidth = m_surfaceSize.width();
353 int ssaaAdjustedHeight = m_surfaceSize.height();
354 if (m_layer->antialiasingMode == QSSGRenderLayer::AAMode::SSAA) {
355 ssaaAdjustedWidth *= m_layer->ssaaMultiplier;
356 ssaaAdjustedHeight *= m_layer->ssaaMultiplier;
357 }
358
359 Q_TRACE(QSSG_prepareFrame_entry, ssaaAdjustedWidth, ssaaAdjustedHeight);
360
361 float dpr = m_sgContext->renderer()->dpr();
362 const QRect vp = QRect(0, 0, ssaaAdjustedWidth, ssaaAdjustedHeight);
364 rhiPrepare(vp, dpr);
365
366 if (m_renderStats)
367 m_renderStats->endRenderPrepare();
368
369 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DPrepareFrame, quint64(ssaaAdjustedWidth) | quint64(ssaaAdjustedHeight) << 32, profilingId);
370
371 Q_TRACE(QSSG_prepareFrame_exit);
372
373 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderFrame);
374 Q_TRACE(QSSG_renderFrame_entry, ssaaAdjustedWidth, ssaaAdjustedHeight);
375 if (m_renderStats)
376 m_renderStats->startRender();
377
378 QColor clearColor = Qt::transparent;
379 if (m_backgroundMode == QSSGRenderLayer::Background::Color
380 || (m_backgroundMode == QSSGRenderLayer::Background::SkyBoxCubeMap && !m_layer->skyBoxCubeMap)
381 || (m_backgroundMode == QSSGRenderLayer::Background::SkyBox && !m_layer->lightProbe)
382 || (m_backgroundMode == QSSGRenderLayer::Background::SkyMaterial && !m_layer->skyMaterial)) {
383 // Same logic as with the main render pass and skybox: tonemap
384 // based on tonemapMode (unless it is None), unless there are effects.
385 clearColor = m_layer->firstEffect ? m_linearBackgroundColor : m_tonemappedBackgroundColor;
386 }
387
388 // This is called from the node's preprocess() meaning Qt Quick has not
389 // actually began recording a renderpass. Do our own.
390 cb->beginPass(m_textureRenderTarget, clearColor, { 1.0f, 0 }, nullptr, rhiCtx->commonPassFlags());
391 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
392 QSSGRHICTX_STAT(rhiCtx, beginRenderPass(m_textureRenderTarget));
394 cb->endPass();
395 QSSGRHICTX_STAT(rhiCtx, endRenderPass());
396 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, quint64(ssaaAdjustedWidth) | quint64(ssaaAdjustedHeight) << 32, QByteArrayLiteral("main"));
397
398 const bool temporalAA = m_layer->temporalAAIsActive;
399 const bool progressiveAA = m_layer->progressiveAAIsActive;
400 const bool superSamplingAA = m_layer->antialiasingMode == QSSGRenderLayer::AAMode::SSAA;
401 QRhi *rhi = rhiCtx->rhi();
402
403 currentTexture = superSamplingAA ? m_ssaaTexture : m_texture;
404
405 // Do effects before antialiasing
406 if (m_effectSystem && m_layer->firstEffect && !m_layer->renderedCameras.isEmpty()) {
407 const auto &renderer = m_sgContext->renderer();
408 QSSGLayerRenderData *theRenderData = renderer->getOrCreateLayerRenderData(*m_layer);
409 Q_ASSERT(theRenderData);
410 QRhiTexture *theDepthTexture = theRenderData->getRenderResult(QSSGRenderResult::Key::DepthTexture)->texture;
411 QRhiTexture *theNormalTexture = theRenderData->getRenderResult(QSSGRenderResult::Key::NormalTexture)->texture;
412 QRhiTexture *theMotionVectorTexture = theRenderData->getRenderResult(QSSGRenderResult::Key::MotionVectorTexture)->texture;
413
414 currentTexture = m_effectSystem->process(*m_layer,
415 currentTexture,
416 theDepthTexture,
417 theNormalTexture,
418 theMotionVectorTexture);
419 }
420
421 if ((progressiveAA || temporalAA) && m_prevTempAATexture) {
422 cb->debugMarkBegin(QByteArrayLiteral("Temporal AA"));
423 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
424 Q_TRACE_SCOPE(QSSG_renderPass, QStringLiteral("Temporal AA"));
425 QRhiTexture *blendResult;
426 uint *aaIndex = progressiveAA ? &m_layer->progAAPassIndex : &m_layer->tempAAPassIndex; // TODO: can we use only one index?
427
428 if (*aaIndex > 0) {
429 if ((temporalAA && m_layer->temporalAAMode != QSSGRenderLayer::TAAMode::MotionVector) ||
430 *aaIndex <
431 (temporalAA && m_layer->temporalAAMode == QSSGRenderLayer::TAAMode::MotionVector ?
432 quint32(QSSGLayerRenderData::MAX_AA_LEVELS) :
433 quint32(m_layer->antialiasingQuality))) {
434 const auto &renderer = m_sgContext->renderer();
435
436 QRhiResourceUpdateBatch *rub = rhi->nextResourceUpdateBatch();
437 QSSGRhiDrawCallData &dcd(rhiCtxD->drawCallData({ m_layer, nullptr, nullptr, nullptr, 0 }));
438 QRhiBuffer *&ubuf = dcd.ubuf;
439 const int ubufSize = 4 * sizeof(float);
440 if (!ubuf) {
441 ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, ubufSize);
442 ubuf->create();
443 }
444 int idx = *aaIndex - 1;
445
446 const QSize textureSize = m_prevTempAATexture->pixelSize();
447 QVector4D bufferData;
448 if (progressiveAA)
449 bufferData = QVector4D(s_ProgressiveAABlendFactors[idx]);
450 else if (m_layer->temporalAAMode == QSSGRenderLayer::TAAMode::Default)
451 bufferData = QVector4D(s_TemporalAABlendFactors);
452 else
453 bufferData = QVector4D(1.0f / qMax(textureSize.width(), 1), 1.0f / qMax(textureSize.height(), 1),
454 0.9f + (qMin(qMax(m_layer->temporalAAStrength, 0.3f), 1.0f) - 0.3f) / 0.7f * 0.09f, 0.0f); //map it to 0.9 to 0.99
455
456 rub->updateDynamicBuffer(ubuf, 0, 4 * sizeof(float), &bufferData);
457 QSSGRhiGraphicsPipelineState ps;
458 ps.viewport = QRhiViewport(0, 0, float(textureSize.width()), float(textureSize.height()));
459
460 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
461 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
462 QSSGRhiShaderResourceBindingList bindings;
463 bindings.addUniformBuffer(0, QRhiShaderResourceBinding::FragmentStage, ubuf);
464 bindings.addTexture(1, QRhiShaderResourceBinding::FragmentStage, currentTexture, sampler);
465 bindings.addTexture(2, QRhiShaderResourceBinding::FragmentStage, m_prevTempAATexture, sampler);
466 if (m_layer->temporalAAMode == QSSGRenderLayer::TAAMode::MotionVector) {
467 QSSGLayerRenderData *theRenderData = renderer->getOrCreateLayerRenderData(*m_layer);
468 Q_ASSERT(theRenderData);
469 QRhiTexture *theDepthTexture = theRenderData->getRenderResult(QSSGRenderResult::Key::DepthTexture)->texture;
470 QRhiTexture *theMotionVectorTexture = theRenderData->getRenderResult(QSSGRenderResult::Key::MotionVectorTexture)->texture;
471 bindings.addTexture(3, QRhiShaderResourceBinding::FragmentStage, theDepthTexture, sampler);
472 bindings.addTexture(4, QRhiShaderResourceBinding::FragmentStage, theMotionVectorTexture, sampler);
473 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(ps, m_sgContext->shaderCache()->getBuiltInRhiShaders().getRhiTemporalAAShader().get());
474 } else {
475 // The fragment shader relies on per-target compilation and
476 // QSHADER_ macros of qsb, hence no need to communicate a flip
477 // flag from here.
478 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(ps, m_sgContext->shaderCache()->getBuiltInRhiShaders().getRhiProgressiveAAShader().get());
479 }
480
481 QRhiShaderResourceBindings *srb = rhiCtxD->srb(bindings);
482 renderer->rhiQuadRenderer()->prepareQuad(rhiCtx, rub);
483 renderer->rhiQuadRenderer()->recordRenderQuadPass(rhiCtx, &ps, srb, m_temporalAARenderTarget, QSSGRhiQuadRenderer::UvCoords);
484 blendResult = m_temporalAATexture;
485 } else {
486 blendResult = m_prevTempAATexture;
487 }
488 } else {
489 // For the first frame: no blend, only copy
490 blendResult = currentTexture;
491 }
492
493 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
494
495 const bool isMotionVector = m_layer->temporalAAMode == QSSGRenderLayer::TAAMode::MotionVector;
496 const quint32 aaLimit = (temporalAA && isMotionVector) ? quint32(QSSGLayerRenderData::MAX_AA_LEVELS) : quint32(m_layer->antialiasingQuality);
497
498 const bool aaActive = (temporalAA && !isMotionVector) || (*aaIndex < aaLimit);
499 const bool usePrevTexture = m_prevTempAATexture != nullptr;
500
501 if (aaActive && usePrevTexture) {
502 QRhiTexture *copySource = (blendResult && (progressiveAA || isMotionVector)) ? blendResult : currentTexture;
503
504 if (copySource) {
505 auto *rub = rhi->nextResourceUpdateBatch();
506 rub->copyTexture(m_prevTempAATexture, copySource);
507 cb->resourceUpdate(rub);
508 }
509 }
510
511 (*aaIndex)++;
512 cb->debugMarkEnd();
513 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, 0, QByteArrayLiteral("temporal_aa"));
514
515 currentTexture = blendResult;
516 }
517
518 if (m_layer->antialiasingMode == QSSGRenderLayer::AAMode::SSAA) {
519 // With supersampling antialiasing we at this point have the
520 // content rendered at a larger size into m_ssaaTexture. Now scale
521 // it down to the expected size into m_texture, using linear
522 // filtering. Unlike in the OpenGL world, there is no
523 // glBlitFramebuffer equivalent available, because APIs like D3D
524 // and Metal have no such operation (the generally supported
525 // texture copy operations are 1:1 copies, without support for
526 // scaling, which is what we would need here). So draw a quad.
527
528 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
529 const auto &renderer = m_sgContext->renderer();
530
531 cb->debugMarkBegin(QByteArrayLiteral("SSAA downsample"));
532 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
533
534 Q_TRACE_SCOPE(QSSG_renderPass, QStringLiteral("SSAA downsample"));
535
536 renderer->rhiQuadRenderer()->prepareQuad(rhiCtx, nullptr);
537
538 // Instead of passing in a flip flag we choose to rely on qsb's
539 // per-target compilation mode in the fragment shader. (it does UV
540 // flipping based on QSHADER_ macros) This is just better for
541 // performance and the shaders are very simple so introducing a
542 // uniform block and branching dynamically would be an overkill.
543 const auto &shaderPipeline = m_sgContext->shaderCache()->getBuiltInRhiShaders().getRhiSupersampleResolveShader(m_layer->viewCount);
544
545 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
546 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
547 QSSGRhiShaderResourceBindingList bindings;
548 bindings.addTexture(0, QRhiShaderResourceBinding::FragmentStage, currentTexture, sampler);
549 QRhiShaderResourceBindings *srb = rhiCtxD->srb(bindings);
550
551 QSSGRhiGraphicsPipelineState ps;
552 ps.viewport = QRhiViewport(0, 0, float(m_surfaceSize.width()), float(m_surfaceSize.height()));
553 ps.viewCount = m_layer->viewCount;
554 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(ps, shaderPipeline.get());
555
556 renderer->rhiQuadRenderer()->recordRenderQuadPass(rhiCtx, &ps, srb, m_ssaaTextureToTextureRenderTarget, QSSGRhiQuadRenderer::UvCoords);
557 cb->debugMarkEnd();
558 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, 0, QByteArrayLiteral("ssaa_downsample"));
559
560 currentTexture = m_texture;
561 }
562
563 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderFrame,
564 STAT_PAYLOAD(QSSGRhiContextStats::get(*rhiCtx)),
565 profilingId);
567 if (m_renderStats)
568 m_renderStats->endRender(dumpRenderTimes());
569 Q_TRACE(QSSG_renderFrame_exit);
570 }
571
572 if (m_layer && m_layer->skyMaterial && m_layer->skyMaterial->wantsMoreFrames)
573 ++m_requestedFramesCount;
574
575 return currentTexture;
576}
577
579{
580 m_sgContext->renderer()->beginFrame(*m_layer);
581}
582
584{
585 m_sgContext->renderer()->endFrame(*m_layer);
586}
587
588void QQuick3DSceneRenderer::rhiPrepare(const QRect &viewport, qreal displayPixelRatio)
589{
590 if (!m_layer)
591 return;
592
593 const auto &renderer = m_sgContext->renderer();
594
595 renderer->setDpr(displayPixelRatio);
596
597 renderer->setViewport(viewport);
598
599 renderer->prepareLayerForRender(*m_layer);
600 // If sync was called the assumption is that the scene is dirty regardless of what
601 // the scene prep function says, we still should verify that we have a camera before
602 // we call render prep and render.
603 const bool renderReady = !m_layer->renderData->renderedCameras.isEmpty();
604 if (renderReady) {
605 renderer->rhiPrepare(*m_layer);
606 m_prepared = true;
607 }
608}
609
611{
612 if (m_prepared) {
613 // There is no clearFirst flag - the rendering here does not record a
614 // beginPass() so it never clears on its own.
615
616 m_sgContext->renderer()->rhiRender(*m_layer);
617 }
618
619 m_prepared = false;
620}
621
622#if QT_CONFIG(quick_shadereffect)
623static QRhiTexture::Format toRhiTextureFormat(QQuickShaderEffectSource::Format format)
624{
625 switch (format) {
626 case QQuickShaderEffectSource::RGBA8:
627 return QRhiTexture::RGBA8;
628 case QQuickShaderEffectSource::RGBA16F:
629 return QRhiTexture::RGBA16F;
630 case QQuickShaderEffectSource::RGBA32F:
631 return QRhiTexture::RGBA32F;
632 default:
633 return QRhiTexture::RGBA8;
634 }
635}
636#endif
637
638static QVector3D tonemapRgb(const QVector3D &c, QQuick3DSceneEnvironment::QQuick3DEnvironmentTonemapModes tonemapMode)
639{
640 switch (tonemapMode) {
641 case QQuick3DSceneEnvironment::TonemapModeLinear:
642 return QSSGTonemapper::tonemapLinearToSrgb(c);
643 case QQuick3DSceneEnvironment::TonemapModeHejlDawson:
644 return QSSGTonemapper::tonemapHejlDawson(c);
645 case QQuick3DSceneEnvironment::TonemapModeAces:
646 return QSSGTonemapper::tonemapAces(c);
647 case QQuick3DSceneEnvironment::TonemapModeFilmic:
648 return QSSGTonemapper::tonemapFilmic(c);
649 default:
650 break;
651 }
652 return c;
653}
654
656{
657 const auto *computePass = qobject_cast<const QQuick3DComputePass *>(pass);
658 return computePass && computePass->executionStage() == QQuick3DComputePass::StartOfFrame
659 ? QSSGRenderUserPassBase::ExecutionStage::StartOfFrame
660 : QSSGRenderUserPassBase::ExecutionStage::PreColor;
661}
662
663void QQuick3DSceneRenderer::synchronize(QQuick3DViewport *view3D, const QSize &size, float dpr)
664{
665 Q_TRACE_SCOPE(QSSG_synchronize, view3D, size, dpr);
666
667 Q_ASSERT(view3D != nullptr); // This is not an option!
668 QSSGRhiContext *rhiCtx = m_sgContext->rhiContext().get();
669 Q_ASSERT(rhiCtx != nullptr);
670
671 // Generate layer node
672 if (!m_layer)
673 m_layer = new QSSGRenderLayer();
674
675 bool newRenderStats = false;
676 if (!m_renderStats) {
677 m_renderStats = view3D->renderStats();
678 newRenderStats = true;
679 }
680
681 if (m_renderStats)
682 m_renderStats->startSync();
683
684 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DSynchronizeFrame);
685
686 m_sgContext->renderer()->setDpr(dpr);
687 bool layerSizeIsDirty = m_surfaceSize != size;
688 m_surfaceSize = size;
689
690 QQuick3DSceneEnvironment *environment = view3D->environment();
691 if (environment->lightmapper()) {
692 QQuick3DLightmapper *lightmapper = environment->lightmapper();
693 lmOptions.opacityThreshold = lightmapper->opacityThreshold();
694 lmOptions.bias = lightmapper->bias();
695 lmOptions.useAdaptiveBias = lightmapper->isAdaptiveBiasEnabled();
696 lmOptions.indirectLightEnabled = lightmapper->isIndirectLightEnabled();
697 lmOptions.indirectLightSamples = lightmapper->samples();
698 lmOptions.indirectLightWorkgroupSize = lightmapper->indirectLightWorkgroupSize();
699 lmOptions.indirectLightBounces = lightmapper->bounces();
700 lmOptions.indirectLightFactor = lightmapper->indirectLightFactor();
701 lmOptions.sigma = lightmapper->denoiseSigma();
702 lmOptions.texelsPerUnit = lightmapper->texelsPerUnit();
703 } else {
704 lmOptions = {};
705 }
706
707
708 if (environment->m_dirtyFlags & QQuick3DSceneEnvironment::InternalDirtyFlag::LightmapperDirty) {
709 environment->m_dirtyFlags &= ~QQuick3DSceneEnvironment::InternalDirtyFlag::LightmapperDirty;
710 // Resolve lightmaps source url
711 const QQmlContext *context = qmlContext(view3D);
712 const QUrl originalSource = environment->lightmapper() ? environment->lightmapper()->source()
713 : QUrl::fromLocalFile(QStringLiteral("lightmaps.bin"));
714 const auto resolvedUrl = context ? context->resolvedUrl(originalSource) : originalSource;
715 const auto qmlSource = QQmlFile::urlToLocalFileOrQrc(resolvedUrl);
716 const QString lightmapSource = qmlSource.isEmpty() ? originalSource.path() : qmlSource;
717 lmOptions.source = lightmapSource;
718 m_layer->lightmapSource = lightmapSource;
719 // HACK: this is also set in the render layer but we need to set it here since
720 // it is needed below when calculating bounding boxes from the stored lightmap mesh
721 m_sgContext->bufferManager()->setLightmapSource(m_layer->lightmapSource);
722 if (QQuick3DSceneManager *sceneManager = QQuick3DObjectPrivate::get(view3D->scene())->sceneManager)
723 sceneManager->lightmapSourceTracker = { m_layer->lightmapSource, true };
724 }
725
726 // Synchronize scene managers under this window
727 QSet<QSSGRenderGraphObject *> resourceLoaders;
728 QQuick3DWindowAttachment::SyncResult requestSharedUpdate = QQuick3DWindowAttachment::SyncResultFlag::None;
729 if (auto window = view3D->window()) {
730 if (!winAttacment || winAttacment->window() != window)
731 winAttacment = QQuick3DSceneManager::getOrSetWindowAttachment(*window);
732
733 if (winAttacment && winAttacment->rci() != m_sgContext)
734 winAttacment->setRci(m_sgContext);
735
736 QSSGRenderRoot *rootNode = winAttacment->rootNode();
737 if (m_layer->rootNode != rootNode) {
738 Q_ASSERT(m_layer->rootNode == nullptr);
739 rootNode->addChild(*m_layer);
740 rootNode->setStartVersion(m_layer->h.version());
741 m_layer->ref(rootNode);
742 }
743
744 if (winAttacment)
745 requestSharedUpdate |= winAttacment->synchronize(resourceLoaders);
746 }
747
748 // Import scenes used in a multi-window application...
749 QQuick3DNode *importScene = view3D->importScene();
750 if (importScene) {
751 QQuick3DSceneManager *importSceneManager = QQuick3DObjectPrivate::get(importScene)->sceneManager;
752 // If the import scene is used with 3D views under a different window, then we'll
753 // need to trigger updates for those as well.
754 if (auto window = importSceneManager->window(); window && window != view3D->window()) {
755 if (auto winAttacment = importSceneManager->wattached) {
756 // Not the same window but backed by the same rhi?
757 auto rci = winAttacment->rci();
758 const bool inlineSync = (rci && rci->rhi() && (rci->rhi()->thread() == m_sgContext->rhi()->thread()));
759 if (inlineSync) {
760 // Given that we're on the same thread, we can do an immediate sync
761 // (rhi instances can differ, e.g., basic renderloop).
762 winAttacment->synchronize(resourceLoaders);
763 } else if (rci && !window->isExposed()) { // Forced sync of non-exposed windows
764 // Not exposed, so not rendering (playing with fire here)...
765 winAttacment->synchronize(resourceLoaders);
766 } else if (!rci || (requestSharedUpdate & QQuick3DWindowAttachment::SyncResultFlag::SharedResourcesDirty)) {
767 // If there's no RCI for the importscene we'll request an update, which should
768 // mean we only get here once. It also means the update to any secondary windows
769 // will be delayed. Note that calling this function on each sync would cause the
770 // different views to ping-pong for updated forever...
771 winAttacment->requestUpdate();
772 }
773 }
774 }
775 }
776
777 // Update the layer node properties
778 // Store the view count in the layer. If there are multiple, or nested views, sync is called multiple times and the view count
779 // can change (see: updateLayerNode()), so we need to store the value on the layer to make sure we don't end up with a mismatch
780 // between between the view count of the views rendering directly to the screen (XrView instance) and the view count of the offscreen
781 // rendered View3Ds.
782 // See also: preSynchronize(), queryMainRenderPassDescriptorAndCommandBuffer() and queryInlineRenderPassDescriptorAndCommandBuffer()
783 // (At this point the mainPassViewCount for this view should be set to the correct value)
784 m_layer->viewCount = rhiCtx->mainPassViewCount();
785 updateLayerNode(*m_layer, *view3D, resourceLoaders.values());
786
787 // If the viewport visibility has changed, we need to mark the layer as dirty to ensure it gets re-rendered.
788 // NOTE: This is needed when there are multiple viewports using a shared scene since the viewport that becomes
789 // visible might wake-up to a scene where all the data is up-to-date, but we still need to render the scene and
790 // not skip it, which would be the case if we see there's no dirty data and therefore skip rendering the frame.
791 if (view3D->m_visibilityChanged) {
792 view3D->m_visibilityChanged = false;
793 m_layer->markDirty(QSSGRenderLayer::DirtyFlag::VisibilityDirty);
794 }
795
796 // Request extra frames for antialiasing (ProgressiveAA/TemporalAA)
797
798 m_requestedFramesCount = 0;
799 if (m_layer->isProgressiveAAEnabled() || m_layer->temporalAAMode == QSSGRenderLayer::TAAMode::MotionVector) {
800 // with progressive AA or temporal AA motion vector mode, we need a number of extra frames after the last dirty one
801 // if we always reset requestedFramesCount when dirty, we will get the extra frames eventually
802 // +1 since we need a normal frame to start with, and we're not copying that from the screen
803 // Temporal AA (MotionVector mode) requires ~44 frames to reach 99% convergence when
804 // blending with mix(current, previous, 0.9). This exponential accumulation ensures
805 // sub-pixel details are properly resolved through temporal super-sampling.
806 m_requestedFramesCount = (m_layer->temporalAAMode == QSSGRenderLayer::TAAMode::MotionVector ? 45 :
807 int(m_layer->antialiasingQuality) + 1);
808 } else if (m_layer->isTemporalAAEnabled()) {
809 // When temporalAA is on and antialiasing mode changes,
810 // layer needs to be re-rendered (at least) MAX_TEMPORAL_AA_LEVELS times
811 // depend on the temporalAA mode to generate temporal antialiasing.
812 // Also, we need to do an extra render when animation stops
813 m_requestedFramesCount = (m_aaIsDirty || m_temporalIsDirty) ? QSSGLayerRenderData::MAX_TEMPORAL_AA_LEVELS : 1;
814 }
815
816 // Now that we have the effect list used for rendering, finalize the shader
817 // code based on the layer (scene.env.) settings.
818 for (QSSGRenderEffect *effectNode = m_layer->firstEffect; effectNode; effectNode = effectNode->m_nextEffect)
819 effectNode->finalizeShaders(*m_layer, m_sgContext.get());
820
821 // Schedule the top-level user passes. A pass is a sub-pass iff another pass
822 // references it through a SubRenderPass command; a sub-pass is invoked by its
823 // parent and renders into the parent's target, so it is never scheduled. Its
824 // order is its command index, established by the parent. A top-level pass
825 // orders by its nesting depth, the number of RenderPass ancestors it has:
826 // deeper passes render first ("children before parents"), so a pass
827 // declared inside its consumer renders before it. Other ancestors do not
828 // count towards the depth, so a pass grouped under a Node orders as if it
829 // were declared at the level of that Node. The
830 // manager breaks ties between passes at equal depth by declaration order, so
831 // the render order is deterministic regardless of the order a
832 // RenderOutputProvider scheduled a pass.
833 //
834 // The role itself is not derived here: each pass mirrors it to its backend
835 // node in updateSpatialNode() from the reference count the SubRenderPass
836 // commands maintain, and the node updates have already been flushed above.
837 if (QQuick3DSceneManager *sm = QQuick3DObjectPrivate::get(view3D->scene())->sceneManager; sm) {
838 // The classification-dependent state only changes when a pass is added
839 // or removed, a command list is rebuilt, a pass is reparented, or a
840 // pass's role flips, so re-derive it only then.
841 if (sm->userRenderPassesDirty) {
842 // A sub-pass renders into its parent's render target, so any attachment
843 // commands it declares are ignored. Warn so the mistake is not silent;
844 // this block only runs when the classification changes.
845 for (QSSGRenderUserPassBase *userPassBase : std::as_const(sm->userRenderPasses)) {
846 if (!userPassBase->isSubPass())
847 continue;
848 const QSSGRenderUserPass *userPass = static_cast<const QSSGRenderUserPass *>(userPassBase);
849 for (const QSSGCommand *cmd : std::as_const(userPass->commands)) {
850 if (cmd->m_type == CommandType::ColorAttachment
851 || cmd->m_type == CommandType::DepthStencilAttachment
852 || cmd->m_type == CommandType::DepthTextureAttachment) {
853 qWarning() << "RenderPass" << sm->lookUpNode(userPass)
854 << "is used as a sub-pass; its" << cmd->typeAsString()
855 << "command is ignored because a sub-pass renders into its parent's render target.";
856 }
857 }
858 }
859 // Nesting depth. Only top-level passes are considered: a sub-pass's
860 // placement never affects ordering, and a pass declared inline on a
861 // SubRenderPass command has no parent item. The depth is the number
862 // of RenderPass ancestors; other ancestors (a Node used for
863 // grouping, for example) are transparent and do not affect the
864 // order. RenderPass ancestors count regardless of their role, so
865 // the order is stable when a pass's role flips at runtime.
866 //
867 // A pass executes in the earliest stage of itself and its
868 // ancestors, so that it still executes before them.
869 for (QSSGRenderUserPassBase *userPass : std::as_const(sm->userRenderPasses)) {
870 userPass->m_nestingDepth = 0;
871 userPass->m_executionStage = QSSGRenderUserPassBase::ExecutionStage::PreColor;
872 if (userPass->isSubPass())
873 continue;
874 const QQuick3DObject *fo = sm->lookUpNode(userPass);
875 if (!fo)
876 continue; // Property-referenced pass without a parent; depth 0.
877 quint32 depth = 0;
878 auto stage = declaredExecutionStage(fo);
879 for (QQuick3DObject *p = fo->parentItem(); p; p = p->parentItem()) {
880 if (!QSSGRenderGraphObjectUtils::isUserRenderPass(QQuick3DObjectPrivate::get(p)->type))
881 continue;
882 ++depth;
883 stage = qMin(stage, declaredExecutionStage(p));
884 }
885 userPass->m_nestingDepth = depth;
886 userPass->m_executionStage = stage;
887 }
888 quint32 declarationOrder = 0;
889 for (QSSGRenderUserPassBase *userPass : std::as_const(sm->userRenderPasses)) {
890 if (!userPass->isSubPass())
891 userPass->m_declarationOrder = declarationOrder++;
892 }
893 sm->userRenderPassesDirty = false;
894 }
895
896 QSSGUserRenderPassManager::UserPassSet topLevelPasses;
897 topLevelPasses.reserve(sm->userRenderPasses.size());
898 for (QSSGRenderUserPassBase *userPass : std::as_const(sm->userRenderPasses)) {
899 userPass->finalizeShaders(*m_sgContext);
900 if (!userPass->isSubPass())
901 topLevelPasses.push_back(userPass);
902 }
903
904 // The layer render data is normally created when the layer is first
905 // prepared, which is after this point. Create it here so the passes are
906 // scheduled for the very first frame as well, rather than only from the
907 // second frame on.
908 QSSGLayerRenderData *renderData = m_sgContext->renderer()->getOrCreateLayerRenderData(*m_layer);
909 if (const QSSGUserRenderPassManagerPtr &upm = renderData->requestUserRenderPassManager())
910 upm->setScheduledPasses(topLevelPasses);
911 }
912
913 if (newRenderStats)
914 m_renderStats->setRhiContext(rhiCtx, m_layer);
915
916 static const auto getStageIndex = [](const QSSGRenderExtension &ext) -> size_t {
917 const QSSGRenderExtension::RenderMode mode = ext.mode();
918 const QSSGRenderExtension::RenderStage stage = ext.stage();
919 // If the mode is 'Standalone' then the stage is irrelevant and we put the
920 // extension in the 'TextureProvider' list.
921 if (mode == QSSGRenderExtension::RenderMode::Standalone)
922 return size_t(QSSGRenderLayer::RenderExtensionStage::TextureProviders);
923
924 switch (stage) {
925 case QSSGRenderExtension::RenderStage::PreColor:
926 return size_t(QSSGRenderLayer::RenderExtensionStage::Underlay);
927 case QSSGRenderExtension::RenderStage::PostColor:
928 return size_t(QSSGRenderLayer::RenderExtensionStage::Overlay);
929 }
930
931 Q_UNREACHABLE_RETURN(size_t(QSSGRenderLayer::RenderExtensionStage::Underlay));
932 };
933
934 // if the list is dirty we rebuild (assumption is that this won't happen frequently).
935 // NOTE: We do this is two steps as extensions can be added both via the extensionList
936 // or via auto-registration.
937 if (QQuick3DSceneManager *sm = QQuick3DObjectPrivate::get(view3D->scene())->sceneManager; sm) {
938 const bool rebuildExtensionLists = (requestSharedUpdate & QQuick3DWindowAttachment::SyncResultFlag::ExtensionsDiry)
939 || view3D->extensionListDirty()
940 || sm->autoRegisteredExtensionsDirty;
941
942 // Explicit extensions from the extension list
943 // NOTE: If either the explicit or auto-registered extensions are dirty we need to
944 // rebuild the list of active extensions.
945 if (rebuildExtensionLists) {
946 // Clear existing extensions
947 for (size_t i = 0; i != size_t(QSSGRenderLayer::RenderExtensionStage::Count); ++i)
948 m_layer->renderExtensions[i].clear();
949
950 // All items in the extension list are root items,
951 const auto &extensions = view3D->extensionList();
952 for (const auto &ext : extensions) {
953 const auto type = QQuick3DObjectPrivate::get(ext)->type;
954 if (QSSGRenderGraphObject::isExtension(type)) {
955 if (type == QSSGRenderGraphObject::Type::RenderExtension) {
956 if (auto *renderExt = qobject_cast<QQuick3DRenderExtension *>(ext)) {
957 if (QSSGRenderExtension *ssgExt = static_cast<QSSGRenderExtension *>(QQuick3DObjectPrivate::get(renderExt)->spatialNode)) {
958 const auto stage = getStageIndex(*ssgExt);
959 auto &list = m_layer->renderExtensions[size_t(stage)];
960 bfs(qobject_cast<QQuick3DRenderExtension *>(ext), list);
961 }
962 }
963 }
964 }
965 }
966
967 view3D->clearExtensionListDirty();
968 }
969
970 // Auto-registered extensions
971 if (sm->autoRegisteredExtensionsDirty) {
972 for (QSSGRenderExtension *ae : std::as_const(sm->autoRegisteredExtensions))
973 m_layer->renderExtensions[getStageIndex(*ae)].push_back(ae);
974 sm->autoRegisteredExtensionsDirty = false;
975 }
976 }
977
978 bool postProcessingNeeded = m_layer->firstEffect;
979 bool postProcessingWasActive = m_effectSystem;
980 QSSGRenderTextureFormat::Format effectOutputFormatOverride = QSSGRenderTextureFormat::Unknown;
981 if (postProcessingNeeded) {
982 QSSGRenderEffect *lastEffect = m_layer->firstEffect;
983 while (lastEffect->m_nextEffect)
984 lastEffect = lastEffect->m_nextEffect;
985 effectOutputFormatOverride = QSSGRhiEffectSystem::overriddenOutputFormat(lastEffect);
986 }
987 const auto layerTextureFormat = [effectOutputFormatOverride, view3D](QRhi *rhi, bool postProc) {
988 if (effectOutputFormatOverride != QSSGRenderTextureFormat::Unknown)
989 return QSSGBufferManager::toRhiFormat(effectOutputFormatOverride);
990
991 // Our standard choice for the postprocessing input/output textures'
992 // format is a floating point one. (unlike intermediate Buffers, which
993 // default to RGBA8 unless the format is explicitly specified)
994 // This is intentional since a float format allows passing in
995 // non-tonemapped content without colors being clamped when written out
996 // to the render target.
997 //
998 // When it comes to the output, this applies to that too due to
999 // QSSGRhiEffectSystem picking it up unless overridden (with a Buffer
1000 // an empty 'name'). Here too a float format gives more flexibility:
1001 // the effect may or may not do its own tonemapping and this approach
1002 // is compatible with potential future on-screen HDR output support.
1003
1004 const QRhiTexture::Format preferredPostProcFormat = QRhiTexture::RGBA16F;
1005 if (postProc && rhi->isTextureFormatSupported(preferredPostProcFormat))
1006 return preferredPostProcFormat;
1007
1008#if QT_CONFIG(quick_shadereffect)
1009 const QRhiTexture::Format preferredView3DFormat = toRhiTextureFormat(view3D->renderFormat());
1010 if (rhi->isTextureFormatSupported(preferredView3DFormat))
1011 return preferredView3DFormat;
1012#endif
1013
1014 return QRhiTexture::RGBA8;
1015 };
1016 bool postProcessingStateDirty = postProcessingNeeded != postProcessingWasActive;
1017
1018 // Store from the layer properties the ones we need to handle ourselves (with the RHI code path)
1019 m_backgroundMode = QSSGRenderLayer::Background(view3D->environment()->backgroundMode());
1020
1021 // This is stateful since we only want to recalculate the tonemapped color
1022 // when the color changes, not in every frame.
1023 QColor currentUserBackgroundColor = view3D->environment()->clearColor();
1024 if (m_userBackgroundColor != currentUserBackgroundColor) {
1025 m_userBackgroundColor = currentUserBackgroundColor;
1026 m_linearBackgroundColor = QSSGUtils::color::sRGBToLinearColor(m_userBackgroundColor);
1027 const QVector3D tc = tonemapRgb(QVector3D(m_linearBackgroundColor.redF(),
1028 m_linearBackgroundColor.greenF(),
1029 m_linearBackgroundColor.blueF()),
1030 view3D->environment()->tonemapMode());
1031 m_tonemappedBackgroundColor = QColor::fromRgbF(tc.x(), tc.y(), tc.z(), m_linearBackgroundColor.alphaF());
1032 }
1033 m_layer->scissorRect = QRect(view3D->environment()->scissorRect().topLeft() * dpr,
1034 view3D->environment()->scissorRect().size() * dpr);
1035
1036 // Add the scene root node for the scene to the layer
1037 // NOTE: The scene root is not the same as THE root node.
1038 // The scene root is the root of the scene in a view (There can be multiple views.)
1039 // THE root node, which there's only one of, is the root for all nodes in the window.
1040 auto sceneRootNode = static_cast<QSSGRenderNode*>(QQuick3DObjectPrivate::get(view3D->scene())->spatialNode);
1041 if (sceneRootNode != m_sceneRootNode) {
1042 if (m_sceneRootNode)
1043 removeNodeFromLayer(m_sceneRootNode);
1044
1045 if (sceneRootNode)
1046 addNodeToLayer(sceneRootNode);
1047
1048 m_sceneRootNode = sceneRootNode;
1049 }
1050
1051 // Add the referenced scene root node to the layer as well if available
1052 QSSGRenderNode *importSceneRootNode = nullptr;
1053 if (importScene)
1054 importSceneRootNode = static_cast<QSSGRenderNode*>(QQuick3DObjectPrivate::get(importScene)->spatialNode);
1055
1056 if (importSceneRootNode != m_importSceneRootNode) {
1057 if (m_importSceneRootNode)
1058 m_layer->removeImportScene(*m_importSceneRootNode);
1059
1060 if (importSceneRootNode) {
1061 // if importScene has the rendered viewport as ancestor, it probably means
1062 // "importScene: MyScene { }" type of inclusion.
1063 // In this case don't duplicate content by adding it again.
1064 QObject *sceneParent = importScene->parent();
1065 bool isEmbedded = false;
1066 while (sceneParent) {
1067 if (sceneParent == view3D) {
1068 isEmbedded = true;
1069 break;
1070 }
1071 sceneParent = sceneParent->parent();
1072 }
1073 if (!isEmbedded)
1074 m_layer->setImportScene(*importSceneRootNode);
1075 }
1076
1077 m_importSceneRootNode = importSceneRootNode;
1078 }
1079
1080 // If the tree is dirty, reindex() rebuilds node indices and marks all
1081 // child layers tree-dirty so they rebuild their node views during prep.
1082 // The layer dirty flag is cleared in the layer prep function; the root
1083 // dirty flag is cleared inside reindex() itself.
1084 {
1085 QSSGRenderRoot *rootNode = winAttacment->rootNode();
1086 if (rootNode->isDirty(QSSGRenderRoot::DirtyFlag::TreeDirty)) {
1087 rootNode->reindex();
1088 }
1089 }
1090
1091 maybeSetupLightmapBaking(view3D);
1092
1093 if (m_useFBO && rhiCtx->isValid()) {
1094 QRhi *rhi = rhiCtx->rhi();
1095 const QSize renderSize = m_layer->isSsaaEnabled() ? m_surfaceSize * m_layer->ssaaMultiplier : m_surfaceSize;
1096
1097 if (m_texture) {
1098 // the size changed, or the AA settings changed, or toggled between some effects - no effect
1099 if (layerSizeIsDirty || postProcessingStateDirty) {
1100 m_texture->setPixelSize(m_surfaceSize);
1101 m_texture->setFormat(layerTextureFormat(rhi, postProcessingNeeded));
1102 m_texture->create();
1103
1104 // If AA settings changed, then we drop and recreate all
1105 // resources, otherwise use a lighter path if just the size
1106 // changed.
1107 if (!m_aaIsDirty) {
1108 // A special case: when toggling effects and AA is on,
1109 // use the heavier AA path because the renderbuffer for
1110 // MSAA and texture for SSAA may need a different
1111 // format now since m_texture's format could have
1112 // changed between RBGA8 and RGBA16F (due to layerTextureFormat()).
1113 if (postProcessingStateDirty && (m_layer->antialiasingMode != QSSGRenderLayer::AAMode::NoAA || m_layer->isTemporalAAEnabled())) {
1114 releaseAaDependentRhiResources();
1115 } else {
1116 if (m_ssaaTexture) {
1117 m_ssaaTexture->setPixelSize(renderSize);
1118 m_ssaaTexture->create();
1119 }
1120 if (m_depthStencilBuffer) {
1121 m_depthStencilBuffer->setPixelSize(renderSize);
1122 m_depthStencilBuffer->create();
1123 }
1124 if (m_multiViewDepthStencilBuffer) {
1125 m_multiViewDepthStencilBuffer->setPixelSize(renderSize);
1126 m_multiViewDepthStencilBuffer->create();
1127 }
1128 if (m_msaaRenderBufferLegacy) {
1129 m_msaaRenderBufferLegacy->setPixelSize(renderSize);
1130 m_msaaRenderBufferLegacy->create();
1131 }
1132 if (m_msaaRenderTexture) {
1133 m_msaaRenderTexture->setPixelSize(renderSize);
1134 m_msaaRenderTexture->create();
1135 }
1136 if (m_msaaMultiViewRenderBuffer) {
1137 m_msaaMultiViewRenderBuffer->setPixelSize(renderSize);
1138 m_msaaMultiViewRenderBuffer->create();
1139 }
1140 // Toggling effects on and off will change the format
1141 // (assuming effects default to a floating point
1142 // format) and that needs on a different renderpass on
1143 // Vulkan. Hence renewing m_textureRenderPassDescriptor as well.
1144 if (postProcessingStateDirty) {
1145 delete m_textureRenderPassDescriptor;
1146 m_textureRenderPassDescriptor = m_textureRenderTarget->newCompatibleRenderPassDescriptor();
1147 m_textureRenderTarget->setRenderPassDescriptor(m_textureRenderPassDescriptor);
1148 }
1149 m_textureRenderTarget->create();
1150 if (m_ssaaTextureToTextureRenderTarget)
1151 m_ssaaTextureToTextureRenderTarget->create();
1152
1153 if (m_temporalAATexture) {
1154 m_temporalAATexture->setPixelSize(renderSize);
1155 m_temporalAATexture->create();
1156 }
1157 if (m_prevTempAATexture) {
1158 m_prevTempAATexture->setPixelSize(renderSize);
1159 m_prevTempAATexture->create();
1160 }
1161 if (m_temporalAARenderTarget)
1162 m_temporalAARenderTarget->create();
1163 }
1164 }
1165 } else if (m_aaIsDirty && rhi->backend() == QRhi::Metal) { // ### to avoid garbage upon enabling MSAA with macOS 10.14 (why is this needed?)
1166 m_texture->create();
1167 }
1168
1169 if (m_aaIsDirty)
1170 releaseAaDependentRhiResources();
1171 }
1172
1173 const QRhiTexture::Flags textureFlags = QRhiTexture::RenderTarget
1174 | QRhiTexture::UsedAsTransferSource; // transfer source is for progressive/temporal AA
1175 const QRhiTexture::Format textureFormat = layerTextureFormat(rhi, postProcessingNeeded);
1176
1177 if (!m_texture) {
1178 if (m_layer->viewCount >= 2)
1179 m_texture = rhi->newTextureArray(textureFormat, m_layer->viewCount, m_surfaceSize, 1, textureFlags);
1180 else
1181 m_texture = rhi->newTexture(textureFormat, m_surfaceSize, 1, textureFlags);
1182 m_texture->create();
1183 }
1184
1185 if (!m_ssaaTexture && m_layer->isSsaaEnabled()) {
1186 if (m_layer->viewCount >= 2)
1187 m_ssaaTexture = rhi->newTextureArray(textureFormat, m_layer->viewCount, renderSize, 1, textureFlags);
1188 else
1189 m_ssaaTexture = rhi->newTexture(textureFormat, renderSize, 1, textureFlags);
1190 m_ssaaTexture->create();
1191 }
1192
1193 if (m_timeBasedAA && !m_temporalAATexture) {
1194 m_temporalAATexture = rhi->newTexture(textureFormat, renderSize, 1, textureFlags);
1195 m_temporalAATexture->create();
1196 m_prevTempAATexture = rhi->newTexture(textureFormat, renderSize, 1, textureFlags);
1197 m_prevTempAATexture->create();
1198 }
1199
1200 // we need to re-render time-based AA not only when AA state changes, but also when resized
1201 if (m_aaIsDirty || layerSizeIsDirty)
1202 m_layer->tempAAPassIndex = m_layer->progAAPassIndex = 0;
1203
1204 if (m_aaIsDirty) {
1205 m_samples = 1;
1206 if (m_layer->antialiasingMode == QSSGRenderLayer::AAMode::MSAA) {
1207 if (rhi->isFeatureSupported(QRhi::MultisampleRenderBuffer)) {
1208 m_samples = qMax(1, int(m_layer->antialiasingQuality));
1209 // The Quick3D API exposes high level values such as
1210 // Medium, High, VeryHigh instead of direct sample
1211 // count values. Therefore, be nice and find a sample
1212 // count that's actually supported in case the one
1213 // associated by default is not.
1214 const QVector<int> supported = rhi->supportedSampleCounts(); // assumed to be sorted
1215 if (!supported.contains(m_samples)) {
1216 if (!supported.isEmpty()) {
1217 auto it = std::lower_bound(supported.cbegin(), supported.cend(), m_samples);
1218 m_samples = it == supported.cend() ? supported.last() : *it;
1219 } else {
1220 m_samples = 1;
1221 }
1222 }
1223 } else {
1224 static bool warned = false;
1225 if (!warned) {
1226 warned = true;
1227 qWarning("Multisample renderbuffers are not supported, disabling MSAA for Offscreen View3D");
1228 }
1229 }
1230 }
1231 }
1232
1233 if (m_layer->viewCount >= 2) {
1234 if (!m_multiViewDepthStencilBuffer) {
1235 const auto format = rhi->isTextureFormatSupported(QRhiTexture::D24S8) ? QRhiTexture::D24S8 : QRhiTexture::D32FS8;
1236 m_multiViewDepthStencilBuffer = rhi->newTextureArray(format, m_layer->viewCount, renderSize,
1237 m_samples, QRhiTexture::RenderTarget);
1238 m_multiViewDepthStencilBuffer->create();
1239 }
1240 } else {
1241 if (!m_depthStencilBuffer) {
1242 m_depthStencilBuffer = rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, renderSize, m_samples);
1243 m_depthStencilBuffer->create();
1244 }
1245 }
1246
1247 if (!m_textureRenderTarget) {
1248 QRhiTextureRenderTargetDescription rtDesc;
1249 QRhiColorAttachment att;
1250 if (m_samples > 1) {
1251 if (m_layer->viewCount >= 2) {
1252 m_msaaMultiViewRenderBuffer = rhi->newTextureArray(textureFormat, m_layer->viewCount, renderSize, m_samples, QRhiTexture::RenderTarget);
1253 m_msaaMultiViewRenderBuffer->create();
1254 att.setTexture(m_msaaMultiViewRenderBuffer);
1255 } else {
1256 if (!rhi->isFeatureSupported(QRhi::MultisampleTexture)) {
1257 // pass in the texture's format (which may be a floating point one!) as the preferred format hint
1258 m_msaaRenderBufferLegacy = rhi->newRenderBuffer(QRhiRenderBuffer::Color, renderSize, m_samples, {}, m_texture->format());
1259 m_msaaRenderBufferLegacy->create();
1260 att.setRenderBuffer(m_msaaRenderBufferLegacy);
1261 } else {
1262 // The texture-backed MSAA path has the benefit of being able to use
1263 // GL_EXT_multisampled_render_to_texture on OpenGL ES when supported (Mali
1264 // and Qualcomm GPUs typically), potentially giving significant performance
1265 // gains. Whereas with 3D APIs other than OpenGL there is often no
1266 // difference between QRhiRenderBuffer and QRhiTexture anyway.
1267 m_msaaRenderTexture = rhi->newTexture(textureFormat, renderSize, m_samples, QRhiTexture::RenderTarget);
1268 m_msaaRenderTexture->create();
1269 att.setTexture(m_msaaRenderTexture);
1270 }
1271 }
1272 att.setResolveTexture(m_texture);
1273 } else {
1274 if (m_layer->antialiasingMode == QSSGRenderLayer::AAMode::SSAA)
1275 att.setTexture(m_ssaaTexture);
1276 else
1277 att.setTexture(m_texture);
1278 }
1279 att.setMultiViewCount(m_layer->viewCount);
1280 rtDesc.setColorAttachments({ att });
1281 if (m_depthStencilBuffer)
1282 rtDesc.setDepthStencilBuffer(m_depthStencilBuffer);
1283 if (m_multiViewDepthStencilBuffer)
1284 rtDesc.setDepthTexture(m_multiViewDepthStencilBuffer);
1285
1286 m_textureRenderTarget = rhi->newTextureRenderTarget(rtDesc);
1287 m_textureRenderTarget->setName(QByteArrayLiteral("View3D"));
1288 m_textureRenderPassDescriptor = m_textureRenderTarget->newCompatibleRenderPassDescriptor();
1289 m_textureRenderTarget->setRenderPassDescriptor(m_textureRenderPassDescriptor);
1290 m_textureRenderTarget->create();
1291 }
1292
1293 if (!m_ssaaTextureToTextureRenderTarget && m_layer->antialiasingMode == QSSGRenderLayer::AAMode::SSAA) {
1294 QRhiColorAttachment att(m_texture);
1295 att.setMultiViewCount(m_layer->viewCount);
1296 m_ssaaTextureToTextureRenderTarget = rhi->newTextureRenderTarget(QRhiTextureRenderTargetDescription({ att }));
1297 m_ssaaTextureToTextureRenderTarget->setName(QByteArrayLiteral("SSAA texture"));
1298 m_ssaaTextureToTextureRenderPassDescriptor = m_ssaaTextureToTextureRenderTarget->newCompatibleRenderPassDescriptor();
1299 m_ssaaTextureToTextureRenderTarget->setRenderPassDescriptor(m_ssaaTextureToTextureRenderPassDescriptor);
1300 m_ssaaTextureToTextureRenderTarget->create();
1301 }
1302
1303 if (m_layer->firstEffect) {
1304 if (!m_effectSystem)
1305 m_effectSystem = new QSSGRhiEffectSystem(m_sgContext);
1306 m_effectSystem->setup(renderSize);
1307 } else if (m_effectSystem) {
1308 delete m_effectSystem;
1309 m_effectSystem = nullptr;
1310 }
1311
1312 if (m_timeBasedAA && !m_temporalAARenderTarget) {
1313 m_temporalAARenderTarget = rhi->newTextureRenderTarget({ m_temporalAATexture });
1314 m_temporalAARenderTarget->setName(QByteArrayLiteral("Temporal AA texture"));
1315 m_temporalAARenderPassDescriptor = m_temporalAARenderTarget->newCompatibleRenderPassDescriptor();
1316 m_temporalAARenderTarget->setRenderPassDescriptor(m_temporalAARenderPassDescriptor);
1317 m_temporalAARenderTarget->create();
1318 }
1319
1320 m_textureNeedsFlip = rhi->isYUpInFramebuffer();
1321 m_aaIsDirty = false;
1322 }
1323
1324 if (m_renderStats)
1325 m_renderStats->endSync(dumpRenderTimes());
1326
1327 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DSynchronizeFrame, quint64(m_surfaceSize.width()) | quint64(m_surfaceSize.height()) << 32, profilingId);
1328}
1329
1331{
1332 if (fboNode)
1333 fboNode->invalidatePending = true;
1334}
1335
1337{
1338 if (m_layer && m_layer->renderData) {
1339 if (const auto &mgr = m_layer->renderData->getShadowMapManager())
1340 mgr->releaseCachedResources();
1341 if (const auto &mgr = m_layer->renderData->getReflectionMapManager())
1342 mgr->releaseCachedResources();
1343 }
1344}
1345
1347{
1348 if (!m_layer || !m_layer->renderData)
1349 return std::nullopt;
1350
1351 QMutexLocker locker(&m_layer->renderedCamerasMutex);
1352
1353 if (m_layer->renderedCameras.isEmpty())
1354 return std::nullopt;
1355
1356 QMatrix4x4 globalTransform = m_layer->renderData->getGlobalTransform(*m_layer->renderedCameras[0]);
1357
1358 const QVector2D viewportSize(m_surfaceSize.width(), m_surfaceSize.height());
1359 const QVector2D position(float(pos.x()), float(pos.y()));
1360 const QRectF viewportRect(QPointF{}, QSizeF(m_surfaceSize));
1361
1362 // First invert the y so we are dealing with numbers in a normal coordinate space.
1363 // Second, move into our layer's coordinate space
1364 QVector2D correctCoords(position.x(), viewportSize.y() - position.y());
1365 QVector2D theLocalMouse = QSSGUtils::rect::toRectRelative(viewportRect, correctCoords);
1366 if ((theLocalMouse.x() < 0.0f || theLocalMouse.x() >= viewportSize.x() || theLocalMouse.y() < 0.0f
1367 || theLocalMouse.y() >= viewportSize.y()))
1368 return std::nullopt;
1369
1370 return m_layer->renderedCameras[0]->unproject(globalTransform, theLocalMouse, viewportRect);
1371}
1372
1373std::optional<QSSGRenderPickResult> QQuick3DSceneRenderer::syncPickClosestPoint(const QVector3D &center, float radiusSquared, QSSGRenderNode *node)
1374{
1375 if (!m_layer)
1376 return std::nullopt;
1377
1378 return QSSGRendererPrivate::syncPickClosestPoint(*m_sgContext,
1379 *m_layer,
1380 center, radiusSquared,
1381 node);
1382}
1383
1385{
1386 if (!m_layer)
1387 return QQuick3DSceneRenderer::PickResultList();
1388
1389 return QSSGRendererPrivate::syncPick(*m_sgContext,
1390 *m_layer,
1391 ray);
1392}
1393
1394QQuick3DSceneRenderer::PickResultList QQuick3DSceneRenderer::syncPickOne(const QSSGRenderRay &ray, QSSGRenderNode *node)
1395{
1396 if (!m_layer)
1397 return QQuick3DSceneRenderer::PickResultList();
1398
1399 return QSSGRendererPrivate::syncPick(*m_sgContext,
1400 *m_layer,
1401 ray,
1402 node);
1403}
1404
1406 QVarLengthArray<QSSGRenderNode *> subset)
1407{
1408 if (!m_layer)
1409 return QQuick3DSceneRenderer::PickResultList();
1410
1411 return QSSGRendererPrivate::syncPickSubset(*m_layer,
1412 *m_sgContext->bufferManager(),
1413 ray,
1414 subset);
1415}
1416
1418{
1419 if (!m_layer)
1420 return QQuick3DSceneRenderer::PickResultList();
1421
1422 return QSSGRendererPrivate::syncPickAll(*m_sgContext,
1423 *m_layer,
1424 ray);
1425}
1426
1428{
1429 if (!m_layer)
1430 return {};
1431
1432 return QSSGRendererPrivate::syncPickInFrustum(*m_sgContext, *m_layer, frustum);
1433}
1434
1436{
1437 QSSGRendererPrivate::setGlobalPickingEnabled(*m_sgContext->renderer(), isEnabled);
1438}
1439
1441{
1442 return m_renderStats;
1443}
1444
1445void QQuick3DRenderLayerHelpers::updateLayerNodeHelper(const QQuick3DViewport &view3D,
1446 const std::shared_ptr<QSSGRenderContextInterface>& rci,
1447 QSSGRenderLayer &layerNode,
1448 bool &aaIsDirty,
1449 bool &temporalIsDirty)
1450{
1451 QList<QSSGRenderGraphObject *> resourceLoaders; // empty list
1452
1453 QQuick3DSceneRenderer dummyRenderer(rci);
1454
1455 // Update the layer node properties
1456 dummyRenderer.updateLayerNode(layerNode, view3D, resourceLoaders);
1457
1458 aaIsDirty = dummyRenderer.m_aaIsDirty;
1459 temporalIsDirty = dummyRenderer.m_temporalIsDirty;
1460}
1461
1462void QQuick3DSceneRenderer::updateLayerNode(QSSGRenderLayer &layerNode,
1463 const QQuick3DViewport &view3D,
1464 const QList<QSSGRenderGraphObject *> &resourceLoaders)
1465{
1466 QQuick3DSceneEnvironment *environment = view3D.environment();
1467 const auto &effects = environment->effectList();
1468
1469 QSSGRenderLayer::AAMode aaMode = QSSGRenderLayer::AAMode(environment->antialiasingMode());
1470 if (aaMode != layerNode.antialiasingMode) {
1471 layerNode.antialiasingMode = aaMode;
1472 layerNode.progAAPassIndex = 0;
1473 m_aaIsDirty = true;
1474 }
1475 QSSGRenderLayer::AAQuality aaQuality = QSSGRenderLayer::AAQuality(environment->antialiasingQuality());
1476 if (aaQuality != layerNode.antialiasingQuality) {
1477 layerNode.antialiasingQuality = aaQuality;
1478 layerNode.ssaaMultiplier = QSSGRenderLayer::ssaaMultiplierForQuality(aaQuality);
1479 m_aaIsDirty = true;
1480 }
1481
1482 // NOTE: Temporal AA is disabled when MSAA is enabled.
1483 const bool temporalAARequested = environment->temporalAAEnabled();
1484 const bool wasTaaEnabled = layerNode.isTemporalAAEnabled();
1485 layerNode.temporalAAMode = temporalAARequested ? QSSGRenderLayer::TAAMode(environment->m_temporalAAMode + 1) // map the environment mode to the layer mode
1486 : QSSGRenderLayer::TAAMode::Off;
1487
1488 // If the state changed we need to reset the temporal AA pass index etc.
1489 if (wasTaaEnabled != layerNode.isTemporalAAEnabled()) {
1490 layerNode.tempAAPassIndex = 0;
1491 m_aaIsDirty = true;
1492 m_temporalIsDirty = true;
1493 }
1494
1495 layerNode.temporalAAStrength = environment->temporalAAStrength();
1496
1497 layerNode.specularAAEnabled = environment->specularAAEnabled();
1498
1499 layerNode.background = QSSGRenderLayer::Background(environment->backgroundMode());
1500 layerNode.clearColor = QVector3D(float(environment->clearColor().redF()),
1501 float(environment->clearColor().greenF()),
1502 float(environment->clearColor().blueF()));
1503
1504 layerNode.gridEnabled = environment->gridEnabled();
1505 layerNode.gridScale = environment->gridScale();
1506 layerNode.gridFlags = environment->gridFlags();
1507
1508 layerNode.aoStrength = environment->aoStrength();
1509 layerNode.aoDistance = environment->aoDistance();
1510 layerNode.aoSoftness = environment->aoSoftness();
1511 layerNode.aoEnabled = environment->aoEnabled();
1512 layerNode.aoBias = environment->aoBias();
1513 layerNode.aoSamplerate = environment->aoSampleRate();
1514 layerNode.aoDither = environment->aoDither();
1515
1516 // ### These images will not be registered anywhere
1517 if (environment->lightProbe()) {
1518 layerNode.lightProbe = environment->lightProbe()->getRenderImage();
1519 // FIXME: Band-aid. Need a proper solution where textureData is setting the format of the render node.
1520 if (auto texData = environment->lightProbe()->textureData();
1521 texData && texData->format() == QQuick3DTextureData::Format::RGBE8) {
1522 layerNode.lightProbe->m_format = QSSGRenderTextureFormat::Format::RGBE8;
1523 }
1524 } else
1525 layerNode.lightProbe = nullptr;
1526 if (view3D.environment()->skyBoxCubeMap())
1527 layerNode.skyBoxCubeMap = view3D.environment()->skyBoxCubeMap()->getRenderImage();
1528 else
1529 layerNode.skyBoxCubeMap = nullptr;
1530
1531 layerNode.skyMaterial = nullptr;
1532 if (auto skyMaterial = environment->skyMaterial())
1533 layerNode.skyMaterial = static_cast<QSSGRenderSkyMaterial *>(QQuick3DObjectPrivate::get(skyMaterial)->spatialNode);
1534
1535 layerNode.lightProbeSettings.probeExposure = environment->probeExposure();
1536 // Remap the probeHorizon to the expected Range
1537 layerNode.lightProbeSettings.probeHorizon = qMin(environment->probeHorizon() - 1.0f, -0.001f);
1538 layerNode.setProbeOrientation(environment->probeOrientation());
1539
1540 QQuick3DViewport::updateCameraForLayer(view3D, layerNode);
1541
1542 layerNode.layerFlags.setFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest, environment->depthTestEnabled());
1543 layerNode.layerFlags.setFlag(QSSGRenderLayer::LayerFlag::EnableDepthPrePass, environment->depthPrePassEnabled());
1544
1545 layerNode.tonemapMode = QQuick3DSceneRenderer::getTonemapMode(*environment);
1546 layerNode.skyboxBlurAmount = environment->skyboxBlurAmount();
1547 if (auto debugSettings = view3D.environment()->debugSettings()) {
1548 layerNode.debugMode = QSSGRenderLayer::MaterialDebugMode(debugSettings->materialOverride());
1549 layerNode.wireframeMode = debugSettings->wireframeEnabled();
1550 layerNode.drawDirectionalLightShadowBoxes = debugSettings->drawDirectionalLightShadowBoxes();
1551 layerNode.drawPointLightShadowBoxes = debugSettings->drawPointLightShadowBoxes();
1552 layerNode.drawShadowCastingBounds = debugSettings->drawShadowCastingBounds();
1553 layerNode.drawShadowReceivingBounds = debugSettings->drawShadowReceivingBounds();
1554 layerNode.drawCascades = debugSettings->drawCascades();
1555 layerNode.drawSceneCascadeIntersection = debugSettings->drawSceneCascadeIntersection();
1556 layerNode.disableShadowCameraUpdate = debugSettings->disableShadowCameraUpdate();
1557 layerNode.drawCulledObjects = debugSettings->drawCulledObjects();
1558 layerNode.drawLevelsOfDetail = debugSettings->drawLevelsOfDetail();
1559 } else {
1560 layerNode.debugMode = QSSGRenderLayer::MaterialDebugMode::None;
1561 layerNode.wireframeMode = false;
1562 layerNode.drawLevelsOfDetail = false;
1563 }
1564
1565 if (environment->fog() && environment->fog()->isEnabled()) {
1566 layerNode.fog.enabled = true;
1567 const QQuick3DFog *fog = environment->fog();
1568 layerNode.fog.color = QSSGUtils::color::sRGBToLinear(fog->color()).toVector3D();
1569 layerNode.fog.density = fog->density();
1570 layerNode.fog.depthEnabled = fog->isDepthEnabled();
1571 layerNode.fog.depthBegin = fog->depthNear();
1572 layerNode.fog.depthEnd = fog->depthFar();
1573 layerNode.fog.depthCurve = fog->depthCurve();
1574 layerNode.fog.heightEnabled = fog->isHeightEnabled();
1575 layerNode.fog.heightMin = fog->leastIntenseY();
1576 layerNode.fog.heightMax = fog->mostIntenseY();
1577 layerNode.fog.heightCurve = fog->heightCurve();
1578 layerNode.fog.transmitEnabled = fog->isTransmitEnabled();
1579 layerNode.fog.transmitCurve = fog->transmitCurve();
1580 } else {
1581 layerNode.fog.enabled = false;
1582 }
1583 const auto method = static_cast<QSSGRenderLayer::OITMethod>(environment->oitMethod());
1584 layerNode.oitMethodDirty = method != layerNode.oitMethod;
1585 layerNode.oitMethod = method;
1586
1587 // Effects need to be rendered in reverse order as described in the file.
1588 // NOTE: We only build up the list here, don't do anything that depends
1589 // on the collected layer state yet. See sync() for that.
1590 layerNode.firstEffect = nullptr; // We reset the linked list
1591 auto rit = effects.crbegin();
1592 const auto rend = effects.crend();
1593 for (; rit != rend; ++rit) {
1594 QQuick3DObjectPrivate *p = QQuick3DObjectPrivate::get(*rit);
1595 QSSGRenderEffect *effectNode = static_cast<QSSGRenderEffect *>(p->spatialNode);
1596 if (effectNode) {
1597 if (layerNode.hasEffect(effectNode)) {
1598 qWarning() << "Duplicate effect found, skipping!";
1599 } else {
1600 effectNode->className = (*rit)->metaObject()->className(); //### persistent, but still icky to store a const char* returned from a function
1601 layerNode.addEffect(*effectNode);
1602 }
1603 }
1604 }
1605
1606 const bool hasEffects = (layerNode.firstEffect != nullptr);
1607
1608 const auto renderMode = view3D.renderMode();
1609
1610 const bool progressiveAA = layerNode.isProgressiveAAEnabled();
1611 const bool temporalAA = layerNode.isTemporalAAEnabled();
1612 const bool superSamplingAA = layerNode.isSsaaEnabled();
1613 m_timeBasedAA = progressiveAA || temporalAA;
1614 m_postProcessingStack = hasEffects || m_timeBasedAA || superSamplingAA;
1615 m_useFBO = renderMode == QQuick3DViewport::RenderMode::Offscreen ||
1616 ((renderMode == QQuick3DViewport::RenderMode::Underlay || renderMode == QQuick3DViewport::RenderMode::Overlay)
1617 && m_postProcessingStack);
1618
1619 // Update the view count
1620
1621 // NOTE: If we're rendering to an FBO, the view count is more than 1, and the View3D is not an XR view instance,
1622 // we need to force the view count to 1 (The only time this should be the case is when embedding View3D(s)
1623 // in XR with multiview enabled).
1624 // Also, note that embedding View3D(s) in XR with multiview enabled only works if those View3D(s) are
1625 // being rendered through a FBO.
1626 if (m_useFBO && (layerNode.viewCount > 1) && !view3D.isXrViewInstance())
1627 layerNode.viewCount = 1;
1628
1629 // ResourceLoaders
1630 layerNode.resourceLoaders.clear();
1631 layerNode.resourceLoaders = resourceLoaders;
1632
1633 layerNode.renderOverrides = QSSGRenderLayer::RenderOverridesT(view3D.renderOverrides().toInt());
1634}
1635
1636void QQuick3DSceneRenderer::removeNodeFromLayer(QSSGRenderNode *node)
1637{
1638 if (!m_layer)
1639 return;
1640
1641 m_layer->removeChild(*node);
1642}
1643
1644void QQuick3DSceneRenderer::maybeSetupLightmapBaking(QQuick3DViewport *view3D)
1645{
1646 if (m_layer->renderData && m_layer->renderData->lightmapBaker)
1647 return;
1648
1649 // Check if we have interactive bake requested or if we are coming in here the second
1650 // time from cmd line request (needs to wait a frame before starting to bake).
1651 bool bakeRequested = false;
1652 bool denoiseRequested = false;
1653 bool fromCmd = false;
1654 QQuick3DLightmapBaker *lightmapBaker = view3D->maybeLightmapBaker();
1655 if (lightmapBaker && (lightmapBaker->m_bakingRequested || lightmapBaker->m_denoisingRequested)) {
1656 bakeRequested = std::exchange(lightmapBaker->m_bakingRequested, false);
1657 denoiseRequested = std::exchange(lightmapBaker->m_denoisingRequested, false);
1658 } else {
1659 bakeRequested = m_lightmapBakingFromCmdRequested;
1660 denoiseRequested = m_lightmapDenoisingFromCmdRequested;
1661 fromCmd = bakeRequested;
1662 }
1663
1664 // Start the bake (we should have a valid layer render data at this point).
1665 if (bakeRequested || denoiseRequested) {
1666 QSSGLightmapBaker::Context ctx;
1667 ctx.settings.bakeRequested = bakeRequested;
1668 ctx.settings.denoiseRequested = denoiseRequested;
1669 ctx.settings.quitWhenFinished = fromCmd;
1670
1671 // We want the frontend callback in the case that a QQuick3DLightmapBaker is present
1672 if (lightmapBaker) {
1673 QQuick3DLightmapBaker::Callback qq3dCallback = lightmapBaker->m_callback;
1674 QQuick3DLightmapBaker::BakingControl *qq3dBakingControl = lightmapBaker->m_bakingControl;
1675 QSSGLightmapper::Callback callback =
1676 [qq3dCallback,
1677 qq3dBakingControl](const QVariantMap &payload,
1678 QSSGLightmapper::BakingControl *qssgBakingControl) {
1679 qq3dCallback(payload, qq3dBakingControl);
1680
1681 if (qq3dBakingControl->isCancelled() && !qssgBakingControl->cancelled)
1682 qssgBakingControl->cancelled = true;
1683 };
1684 ctx.callbacks.lightmapBakingOutput = callback;
1685 }
1686
1687 // Both the QQuick3DLightmapBaker and cmd / env variant needs this
1688 ctx.callbacks.triggerNewFrame = [view3D](bool releaseResources) {
1689 if (releaseResources) {
1690 QMetaObject::invokeMethod(view3D->window(),
1691 &QQuickWindow::releaseResources,
1692 Qt::QueuedConnection);
1693 }
1694 QMetaObject::invokeMethod(view3D, &QQuick3DViewport::update, Qt::QueuedConnection);
1695 };
1696 ctx.callbacks.setCurrentlyBaking = [this](bool value) {
1697 m_sgContext->bufferManager()->setCurrentlyLightmapBaking(value);
1698 };
1699
1700 ctx.env.rhiCtx = m_sgContext->rhiContext().get();
1701 ctx.env.renderer = m_sgContext->renderer().get();
1702 ctx.env.lmOptions = lmOptions;
1703 m_layer->renderData->initializeLightmapBaking(ctx);
1704
1705 } else {
1706 // Check cmd line and env flags for request
1707 static bool flagsChecked = false;
1708 if (flagsChecked)
1709 return;
1710 flagsChecked = true;
1711
1712 auto isLightmapFlagSet = [](const QString &flag, const char *envVar) {
1713 return QCoreApplication::arguments().contains(flag)
1714 || qEnvironmentVariableIntValue(envVar);
1715 };
1716
1717 m_lightmapBakingFromCmdRequested = isLightmapFlagSet(QStringLiteral("--bake-lightmaps"), "QT_QUICK3D_BAKE_LIGHTMAPS");
1718 m_lightmapDenoisingFromCmdRequested = isLightmapFlagSet(QStringLiteral("--denoise-lightmaps"), "QT_QUICK3D_DENOISE_LIGHTMAPS");
1719
1720 if (m_lightmapBakingFromCmdRequested || m_lightmapDenoisingFromCmdRequested) {
1721 // Delay one frame so the render data is initialized
1722 QMetaObject::invokeMethod(view3D, &QQuick3DViewport::update, Qt::QueuedConnection);
1723 }
1724 }
1725}
1726
1727void QQuick3DSceneRenderer::addNodeToLayer(QSSGRenderNode *node)
1728{
1729 if (!m_layer)
1730 return;
1731
1732 m_layer->addChild(*node);
1733}
1734
1735QSGRenderNode::StateFlags QQuick3DSGRenderNode::changedStates() const
1736{
1737 return BlendState | StencilState | DepthState | ScissorState | ColorState | CullState | ViewportState | RenderTargetState;
1738}
1739
1740namespace {
1741inline QRect convertQtRectToGLViewport(const QRectF &rect, const QSize surfaceSize)
1742{
1743 const int x = int(rect.x());
1744 const int y = surfaceSize.height() - (int(rect.y()) + int(rect.height()));
1745 const int width = int(rect.width());
1746 const int height = int(rect.height());
1747 return QRect(x, y, width, height);
1748}
1749
1750inline void queryMainRenderPassDescriptorAndCommandBuffer(QQuickWindow *window, QSSGRhiContext *rhiCtx)
1751{
1752 if (rhiCtx->isValid()) {
1753 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
1754 // Query from the rif because that is available in the sync
1755 // phase (updatePaintNode) already. QSGDefaultRenderContext's
1756 // copies of the rp and cb are not there until the render
1757 // phase of the scenegraph.
1758 int sampleCount = 1;
1759 int viewCount = 1;
1760 QRhiSwapChain *swapchain = window->swapChain();
1761 if (swapchain) {
1762 rhiCtxD->setMainRenderPassDescriptor(swapchain->renderPassDescriptor());
1763 rhiCtxD->setCommandBuffer(swapchain->currentFrameCommandBuffer());
1764 rhiCtxD->setRenderTarget(swapchain->currentFrameRenderTarget());
1765 sampleCount = swapchain->sampleCount();
1766 } else {
1767 QSGRendererInterface *rif = window->rendererInterface();
1768 // no swapchain when using a QQuickRenderControl (redirecting to a texture etc.)
1769 QRhiCommandBuffer *cb = static_cast<QRhiCommandBuffer *>(
1770 rif->getResource(window, QSGRendererInterface::RhiRedirectCommandBuffer));
1771 QRhiTextureRenderTarget *rt = static_cast<QRhiTextureRenderTarget *>(
1772 rif->getResource(window, QSGRendererInterface::RhiRedirectRenderTarget));
1773 if (cb && rt) {
1774 rhiCtxD->setMainRenderPassDescriptor(rt->renderPassDescriptor());
1775 rhiCtxD->setCommandBuffer(cb);
1776 rhiCtxD->setRenderTarget(rt);
1777 const auto descr = rt->description();
1778 const QRhiColorAttachment *color0 = descr.cbeginColorAttachments();
1779 if (color0 && color0->texture()) {
1780 sampleCount = color0->texture()->sampleCount();
1781 if (rt->resourceType() == QRhiResource::TextureRenderTarget) {
1782 const QRhiTextureRenderTargetDescription desc = static_cast<QRhiTextureRenderTarget *>(rt)->description();
1783 for (auto it = desc.cbeginColorAttachments(), end = desc.cendColorAttachments(); it != end; ++it) {
1784 if (it->multiViewCount() >= 2) {
1785 viewCount = it->multiViewCount();
1786 break;
1787 }
1788 }
1789 }
1790 }
1791 } else {
1792 qWarning("Neither swapchain nor redirected command buffer and render target are available.");
1793 }
1794 }
1795
1796 // MSAA is out of our control on this path: it is up to the
1797 // QQuickWindow and the scenegraph to set up the swapchain based on the
1798 // QSurfaceFormat's samples(). The only thing we need to do here is to
1799 // pass the sample count to the renderer because it is needed when
1800 // creating graphics pipelines.
1801 rhiCtxD->setMainPassSampleCount(sampleCount);
1802
1803 // The "direct renderer", i.e. the Underlay and Overlay modes are the
1804 // only ones that support multiview rendering. This becomes active when
1805 // the QQuickWindow is redirected into a texture array, typically with
1806 // an array size of 2 (2 views, for the left and right eye). Otherwise,
1807 // when targeting a window or redirected to a 2D texture, this is not
1808 // applicable and the view count is 1.
1809 rhiCtxD->setMainPassViewCount(viewCount);
1810 }
1811}
1812
1813// The alternative to queryMainRenderPassDescriptorAndCommandBuffer()
1814// specifically for the Inline render mode when there is a QSGRenderNode.
1815inline void queryInlineRenderPassDescriptorAndCommandBuffer(QSGRenderNode *node, QSSGRhiContext *rhiCtx)
1816{
1817 QSGRenderNodePrivate *d = QSGRenderNodePrivate::get(node);
1818 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
1819 rhiCtxD->setMainRenderPassDescriptor(d->m_rt.rpDesc);
1820 rhiCtxD->setCommandBuffer(d->m_rt.cb);
1821 rhiCtxD->setRenderTarget(d->m_rt.rt);
1822 rhiCtxD->setMainPassSampleCount(d->m_rt.rt->sampleCount());
1823 rhiCtxD->setMainPassViewCount(1);
1824}
1825
1826} // namespace
1827
1828QQuick3DSGRenderNode::~QQuick3DSGRenderNode()
1829{
1830 delete renderer;
1831}
1832
1833void QQuick3DSGRenderNode::prepare()
1834{
1835 // this is outside the main renderpass
1836
1837 if (!renderer->m_sgContext->rhiContext()->isValid())
1838 return;
1839 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DPrepareFrame);
1840 if (renderer->renderStats())
1841 renderer->renderStats()->startRenderPrepare();
1842
1843 queryInlineRenderPassDescriptorAndCommandBuffer(this, renderer->m_sgContext->rhiContext().get());
1844
1845 qreal dpr = window->effectiveDevicePixelRatio();
1846 const QSizeF itemSize = renderer->surfaceSize() / dpr;
1847 QRectF viewport = matrix()->mapRect(QRectF(QPoint(0, 0), itemSize));
1848 viewport = QRectF(viewport.topLeft() * dpr, viewport.size() * dpr);
1849 const QRect vp = convertQtRectToGLViewport(viewport, window->size() * dpr);
1850
1851 Q_TRACE_SCOPE(QSSG_prepareFrame, vp.width(), vp.height());
1852
1854 renderer->rhiPrepare(vp, dpr);
1855 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DPrepareFrame, quint64(vp.width()) | quint64(vp.height()) << 32, renderer->profilingId);
1856 if (renderer->renderStats())
1857 renderer->renderStats()->endRenderPrepare();
1858}
1859
1860void QQuick3DSGRenderNode::render(const QSGRenderNode::RenderState *state)
1861{
1862 Q_UNUSED(state);
1863
1864 const auto &rhiContext = renderer->m_sgContext->rhiContext();
1865
1866 if (rhiContext->isValid()) {
1867 if (renderer->renderStats())
1868 renderer->renderStats()->startRender();
1869 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderFrame);
1870 Q_TRACE_SCOPE(QSSG_renderFrame, 0, 0);
1871
1872 queryInlineRenderPassDescriptorAndCommandBuffer(this, renderer->m_sgContext->rhiContext().get());
1873
1875 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderFrame,
1876 STAT_PAYLOAD(QSSGRhiContextStats::get(*rhiContext)), renderer->profilingId);
1878 if (renderer->renderStats())
1879 renderer->renderStats()->endRender(dumpRenderTimes());
1880 }
1881}
1882
1883void QQuick3DSGRenderNode::releaseResources()
1884{
1885}
1886
1887QSGRenderNode::RenderingFlags QQuick3DSGRenderNode::flags() const
1888{
1889 // don't want begin/endExternal() to be called by Quick
1890 return NoExternalRendering;
1891}
1892
1893QQuick3DSGDirectRenderer::QQuick3DSGDirectRenderer(QQuick3DSceneRenderer *renderer, QQuickWindow *window, QQuick3DSGDirectRenderer::QQuick3DSGDirectRendererMode mode)
1894 : m_renderer(renderer)
1895 , m_window(window)
1896{
1897 if (QSGRendererInterface::isApiRhiBased(window->rendererInterface()->graphicsApi())) {
1898 connect(window, &QQuickWindow::beforeRendering, this, &QQuick3DSGDirectRenderer::prepare, Qt::DirectConnection);
1899 if (mode == Underlay)
1900 connect(window, &QQuickWindow::beforeRenderPassRecording, this, &QQuick3DSGDirectRenderer::render, Qt::DirectConnection);
1901 else
1902 connect(window, &QQuickWindow::afterRenderPassRecording, this, &QQuick3DSGDirectRenderer::render, Qt::DirectConnection);
1903 }
1904}
1905
1907{
1908 delete m_renderer;
1909}
1910
1911void QQuick3DSGDirectRenderer::setViewport(const QRectF &viewport)
1912{
1913 m_viewport = viewport;
1914}
1915
1917{
1918 if (m_isVisible == visible)
1919 return;
1920 m_isVisible = visible;
1921 m_window->update();
1922}
1923
1925{
1926 renderPending = true;
1927 requestFullUpdate(m_window);
1928}
1929
1931{
1932 // This is called from the QQuick3DViewport's updatePaintNode(), before
1933 // QQuick3DSceneRenderer::synchronize(). It is essential to query things
1934 // such as the view count already here, so that synchronize() can rely on
1935 // mainPassViewCount() for instance. prepare() is too late as that is only
1936 // called on beforeRendering (so after the scenegraph sync phase).
1937 if (m_renderer->m_sgContext->rhiContext()->isValid())
1938 queryMainRenderPassDescriptorAndCommandBuffer(m_window, m_renderer->m_sgContext->rhiContext().get());
1939}
1940
1941void QQuick3DSGDirectRenderer::prepare()
1942{
1943 if (!m_isVisible || !m_renderer)
1944 return;
1945
1946 if (m_renderer->m_sgContext->rhiContext()->isValid()) {
1947 // this is outside the main renderpass
1948 if (m_renderer->m_postProcessingStack) {
1949 if (renderPending) {
1950 renderPending = false;
1951 m_rhiTexture = m_renderer->renderToRhiTexture(m_window);
1952 // Set up the main render target again, e.g. the postprocessing
1953 // stack could have clobbered some settings such as the sample count.
1954 queryMainRenderPassDescriptorAndCommandBuffer(m_window, m_renderer->m_sgContext->rhiContext().get());
1955 const auto &quadRenderer = m_renderer->m_sgContext->renderer()->rhiQuadRenderer();
1956 quadRenderer->prepareQuad(m_renderer->m_sgContext->rhiContext().get(), nullptr);
1957 if (m_renderer->m_requestedFramesCount > 0) {
1959 m_renderer->m_requestedFramesCount--;
1960 }
1961 }
1962 }
1963 else
1964 {
1965 QQuick3DRenderStats *renderStats = m_renderer->renderStats();
1966 if (renderStats)
1967 renderStats->startRenderPrepare();
1968
1969 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DPrepareFrame);
1970 queryMainRenderPassDescriptorAndCommandBuffer(m_window, m_renderer->m_sgContext->rhiContext().get());
1971 const QRect vp = convertQtRectToGLViewport(m_viewport, m_window->size() * m_window->effectiveDevicePixelRatio());
1972
1973 Q_TRACE_SCOPE(QSSG_prepareFrame, vp.width(), vp.height());
1974 m_renderer->beginFrame();
1975 m_renderer->rhiPrepare(vp, m_window->effectiveDevicePixelRatio());
1976 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DPrepareFrame, quint64(vp.width()) | quint64(vp.height()) << 32, m_renderer->profilingId);
1977
1978 if (renderStats)
1979 renderStats->endRenderPrepare();
1980 }
1981 }
1982}
1983
1984void QQuick3DSGDirectRenderer::render()
1985{
1986 if (!m_isVisible || !m_renderer)
1987 return;
1988
1989 const auto &rhiContext = m_renderer->m_sgContext->rhiContext();
1990
1991 if (rhiContext->isValid()) {
1992 // the command buffer is recording the main renderpass at this point
1993
1994 // No m_window->beginExternalCommands() must be done here. When the
1995 // renderer is using the same
1996 // QRhi/QRhiCommandBuffer/QRhiRenderPassDescriptor as the Qt Quick
1997 // scenegraph, there is no difference from the RHI's perspective. There are
1998 // no external (native) commands here.
1999
2000 // Requery the command buffer and co. since Offscreen mode View3Ds may
2001 // have altered these on the context.
2002 if (m_renderer->m_postProcessingStack) {
2003 if (m_rhiTexture) {
2004 queryMainRenderPassDescriptorAndCommandBuffer(m_window, rhiContext.get());
2005 auto rhiCtx = m_renderer->m_sgContext->rhiContext().get();
2006 const auto &renderer = m_renderer->m_sgContext->renderer();
2007 QRhiCommandBuffer *cb = rhiContext->commandBuffer();
2008 cb->debugMarkBegin(QByteArrayLiteral("Post-processing result to main rt"));
2009
2010 // Instead of passing in a flip flag we choose to rely on qsb's
2011 // per-target compilation mode in the fragment shader. (it does UV
2012 // flipping based on QSHADER_ macros) This is just better for
2013 // performance and the shaders are very simple so introducing a
2014 // uniform block and branching dynamically would be an overkill.
2015 QRect vp = convertQtRectToGLViewport(m_viewport, m_window->size() * m_window->effectiveDevicePixelRatio());
2016
2017 const auto &shaderCache = m_renderer->m_sgContext->shaderCache();
2018 const auto &shaderPipeline = shaderCache->getBuiltInRhiShaders().getRhiSimpleQuadShader(m_renderer->m_layer->viewCount);
2019
2020 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
2021 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge });
2022 QSSGRhiShaderResourceBindingList bindings;
2023 bindings.addTexture(0, QRhiShaderResourceBinding::FragmentStage, m_rhiTexture, sampler);
2024 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiContext.get());
2025 QRhiShaderResourceBindings *srb = rhiCtxD->srb(bindings);
2026
2027 QSSGRhiGraphicsPipelineState ps;
2028 ps.viewport = QRhiViewport(float(vp.x()), float(vp.y()), float(vp.width()), float(vp.height()));
2029 ps.samples = rhiCtx->mainPassSampleCount();
2030 ps.viewCount = m_renderer->m_layer->viewCount;
2031 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(ps, shaderPipeline.get());
2032 renderer->rhiQuadRenderer()->recordRenderQuad(rhiCtx, &ps, srb, rhiCtx->mainRenderPassDescriptor(), QSSGRhiQuadRenderer::UvCoords | QSSGRhiQuadRenderer::PremulBlend);
2033 cb->debugMarkEnd();
2034 }
2035 }
2036 else
2037 {
2038 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderFrame);
2039 Q_TRACE_SCOPE(QSSG_renderFrame, 0, 0);
2040 if (m_renderer->renderStats())
2041 m_renderer->renderStats()->startRender();
2042
2043 queryMainRenderPassDescriptorAndCommandBuffer(m_window, rhiContext.get());
2044
2045 m_renderer->rhiRender();
2046
2047 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderFrame,
2048 STAT_PAYLOAD(QSSGRhiContextStats::get(*rhiContext)),
2049 m_renderer->profilingId);
2050 m_renderer->endFrame();
2051
2052 if (m_renderer->renderStats())
2053 m_renderer->renderStats()->endRender(dumpRenderTimes());
2054 }
2055 }
2056}
2057
2058QT_END_NAMESPACE
void setViewport(const QRectF &viewport)
void render(const RenderState *state) override
This function is called by the renderer and should paint this node with directly invoking commands vi...
void releaseResources() override
This function is called when all custom graphics resources allocated by this node have to be freed im...
RenderingFlags flags() const override
void prepare() override
Called from the frame preparation phase.
QQuick3DSceneRenderer * renderer
StateFlags changedStates() const override
This function should return a mask where each bit represents graphics states changed by the \l render...
PickResultList syncPick(const QSSGRenderRay &ray)
QQuick3DSceneRenderer(const std::shared_ptr< QSSGRenderContextInterface > &rci)
void rhiPrepare(const QRect &viewport, qreal displayPixelRatio)
PickResultList syncPickSubset(const QSSGRenderRay &ray, QVarLengthArray< QSSGRenderNode * > subset)
void synchronize(QQuick3DViewport *view3D, const QSize &size, float dpr)
std::optional< QSSGRenderRay > getRayFromViewportPos(const QPointF &pos)
PickResultList syncPickAll(const QSSGRenderRay &ray)
void setGlobalPickingEnabled(bool isEnabled)
QQuick3DRenderStats * renderStats()
QList< const QSSGRenderNode * > syncPickInFrustum(const QSSGFrustum &frustum)
QQuick3DSceneRenderer * renderer
QSGTexture * texture() const override
Returns a pointer to the texture object.
void preprocess() override
Override this function to do processing on the node before it is rendered.
Combined button and popup list for selecting options.
Q_TRACE_POINT(qtcore, QCoreApplication_postEvent_exit)
Q_TRACE_POINT(qtcore, QFactoryLoader_update, const QString &fileName)
Q_TRACE_POINT(qtquick3d, QSSG_renderFrame_entry, int width, int height)
static QSSGRenderUserPassBase::ExecutionStage declaredExecutionStage(const QQuick3DObject *pass)
static void bfs(In *inExtension, QList< Out * > &outList)
static const QVector2D s_ProgressiveAABlendFactors[QSSGLayerRenderData::MAX_AA_LEVELS]
static QVector3D tonemapRgb(const QVector3D &c, QQuick3DSceneEnvironment::QQuick3DEnvironmentTonemapModes tonemapMode)
static bool dumpRenderTimes()
Q_TRACE_POINT(qtquick3d, QSSG_synchronize_entry, QQuick3DViewport *view3D, const QSize &size, float dpr)
static const QVector2D s_TemporalAABlendFactors
static void requestFullUpdate(QQuickWindow *window)