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