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
qsgrenderloop.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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
7#include <private/qquickanimatorcontroller_p.h>
8
9#include <QtCore/QCoreApplication>
10#include <QtCore/QElapsedTimer>
11#include <QtCore/QLibraryInfo>
12#include <QtCore/private/qabstractanimation_p.h>
13
14#include <QtGui/QOffscreenSurface>
15#include <QtGui/private/qguiapplication_p.h>
16#include <qpa/qplatformintegration.h>
17#include <QPlatformSurfaceEvent>
18
19#include <QtQml/private/qqmlglobal_p.h>
20
21#include <QtQuick/QQuickWindow>
22#include <QtQuick/private/qquickwindow_p.h>
23#include <QtQuick/private/qquickitem_p.h>
24#include <QtQuick/private/qsgcontext_p.h>
25#include <QtQuick/private/qsgrenderer_p.h>
26#include <private/qquickprofiler_p.h>
27#include <qtquick_tracepoints_p.h>
28
29#include <private/qsgrhishadereffectnode_p.h>
30
31#include <private/qsgdefaultrendercontext_p.h>
32
33#ifdef Q_OS_WIN
34#include <QtCore/qt_windows.h>
35#endif
36
38
39extern bool qsg_useConsistentTiming();
40
41#define ENABLE_DEFAULT_BACKEND
42
43Q_TRACE_POINT(qtquick, QSG_renderWindow_entry)
44Q_TRACE_POINT(qtquick, QSG_renderWindow_exit)
45Q_TRACE_POINT(qtquick, QSG_polishItems_entry)
46Q_TRACE_POINT(qtquick, QSG_polishItems_exit)
47Q_TRACE_POINT(qtquick, QSG_sync_entry)
48Q_TRACE_POINT(qtquick, QSG_sync_exit)
49Q_TRACE_POINT(qtquick, QSG_render_entry)
50Q_TRACE_POINT(qtquick, QSG_render_exit)
51Q_TRACE_POINT(qtquick, QSG_swap_entry)
52Q_TRACE_POINT(qtquick, QSG_swap_exit)
53
54
55/*
56 - Uses one QRhi per window. (and so each window has its own QOpenGLContext or ID3D11Device(Context) etc.)
57 - Animations are advanced using the standard timer (no custom animation
58 driver is installed), so QML animations run as expected even when vsync
59 throttling is broken.
60 */
61
62DEFINE_BOOL_CONFIG_OPTION(qmlNoThreadedRenderer, QML_BAD_GUI_RENDER_LOOP);
63DEFINE_BOOL_CONFIG_OPTION(qmlForceThreadedRenderer, QML_FORCE_THREADED_RENDERER); // Might trigger graphics driver threading bugs, use at own risk
64
65QSGRenderLoop *QSGRenderLoop::s_instance = nullptr;
66
67QSGRenderLoop::~QSGRenderLoop()
68{
69}
70
71void QSGRenderLoop::cleanup()
72{
73 if (!s_instance)
74 return;
75 for (QQuickWindow *w : s_instance->windows()) {
76 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(w);
77 if (wd->windowManager == s_instance) {
78 s_instance->windowDestroyed(w);
79 wd->windowManager = nullptr;
80 }
81 }
82 delete s_instance;
83 s_instance = nullptr;
84}
85
86QSurface::SurfaceType QSGRenderLoop::windowSurfaceType() const
87{
89 return QSGRhiSupport::instance()->windowSurfaceType();
90#else
91 return QSurface::RasterSurface;
92#endif
93}
94
95void QSGRenderLoop::postJob(QQuickWindow *window, QRunnable *job)
96{
97 Q_ASSERT(job);
99 Q_ASSERT(window);
100 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
101 if (cd->rhi)
102 cd->rhi->makeThreadLocalNativeContextCurrent();
103 job->run();
104#else
105 Q_UNUSED(window);
106 job->run();
107#endif
108 delete job;
109}
110
113{
115public:
118
119 void show(QQuickWindow *window) override;
120 void hide(QQuickWindow *window) override;
121
122 void windowDestroyed(QQuickWindow *window) override;
123
124 void renderWindow(QQuickWindow *window);
125 void exposureChanged(QQuickWindow *window) override;
126 QImage grab(QQuickWindow *window) override;
127
128 void maybeUpdate(QQuickWindow *window) override;
129 void update(QQuickWindow *window) override { maybeUpdate(window); } // identical for this implementation.
130 void handleUpdateRequest(QQuickWindow *) override;
131
132 void releaseResources(QQuickWindow *) override;
133
134 QAnimationDriver *animationDriver() const override { return nullptr; }
135
136 QSGContext *sceneGraphContext() const override;
137 QSGRenderContext *createRenderContext(QSGContext *) const override;
138
139 void releaseSwapchain(QQuickWindow *window);
142
143 bool eventFilter(QObject *watched, QEvent *event) override;
144
145 struct WindowData {
147 : updatePending(false),
148 rhiDeviceLost(false),
149 rhiDoomed(false)
150 { }
151 QRhi *rhi = nullptr;
152 bool ownRhi = true;
153 QSGRenderContext *rc = nullptr;
155 int sampleCount = 1;
158 bool rhiDoomed : 1;
159 };
160
161 bool ensureRhi(QQuickWindow *window, WindowData &data);
162
164
165 QOffscreenSurface *offscreenSurface = nullptr;
166 QSGContext *sg;
168
169 bool m_inPolish = false;
170
172};
173#endif
174
175QSGRenderLoop *QSGRenderLoop::instance()
176{
177 if (!s_instance) {
178
179 QSGRhiSupport::checkEnvQSgInfo();
180
181 s_instance = QSGContext::createWindowManager();
183 if (!s_instance) {
184 QSGRhiSupport *rhiSupport = QSGRhiSupport::instance();
185
186 QSGRenderLoopType loopType;
187 if (rhiSupport->rhiBackend() != QRhi::OpenGLES2) {
188 loopType = ThreadedRenderLoop;
189 } else {
190 if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
191 loopType = ThreadedRenderLoop;
192 else
193 loopType = BasicRenderLoop;
194 }
195
196 switch (rhiSupport->rhiBackend()) {
197 case QRhi::Null:
198 loopType = BasicRenderLoop;
199 break;
200
201 case QRhi::D3D11:
202 // The threaded loop's model may not be suitable for DXGI
203 // due to the possibility of having the main thread (with
204 // the Windows message pump) blocked while issuing a
205 // Present on the render thread. However, according to the
206 // docs this can be a problem for fullscreen swapchains
207 // only. So leave threaded enabled by default for now and
208 // revisit later if there are problems.
209 break;
210
211 default:
212 break;
213 }
214
215 // The environment variables can always override. This is good
216 // because in some situations it makes perfect sense to try out a
217 // render loop that is otherwise disabled by default.
218
219 if (qmlNoThreadedRenderer())
220 loopType = BasicRenderLoop;
221 else if (qmlForceThreadedRenderer())
222 loopType = ThreadedRenderLoop;
223
224 if (Q_UNLIKELY(qEnvironmentVariableIsSet("QSG_RENDER_LOOP"))) {
225 const QByteArray loopName = qgetenv("QSG_RENDER_LOOP");
226 if (loopName == "windows") {
227 qWarning("The 'windows' render loop is no longer supported. Using 'basic' instead.");
228 loopType = BasicRenderLoop;
229 } else if (loopName == "basic") {
230 loopType = BasicRenderLoop;
231 } else if (loopName == "threaded") {
232 loopType = ThreadedRenderLoop;
233 }
234 }
235
236 switch (loopType) {
237#if QT_CONFIG(thread)
238 case ThreadedRenderLoop:
239 qCDebug(QSG_LOG_INFO, "threaded render loop");
240 s_instance = new QSGThreadedRenderLoop();
241 break;
242#endif
243 default:
244 qCDebug(QSG_LOG_INFO, "basic render loop");
245 s_instance = new QSGGuiThreadRenderLoop();
246 break;
247 }
248 }
249#endif
250 qAddPostRoutine(QSGRenderLoop::cleanup);
251 }
252
253 return s_instance;
254}
255
256void QSGRenderLoop::setInstance(QSGRenderLoop *instance)
257{
258 Q_ASSERT(!s_instance);
259 s_instance = instance;
260}
261
262void QSGRenderLoop::handleContextCreationFailure(QQuickWindow *window)
263{
264 // Must always be called on the gui thread.
265
266 // Guard for recursion; relevant due to the MessageBox() on Windows.
267 static QSet<QQuickWindow *> recurseGuard;
268 if (recurseGuard.contains(window))
269 return;
270
271 recurseGuard.insert(window);
272
273 QString translatedMessage;
274 QString untranslatedMessage;
275 QQuickWindowPrivate::rhiCreationFailureMessage(QSGRhiSupport::instance()->rhiBackendName(),
276 &translatedMessage,
277 &untranslatedMessage);
278 // If there is a slot connected to the error signal, emit it and leave it to
279 // the application to do something with the message. If nothing is connected,
280 // show a message on our own and terminate.
281 const bool signalEmitted =
282 QQuickWindowPrivate::get(window)->emitError(QQuickWindow::ContextNotAvailable,
283 translatedMessage);
284#if defined(Q_OS_WIN)
285 if (!signalEmitted && !QLibraryInfo::isDebugBuild() && !GetConsoleWindow()) {
286 MessageBox(0, (LPCTSTR) translatedMessage.utf16(),
287 (LPCTSTR)(QCoreApplication::applicationName().utf16()),
288 MB_OK | MB_ICONERROR);
289 }
290#endif // Q_OS_WIN
291 if (!signalEmitted)
292 qFatal("%s", qPrintable(untranslatedMessage));
293
294 recurseGuard.remove(window);
295}
296
298QSGGuiThreadRenderLoop::QSGGuiThreadRenderLoop()
299{
301 QUnifiedTimer::instance(true)->setConsistentTiming(true);
302 qCDebug(QSG_LOG_INFO, "using fixed animation steps");
303 }
304
305 sg = QSGContext::createDefaultContext();
306}
307
309{
310 qDeleteAll(pendingRenderContexts);
311 delete sg;
312}
313
314void QSGGuiThreadRenderLoop::show(QQuickWindow *window)
315{
316 if (!m_windows.contains(window))
317 m_windows.insert(window, {});
318
319 m_windows[window].timeBetweenRenders.start();
320 maybeUpdate(window);
321}
322
323void QSGGuiThreadRenderLoop::hide(QQuickWindow *window)
324{
325 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
326 cd->fireAboutToStop();
327 auto it = m_windows.find(window);
328 if (it != m_windows.end())
329 it->updatePending = false;
330}
331
332void QSGGuiThreadRenderLoop::windowDestroyed(QQuickWindow *window)
333{
334 hide(window);
335
336 WindowData data = m_windows.value(window, {});
337 m_windows.remove(window);
338
339 QQuickWindowPrivate *d = QQuickWindowPrivate::get(window);
340
341 if (data.rhi) {
342 // Direct OpenGL calls in user code need a current context, like
343 // when rendering; ensure this (no-op when not running on GL).
344 // Also works when there is no handle() anymore.
345 data.rhi->makeThreadLocalNativeContextCurrent();
346 }
347
348 if (d->swapchain) {
349 if (window->handle()) {
350 // We get here when exiting via QCoreApplication::quit() instead of
351 // through QWindow::close().
352 releaseSwapchain(window);
353 } else {
354 qWarning("QSGGuiThreadRenderLoop cleanup with QQuickWindow %p swapchain %p still alive, this should not happen.",
355 window, d->swapchain);
356 }
357 }
358
359 d->cleanupNodesOnShutdown();
360
361#if QT_CONFIG(quick_shadereffect)
362 QSGRhiShaderEffectNode::resetMaterialTypeCache(window);
363#endif
364
365 if (data.rc) {
366 data.rc->invalidate();
367 delete data.rc;
368 }
369
370 if (data.ownRhi)
371 QSGRhiSupport::instance()->destroyRhi(data.rhi, d->graphicsConfig);
372
373 d->rhi = nullptr;
374
375 d->animationController.reset();
376
377 if (m_windows.isEmpty()) {
378 delete offscreenSurface;
379 offscreenSurface = nullptr;
380 }
381}
382
384{
385 for (auto it = m_windows.begin(), itEnd = m_windows.end(); it != itEnd; ++it) {
386 if (it->rhi) {
387 QQuickWindowPrivate::get(it.key())->cleanupNodesOnShutdown();
388 if (it->rc)
389 it->rc->invalidate();
390 releaseSwapchain(it.key());
391 if (it->ownRhi)
392 QSGRhiSupport::instance()->destroyRhi(it->rhi, {});
393 it->rhi = nullptr;
394 }
395 }
396}
397
399{
400 qWarning("Graphics device lost, cleaning up scenegraph and releasing RHIs");
401
402 for (auto it = m_windows.begin(), itEnd = m_windows.end(); it != itEnd; ++it) {
403 if (!it->rhi || !it->rhi->isDeviceLost())
404 continue;
405
406 QQuickWindowPrivate::get(it.key())->cleanupNodesOnShutdown();
407
408 if (it->rc)
409 it->rc->invalidate();
410
411 releaseSwapchain(it.key());
412 it->rhiDeviceLost = true;
413
414 if (it->ownRhi)
415 QSGRhiSupport::instance()->destroyRhi(it->rhi, {});
416 it->rhi = nullptr;
417 }
418}
419
420void QSGGuiThreadRenderLoop::releaseSwapchain(QQuickWindow *window)
421{
422 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(window);
423 delete wd->rpDescForSwapchain;
424 wd->rpDescForSwapchain = nullptr;
425 delete wd->swapchain;
426 wd->swapchain = nullptr;
427 delete wd->depthStencilForSwapchain;
428 wd->depthStencilForSwapchain = nullptr;
429 wd->hasActiveSwapchain = wd->hasRenderableSwapchain = wd->swapchainJustBecameRenderable = false;
430}
431
432bool QSGGuiThreadRenderLoop::eventFilter(QObject *watched, QEvent *event)
433{
434 switch (event->type()) {
435 case QEvent::PlatformSurface:
436 // this is the proper time to tear down the swapchain (while the native window and surface are still around)
437 if (static_cast<QPlatformSurfaceEvent *>(event)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) {
438 QQuickWindow *w = qobject_cast<QQuickWindow *>(watched);
439 if (w)
441 // keep this filter on the window - needed for uncommon but valid
442 // sequences of calls like window->destroy(); window->show();
443 }
444 break;
445 default:
446 break;
447 }
448 return QObject::eventFilter(watched, event);
449}
450
451bool QSGGuiThreadRenderLoop::ensureRhi(QQuickWindow *window, WindowData &data)
452{
453 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
454 QSGRhiSupport *rhiSupport = QSGRhiSupport::instance();
455 bool ok = data.rhi != nullptr;
456
457 if (!data.rhi) {
458 // This block below handles both the initial QRhi initialization and
459 // also the subsequent reinitialization attempts after a device lost
460 // (reset) situation.
461
462 if (data.rhiDoomed) // no repeated attempts if the initial attempt failed
463 return false;
464
465 if (!offscreenSurface)
466 offscreenSurface = rhiSupport->maybeCreateOffscreenSurface(window);
467
468 const bool forcePreferSwRenderer = swRastFallbackDueToSwapchainFailure;
469 QSGRhiSupport::RhiCreateResult rhiResult = rhiSupport->createRhi(window, offscreenSurface, forcePreferSwRenderer);
470 data.rhi = rhiResult.rhi;
471 data.ownRhi = rhiResult.own;
472
473 if (data.rhi) {
474 data.rhiDeviceLost = false;
475
476 ok = true;
477 // We need to guarantee that sceneGraphInitialized is
478 // emitted with a context current, if running with OpenGL.
479 data.rhi->makeThreadLocalNativeContextCurrent();
480
481 // The sample count cannot vary between windows as we use the same
482 // rendercontext for all of them. Decide it here and now.
483 data.sampleCount = rhiSupport->chooseSampleCountForWindowWithRhi(window, data.rhi);
484
485 cd->rhi = data.rhi; // set this early in case something hooked up to rc initialized() accesses it
486
487 QSGDefaultRenderContext::InitParams rcParams;
488 rcParams.rhi = data.rhi;
489 rcParams.sampleCount = data.sampleCount;
490 rcParams.initialSurfacePixelSize = window->size() * window->effectiveDevicePixelRatio();
491 rcParams.maybeSurface = window;
492 cd->context->initialize(&rcParams);
493 } else {
494 if (!data.rhiDeviceLost) {
495 data.rhiDoomed = true;
496 handleContextCreationFailure(window);
497 }
498 // otherwise no error, just return false so that we will retry on a subsequent rendering attempt
499 }
500 }
501
502 if (data.rhi && !cd->swapchain) {
503 // if it's not the first window then the rhi is not yet stored to
504 // QQuickWindowPrivate, do it now
505 cd->rhi = data.rhi;
506
507 // Unlike the threaded render loop, we use the same rhi for all windows
508 // and so createRhi() is called only once. Certain initialization may
509 // need to be done on a per window basis still, so make sure it is done.
510 rhiSupport->prepareWindowForRhi(window);
511
512 QRhiSwapChain::Flags flags = QRhiSwapChain::UsedAsTransferSource; // may be used in a grab
513 const QSurfaceFormat requestedFormat = window->requestedFormat();
514
515 // QQ is always premul alpha. Decide based on alphaBufferSize in
516 // requestedFormat(). (the platform plugin can override format() but
517 // what matters here is what the application wanted, hence using the
518 // requested one)
519 const bool alpha = requestedFormat.alphaBufferSize() > 0;
520 if (alpha)
521 flags |= QRhiSwapChain::SurfaceHasPreMulAlpha;
522
523 // Request NoVSync if swap interval was set to 0 (either by the app or
524 // by QSG_NO_VSYNC). What this means in practice is another question,
525 // but at least we tried.
526 if (requestedFormat.swapInterval() == 0) {
527 qCDebug(QSG_LOG_INFO, "Swap interval is 0, attempting to disable vsync when presenting.");
528 flags |= QRhiSwapChain::NoVSync;
529 }
530
531 cd->swapchain = data.rhi->newSwapChain();
532 static bool depthBufferEnabled = qEnvironmentVariableIsEmpty("QSG_NO_DEPTH_BUFFER");
533 if (depthBufferEnabled) {
534 cd->depthStencilForSwapchain = data.rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
535 QSize(),
536 data.sampleCount,
537 QRhiRenderBuffer::UsedWithSwapChainOnly);
538 cd->swapchain->setDepthStencil(cd->depthStencilForSwapchain);
539 }
540 cd->swapchain->setWindow(window);
541 rhiSupport->applySwapChainFormat(cd->swapchain, window);
542 qCDebug(QSG_LOG_INFO, "MSAA sample count for the swapchain is %d. Alpha channel requested = %s",
543 data.sampleCount, alpha ? "yes" : "no");
544 cd->swapchain->setSampleCount(data.sampleCount);
545 cd->swapchain->setFlags(flags);
546 cd->rpDescForSwapchain = cd->swapchain->newCompatibleRenderPassDescriptor();
547 cd->swapchain->setRenderPassDescriptor(cd->rpDescForSwapchain);
548
549 window->installEventFilter(this);
550 }
551
552 if (!data.rc) {
553 QSGRenderContext *rc = cd->context;
554 pendingRenderContexts.remove(rc);
555 data.rc = rc;
556 if (!data.rc)
557 qWarning("No QSGRenderContext for window %p, this should not happen", window);
558 }
559
560 return ok;
561}
562
563void QSGGuiThreadRenderLoop::renderWindow(QQuickWindow *window)
564{
565 auto winDataIt = m_windows.find(window);
566 if (winDataIt == m_windows.end())
567 return;
568
569 WindowData &data(*winDataIt);
570 bool alsoSwap = data.updatePending;
571 data.updatePending = false;
572
573 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
574 if (!cd->isRenderable())
575 return;
576
577 if (!cd->updatesEnabled)
578 return;
579
580 if (!ensureRhi(window, data))
581 return;
582
583 cd->deliveryAgentPrivate()->flushFrameSynchronousEvents(window);
584 // Event delivery/processing triggered the window to be deleted or stop rendering.
585 if (!m_windows.contains(window))
586 return;
587
588 QSize effectiveOutputSize; // always prefer what the surface tells us, not the QWindow
589 if (cd->swapchain) {
590 effectiveOutputSize = cd->swapchain->surfacePixelSize();
591 // An update request could still be delivered right before we get an
592 // unexpose. With Vulkan on Windows for example attempting to render
593 // leads to failures at this stage since the surface size is already 0.
594 if (effectiveOutputSize.isEmpty())
595 return;
596 }
597
598 Q_TRACE_SCOPE(QSG_renderWindow);
599 QElapsedTimer renderTimer;
600 qint64 renderTime = 0, syncTime = 0, polishTime = 0;
601 const bool profileFrames = QSG_LOG_TIME_RENDERLOOP().isDebugEnabled();
602 if (profileFrames)
603 renderTimer.start();
604 Q_TRACE(QSG_polishItems_entry);
605 Q_QUICK_SG_PROFILE_START(QQuickProfiler::SceneGraphPolishFrame);
606
607 m_inPolish = true;
608 cd->polishItems();
609 m_inPolish = false;
610
611 if (profileFrames)
612 polishTime = renderTimer.nsecsElapsed();
613
614 Q_TRACE(QSG_polishItems_exit);
615 Q_QUICK_SG_PROFILE_SWITCH(QQuickProfiler::SceneGraphPolishFrame,
616 QQuickProfiler::SceneGraphRenderLoopFrame,
617 QQuickProfiler::SceneGraphPolishPolish);
618 Q_TRACE(QSG_sync_entry);
619
620 emit window->afterAnimating();
621
622 // Begin the frame before syncing -> sync is where we may invoke
623 // updatePaintNode() on the items and they may want to do resource updates.
624 // Also relevant for applications that connect to the before/afterSynchronizing
625 // signals and want to do graphics stuff already there.
626 if (cd->swapchain) {
627 Q_ASSERT(!effectiveOutputSize.isEmpty());
628 QSGRhiSupport *rhiSupport = QSGRhiSupport::instance();
629 const QSize previousOutputSize = cd->swapchain->currentPixelSize();
630 if (previousOutputSize != effectiveOutputSize || cd->swapchainJustBecameRenderable) {
631 if (cd->swapchainJustBecameRenderable)
632 qCDebug(QSG_LOG_RENDERLOOP, "just became exposed");
633
634 cd->hasActiveSwapchain = cd->swapchain->createOrResize();
635 if (!cd->hasActiveSwapchain) {
636 if (data.rhi->isDeviceLost()) {
638 return;
639 } else if (previousOutputSize.isEmpty() && !swRastFallbackDueToSwapchainFailure && rhiSupport->attemptReinitWithSwRastUponFail()) {
640 qWarning("Failed to create swapchain."
641 " Retrying by requesting a software rasterizer, if applicable for the 3D API implementation.");
644 return;
645 }
646 }
647
648 cd->swapchainJustBecameRenderable = false;
649 cd->hasRenderableSwapchain = cd->hasActiveSwapchain;
650
651 if (cd->hasActiveSwapchain) {
652 // surface size atomicity: now that buildOrResize() succeeded,
653 // query the size that was used in there by the swapchain, and
654 // that is the size we will use while preparing the next frame.
655 effectiveOutputSize = cd->swapchain->currentPixelSize();
656 qCDebug(QSG_LOG_RENDERLOOP) << "rhi swapchain size" << effectiveOutputSize;
657 } else {
658 qWarning("Failed to build or resize swapchain");
659 }
660 }
661
662 emit window->beforeFrameBegin();
663
664 Q_ASSERT(data.rhi == cd->rhi);
665 QRhi::FrameOpResult frameResult = data.rhi->beginFrame(cd->swapchain);
666 if (frameResult != QRhi::FrameOpSuccess) {
667 if (frameResult == QRhi::FrameOpDeviceLost)
669 else if (frameResult == QRhi::FrameOpError)
670 qWarning("Failed to start frame");
671 // out of date is not worth warning about - it may happen even during resizing on some platforms
672 emit window->afterFrameEnd();
673 return;
674 }
675 }
676
677 // Enable external OpenGL rendering connected to one of the
678 // QQuickWindow signals (beforeSynchronizing, beforeRendering,
679 // etc.) to function like it did on the direct OpenGL path,
680 // i.e. ensure there is a context current, just in case.
681 data.rhi->makeThreadLocalNativeContextCurrent();
682
683 cd->syncSceneGraph();
684 data.rc->endSync();
685
686 if (profileFrames)
687 syncTime = renderTimer.nsecsElapsed();
688
689 Q_TRACE(QSG_sync_exit);
690 Q_QUICK_SG_PROFILE_RECORD(QQuickProfiler::SceneGraphRenderLoopFrame,
691 QQuickProfiler::SceneGraphRenderLoopSync);
692 Q_TRACE(QSG_render_entry);
693
694 cd->renderSceneGraph();
695
696 if (profileFrames)
697 renderTime = renderTimer.nsecsElapsed();
698 Q_TRACE(QSG_render_exit);
699 Q_QUICK_SG_PROFILE_RECORD(QQuickProfiler::SceneGraphRenderLoopFrame,
700 QQuickProfiler::SceneGraphRenderLoopRender);
701 Q_TRACE(QSG_swap_entry);
702
703 const bool needsPresent = alsoSwap && window->isVisible();
704 double lastCompletedGpuTime = 0;
705 if (cd->swapchain) {
706 QRhi::EndFrameFlags flags;
707 if (!needsPresent)
708 flags |= QRhi::SkipPresent;
709 QRhi::FrameOpResult frameResult = data.rhi->endFrame(cd->swapchain, flags);
710 if (frameResult != QRhi::FrameOpSuccess) {
711 if (frameResult == QRhi::FrameOpDeviceLost)
713 else if (frameResult == QRhi::FrameOpError)
714 qWarning("Failed to end frame");
715 } else {
716 lastCompletedGpuTime = cd->swapchain->currentFrameCommandBuffer()->lastCompletedGpuTime();
717 }
718 }
719 if (needsPresent)
720 cd->fireFrameSwapped();
721
722 emit window->afterFrameEnd();
723
724 qint64 swapTime = 0;
725 if (profileFrames)
726 swapTime = renderTimer.nsecsElapsed();
727
728 Q_TRACE(QSG_swap_exit);
729 Q_QUICK_SG_PROFILE_END(QQuickProfiler::SceneGraphRenderLoopFrame,
730 QQuickProfiler::SceneGraphRenderLoopSwap);
731
732 if (profileFrames) {
733 qCDebug(QSG_LOG_TIME_RENDERLOOP,
734 "[window %p][gui thread] syncAndRender: frame rendered in %dms, polish=%d, sync=%d, render=%d, swap=%d, perWindowFrameDelta=%d",
735 window,
736 int(swapTime / 1000000),
737 int(polishTime / 1000000),
738 int((syncTime - polishTime) / 1000000),
739 int((renderTime - syncTime) / 1000000),
740 int((swapTime - renderTime) / 1000000),
741 int(data.timeBetweenRenders.restart()));
742 if (!qFuzzyIsNull(lastCompletedGpuTime) && cd->graphicsConfig.timestampsEnabled()) {
743 qCDebug(QSG_LOG_TIME_RENDERLOOP, "[window %p][gui thread] syncAndRender: last retrieved GPU frame time was %.4f ms",
744 window,
745 lastCompletedGpuTime * 1000.0);
746 }
747 }
748
749 // Might have been set during syncSceneGraph()
750 if (data.updatePending)
751 maybeUpdate(window);
752}
753
754void QSGGuiThreadRenderLoop::exposureChanged(QQuickWindow *window)
755{
756 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(window);
757
758 // This is tricker than used to be. We want to detect having an empty
759 // surface size (which may be the case even when window->size() is
760 // non-empty, on some platforms with some graphics APIs!) as well as the
761 // case when the window just became "newly exposed" (e.g. after a
762 // minimize-restore on Windows, or when switching between fully obscured -
763 // not fully obscured on macOS)
764
765 if (!window->isExposed() || (wd->hasActiveSwapchain && wd->swapchain->surfacePixelSize().isEmpty()))
766 wd->hasRenderableSwapchain = false;
767
768 if (window->isExposed() && !wd->hasRenderableSwapchain && wd->hasActiveSwapchain
769 && !wd->swapchain->surfacePixelSize().isEmpty())
770 {
771 wd->hasRenderableSwapchain = true;
772 wd->swapchainJustBecameRenderable = true;
773 }
774
775 auto winDataIt = m_windows.find(window);
776 if (winDataIt != m_windows.end()) {
777 if (window->isExposed() && (!winDataIt->rhi || !wd->hasActiveSwapchain || wd->hasRenderableSwapchain)) {
778 winDataIt->updatePending = true;
779 renderWindow(window);
780 }
781 }
782}
783
784QImage QSGGuiThreadRenderLoop::grab(QQuickWindow *window)
785{
786 auto winDataIt = m_windows.find(window);
787 if (winDataIt == m_windows.end())
788 return QImage();
789
790 if (!ensureRhi(window, *winDataIt))
791 return QImage();
792
793 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
794 m_inPolish = true;
795 cd->polishItems();
796 m_inPolish = false;
797
798 // The assumption is that the swapchain is usable since on expose we do a
799 // renderWindow() so one cannot get to grab() without having done at least
800 // one on-screen frame.
801 cd->rhi->beginFrame(cd->swapchain);
802 cd->rhi->makeThreadLocalNativeContextCurrent(); // for custom GL rendering before/during/after sync
803 cd->syncSceneGraph();
804 cd->renderSceneGraph();
805 QImage image = QSGRhiSupport::instance()->grabAndBlockInCurrentFrame(cd->rhi, cd->swapchain->currentFrameCommandBuffer());
806 cd->rhi->endFrame(cd->swapchain, QRhi::SkipPresent);
807
808 image.setDevicePixelRatio(window->effectiveDevicePixelRatio());
809 return image;
810}
811
812void QSGGuiThreadRenderLoop::maybeUpdate(QQuickWindow *window)
813{
814 auto winDataIt = m_windows.find(window);
815 if (winDataIt == m_windows.end())
816 return;
817
818 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
819 if (!cd->isRenderable())
820 return;
821
822 winDataIt->updatePending = true;
823
824 // An updatePolish() implementation may call update() to get the QQuickItem
825 // dirtied. That's fine but it also leads to calling this function.
826 // Requesting another update is a waste then since the updatePolish() call
827 // will be followed up with a round of sync and render.
828 if (m_inPolish)
829 return;
830
831 window->requestUpdate();
832}
833
835{
836 return sg;
837}
838
839QSGRenderContext *QSGGuiThreadRenderLoop::createRenderContext(QSGContext *sg) const
840{
841 QSGRenderContext *rc = sg->createRenderContext();
842 pendingRenderContexts.insert(rc);
843 return rc;
844}
845
847{
848 // No full invalidation of the rendercontext, just clear some caches.
849 QQuickWindowPrivate *d = QQuickWindowPrivate::get(w);
850 emit d->context->releaseCachedResourcesRequested();
851 if (d->renderer)
852 d->renderer->releaseCachedResources();
853#if QT_CONFIG(quick_shadereffect)
854 QSGRhiShaderEffectNode::garbageCollectMaterialTypeCache(w);
855#endif
856}
857
859{
860 renderWindow(window);
861}
862
863#endif // ENABLE_DEFAULT_BACKEND
864
865QT_END_NAMESPACE
866
867#include "qsgrenderloop.moc"
868#include "moc_qsgrenderloop_p.cpp"
QAnimationDriver * animationDriver() const override
void update(QQuickWindow *window) override
void renderWindow(QQuickWindow *window)
void releaseSwapchain(QQuickWindow *window)
void show(QQuickWindow *window) override
bool eventFilter(QObject *watched, QEvent *event) override
Filters events if this object has been installed as an event filter for the watched object.
QSGRenderContext * createRenderContext(QSGContext *) const override
void windowDestroyed(QQuickWindow *window) override
bool ensureRhi(QQuickWindow *window, WindowData &data)
QOffscreenSurface * offscreenSurface
void releaseResources(QQuickWindow *) override
void exposureChanged(QQuickWindow *window) override
QSGContext * sceneGraphContext() const override
QHash< QQuickWindow *, WindowData > m_windows
QSet< QSGRenderContext * > pendingRenderContexts
void handleUpdateRequest(QQuickWindow *) override
void hide(QQuickWindow *window) override
QImage grab(QQuickWindow *window) override
void maybeUpdate(QQuickWindow *window) override
bool qsg_useConsistentTiming()
#define ENABLE_DEFAULT_BACKEND
DEFINE_BOOL_CONFIG_OPTION(forceDiskCache, QML_FORCE_DISK_CACHE)