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 const auto windows = s_instance->windows();
77 for (QQuickWindow *w : windows) {
78 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(w);
79 if (wd->windowManager == s_instance) {
80 s_instance->windowDestroyed(w);
81 wd->windowManager = nullptr;
82 }
83 }
84 delete s_instance;
85 s_instance = nullptr;
86}
87
88QSurface::SurfaceType QSGRenderLoop::windowSurfaceType() const
89{
91 return QSGRhiSupport::instance()->windowSurfaceType();
92#else
93 return QSurface::RasterSurface;
94#endif
95}
96
97void QSGRenderLoop::postJob(QQuickWindow *window, QRunnable *job)
98{
99 Q_ASSERT(job);
101 Q_ASSERT(window);
102 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
103 if (cd->rhi)
104 cd->rhi->makeThreadLocalNativeContextCurrent();
105 job->run();
106#else
107 Q_UNUSED(window);
108 job->run();
109#endif
110 delete job;
111}
112
115{
117public:
120
121 void show(QQuickWindow *window) override;
122 void hide(QQuickWindow *window) override;
123
124 void windowDestroyed(QQuickWindow *window) override;
125
126 void renderWindow(QQuickWindow *window);
127 void exposureChanged(QQuickWindow *window) override;
128 QImage grab(QQuickWindow *window) override;
129
130 void maybeUpdate(QQuickWindow *window) override;
131 void update(QQuickWindow *window) override { maybeUpdate(window); } // identical for this implementation.
132 void handleUpdateRequest(QQuickWindow *) override;
133
134 void releaseResources(QQuickWindow *) override;
135
136 QAnimationDriver *animationDriver() const override { return nullptr; }
137
138 QSGContext *sceneGraphContext() const override;
139 QSGRenderContext *createRenderContext(QSGContext *) const override;
140
141 void releaseSwapchain(QQuickWindow *window);
144
145 bool eventFilter(QObject *watched, QEvent *event) override;
146
147 struct WindowData {
149 : updatePending(false),
150 rhiDeviceLost(false),
151 rhiDoomed(false),
152 swapchainOutOfDate(false)
153 { }
154 QRhi *rhi = nullptr;
155 bool ownRhi = true;
156 QOffscreenSurface *offscreenSurface = nullptr;
157 QSGRenderContext *rc = nullptr;
159 int sampleCount = 1;
162 bool rhiDoomed : 1;
164 };
165
166 bool ensureRhi(QQuickWindow *window, WindowData &data);
167
169
170 QSGContext *sg;
172
173 bool m_inPolish = false;
174
176};
177#endif
178
179QSGRenderLoop *QSGRenderLoop::instance()
180{
181 if (!s_instance) {
182
183 QSGRhiSupport::checkEnvQSgInfo();
184
185 s_instance = QSGContext::createWindowManager();
187 if (!s_instance) {
188 QSGRhiSupport *rhiSupport = QSGRhiSupport::instance();
189
190 QSGRenderLoopType loopType;
191 if (rhiSupport->rhiBackend() != QRhi::OpenGLES2) {
192 loopType = ThreadedRenderLoop;
193 } else {
194 if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedOpenGL))
195 loopType = ThreadedRenderLoop;
196 else
197 loopType = BasicRenderLoop;
198 }
199
200 switch (rhiSupport->rhiBackend()) {
201 case QRhi::Null:
202 loopType = BasicRenderLoop;
203 break;
204
205 case QRhi::D3D11:
206 // The threaded loop's model may not be suitable for DXGI
207 // due to the possibility of having the main thread (with
208 // the Windows message pump) blocked while issuing a
209 // Present on the render thread. However, according to the
210 // docs this can be a problem for fullscreen swapchains
211 // only. So leave threaded enabled by default for now and
212 // revisit later if there are problems.
213 break;
214
215 default:
216 break;
217 }
218
219 // The environment variables can always override. This is good
220 // because in some situations it makes perfect sense to try out a
221 // render loop that is otherwise disabled by default.
222
223 if (qmlNoThreadedRenderer())
224 loopType = BasicRenderLoop;
225 else if (qmlForceThreadedRenderer())
226 loopType = ThreadedRenderLoop;
227
228 if (Q_UNLIKELY(qEnvironmentVariableIsSet("QSG_RENDER_LOOP"))) {
229 const QByteArray loopName = qgetenv("QSG_RENDER_LOOP");
230 if (loopName == "windows") {
231 qWarning("The 'windows' render loop is no longer supported. Using 'basic' instead.");
232 loopType = BasicRenderLoop;
233 } else if (loopName == "basic") {
234 loopType = BasicRenderLoop;
235 } else if (loopName == "threaded") {
236 loopType = ThreadedRenderLoop;
237 }
238 }
239
240 switch (loopType) {
241#if QT_CONFIG(thread)
242 case ThreadedRenderLoop:
243 qCDebug(QSG_LOG_INFO, "threaded render loop");
244 s_instance = new QSGThreadedRenderLoop();
245 break;
246#endif
247 default:
248 qCDebug(QSG_LOG_INFO, "basic render loop");
249 s_instance = new QSGGuiThreadRenderLoop();
250 break;
251 }
252 }
253#endif
254 qAddPostRoutine(QSGRenderLoop::cleanup);
255 }
256
257 return s_instance;
258}
259
260void QSGRenderLoop::setInstance(QSGRenderLoop *instance)
261{
262 Q_ASSERT(!s_instance);
263 s_instance = instance;
264}
265
266void QSGRenderLoop::handleContextCreationFailure(QQuickWindow *window)
267{
268 // Must always be called on the gui thread.
269
270 // Guard for recursion; relevant due to the MessageBox() on Windows.
271 static QSet<QQuickWindow *> recurseGuard;
272 if (recurseGuard.contains(window))
273 return;
274
275 recurseGuard.insert(window);
276
277 QString translatedMessage;
278 QString untranslatedMessage;
279 QQuickWindowPrivate::rhiCreationFailureMessage(QSGRhiSupport::instance()->rhiBackendName(),
280 &translatedMessage,
281 &untranslatedMessage);
282 // If there is a slot connected to the error signal, emit it and leave it to
283 // the application to do something with the message. If nothing is connected,
284 // show a message on our own and terminate.
285 const bool signalEmitted =
286 QQuickWindowPrivate::get(window)->emitError(QQuickWindow::ContextNotAvailable,
287 translatedMessage);
288#if defined(Q_OS_WIN)
289 if (!signalEmitted && !QLibraryInfo::isDebugBuild() && !GetConsoleWindow()) {
290 MessageBox(0, (LPCTSTR) translatedMessage.utf16(),
291 (LPCTSTR)(QCoreApplication::applicationName().utf16()),
292 MB_OK | MB_ICONERROR);
293 }
294#endif // Q_OS_WIN
295 if (!signalEmitted)
296 qFatal("%s", qPrintable(untranslatedMessage));
297
298 recurseGuard.remove(window);
299}
300
302QSGGuiThreadRenderLoop::QSGGuiThreadRenderLoop()
303{
305 QUnifiedTimer::instance(true)->setConsistentTiming(true);
306 qCDebug(QSG_LOG_INFO, "using fixed animation steps");
307 }
308
309 sg = QSGContext::createDefaultContext();
310}
311
313{
314 qDeleteAll(pendingRenderContexts);
315 delete sg;
316}
317
318void QSGGuiThreadRenderLoop::show(QQuickWindow *window)
319{
320 if (!m_windows.contains(window))
321 m_windows.insert(window, {});
322
323 m_windows[window].timeBetweenRenders.start();
324 maybeUpdate(window);
325}
326
327void QSGGuiThreadRenderLoop::hide(QQuickWindow *window)
328{
329 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
330 cd->fireAboutToStop();
331 auto it = m_windows.find(window);
332 if (it != m_windows.end())
333 it->updatePending = false;
334}
335
336void QSGGuiThreadRenderLoop::windowDestroyed(QQuickWindow *window)
337{
338 hide(window);
339
340 WindowData data = m_windows.value(window, {});
341 m_windows.remove(window);
342
343 QQuickWindowPrivate *d = QQuickWindowPrivate::get(window);
344
345 if (data.rhi) {
346 // Direct OpenGL calls in user code need a current context, like
347 // when rendering; ensure this (no-op when not running on GL).
348 // Also works when there is no handle() anymore.
349 data.rhi->makeThreadLocalNativeContextCurrent();
350 }
351
352 if (d->swapchain) {
353 if (window->handle()) {
354 // We get here when exiting via QCoreApplication::quit() instead of
355 // through QWindow::close().
356 releaseSwapchain(window);
357 } else {
358 qWarning("QSGGuiThreadRenderLoop cleanup with QQuickWindow %p swapchain %p still alive, this should not happen.",
359 window, d->swapchain);
360 }
361 }
362
363 d->cleanupNodesOnShutdown();
364
365#if QT_CONFIG(quick_shadereffect)
366 QSGRhiShaderEffectNode::resetMaterialTypeCache(window);
367#endif
368
369 if (data.rc) {
370 data.rc->invalidate();
371 delete data.rc;
372 }
373
374 if (data.ownRhi)
375 QSGRhiSupport::instance()->destroyRhi(data.rhi, d->graphicsConfig);
376
377 d->rhi = nullptr;
378
379 d->animationController.reset();
380
381 delete data.offscreenSurface;
382}
383
385{
386 for (auto it = m_windows.begin(), itEnd = m_windows.end(); it != itEnd; ++it) {
387 if (it->rhi) {
388 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(it.key());
389 wd->cleanupNodesOnShutdown();
390 if (it->rc)
391 it->rc->invalidate();
392 releaseSwapchain(it.key());
393 if (it->ownRhi)
394 QSGRhiSupport::instance()->destroyRhi(it->rhi, {});
395 it->rhi = nullptr;
396 wd->rhi = nullptr;
397 }
398 }
399}
400
402{
403 qWarning("Graphics device lost, cleaning up scenegraph and releasing RHIs");
404
405 for (auto it = m_windows.begin(), itEnd = m_windows.end(); it != itEnd; ++it) {
406 if (!it->rhi || !it->rhi->isDeviceLost())
407 continue;
408
409 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(it.key());
410 wd->cleanupNodesOnShutdown();
411
412 if (it->rc)
413 it->rc->invalidate();
414
415 releaseSwapchain(it.key());
416 it->rhiDeviceLost = true;
417
418 if (it->ownRhi)
419 QSGRhiSupport::instance()->destroyRhi(it->rhi, {});
420 it->rhi = nullptr;
421 wd->rhi = nullptr;
422 }
423}
424
425void QSGGuiThreadRenderLoop::releaseSwapchain(QQuickWindow *window)
426{
427 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(window);
428 delete wd->rpDescForSwapchain;
429 wd->rpDescForSwapchain = nullptr;
430 delete wd->swapchain;
431 wd->swapchain = nullptr;
432 delete wd->depthStencilForSwapchain;
433 wd->depthStencilForSwapchain = nullptr;
434 wd->hasActiveSwapchain = wd->hasRenderableSwapchain = wd->swapchainJustBecameRenderable = false;
435}
436
437bool QSGGuiThreadRenderLoop::eventFilter(QObject *watched, QEvent *event)
438{
439 switch (event->type()) {
440 case QEvent::PlatformSurface:
441 // this is the proper time to tear down the swapchain (while the native window and surface are still around)
442 if (static_cast<QPlatformSurfaceEvent *>(event)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) {
443 QQuickWindow *w = qobject_cast<QQuickWindow *>(watched);
444 if (w)
446 // keep this filter on the window - needed for uncommon but valid
447 // sequences of calls like window->destroy(); window->show();
448 }
449 break;
450 default:
451 break;
452 }
453 return QObject::eventFilter(watched, event);
454}
455
456bool QSGGuiThreadRenderLoop::ensureRhi(QQuickWindow *window, WindowData &data)
457{
458 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
459 QSGRhiSupport *rhiSupport = QSGRhiSupport::instance();
460 bool ok = data.rhi != nullptr;
461
462 if (!data.rhi) {
463 // This block below handles both the initial QRhi initialization and
464 // also the subsequent reinitialization attempts after a device lost
465 // (reset) situation.
466
467 if (data.rhiDoomed) // no repeated attempts if the initial attempt failed
468 return false;
469
470 if (!data.offscreenSurface)
471 data.offscreenSurface = rhiSupport->maybeCreateOffscreenSurface(window);
472
473 const bool forcePreferSwRenderer = swRastFallbackDueToSwapchainFailure;
474 QSGRhiSupport::RhiCreateResult rhiResult =
475 rhiSupport->createRhi(window, data.offscreenSurface, forcePreferSwRenderer);
476 data.rhi = rhiResult.rhi;
477 data.ownRhi = rhiResult.own;
478
479 if (data.rhi) {
480 data.rhiDeviceLost = false;
481
482 ok = true;
483 // We need to guarantee that sceneGraphInitialized is
484 // emitted with a context current, if running with OpenGL.
485 data.rhi->makeThreadLocalNativeContextCurrent();
486
487 data.sampleCount = rhiSupport->chooseSampleCountForWindowWithRhi(window, data.rhi);
488
489 cd->rhi = data.rhi; // set this early in case something hooked up to rc initialized() accesses it
490
491 QSGDefaultRenderContext::InitParams rcParams;
492 rcParams.rhi = data.rhi;
493 rcParams.sampleCount = data.sampleCount;
494 rcParams.initialSurfacePixelSize = window->size() * window->effectiveDevicePixelRatio();
495 rcParams.maybeSurface = window;
496 cd->context->initialize(&rcParams);
497 } else {
498 if (!data.rhiDeviceLost) {
499 data.rhiDoomed = true;
500 handleContextCreationFailure(window);
501 }
502 // otherwise no error, just return false so that we will retry on a subsequent rendering attempt
503 }
504 }
505
506 if (data.rhi && !cd->swapchain) {
507 cd->rhi = data.rhi;
508
509 rhiSupport->prepareWindowForRhi(window);
510
511 QRhiSwapChain::Flags flags = QRhiSwapChain::UsedAsTransferSource; // may be used in a grab
512 const QSurfaceFormat requestedFormat = window->requestedFormat();
513
514 // QQ is always premul alpha. Decide based on alphaBufferSize in
515 // requestedFormat(). (the platform plugin can override format() but
516 // what matters here is what the application wanted, hence using the
517 // requested one)
518 const bool alpha = requestedFormat.alphaBufferSize() > 0;
519 if (alpha)
520 flags |= QRhiSwapChain::SurfaceHasPreMulAlpha;
521
522 // Request NoVSync if swap interval was set to 0 (either by the app or
523 // by QSG_NO_VSYNC). What this means in practice is another question,
524 // but at least we tried.
525 if (requestedFormat.swapInterval() == 0) {
526 qCDebug(QSG_LOG_INFO, "Swap interval is 0, attempting to disable vsync when presenting.");
527 flags |= QRhiSwapChain::NoVSync;
528 }
529
530 cd->swapchain = data.rhi->newSwapChain();
531 static bool depthBufferEnabled = qEnvironmentVariableIsEmpty("QSG_NO_DEPTH_BUFFER");
532 if (depthBufferEnabled) {
533 cd->depthStencilForSwapchain = data.rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
534 QSize(),
535 data.sampleCount,
536 QRhiRenderBuffer::UsedWithSwapChainOnly
537 | QSGRhiSupport::depthStencilBufferFlags());
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 (!cd->hasActiveSwapchain || previousOutputSize != effectiveOutputSize || cd->swapchainJustBecameRenderable || data.swapchainOutOfDate) {
631 if (cd->swapchainJustBecameRenderable)
632 qCDebug(QSG_LOG_RENDERLOOP, "just became exposed");
633 if (data.swapchainOutOfDate)
634 qCDebug(QSG_LOG_RENDERLOOP, "swapchain out of date");
635
636 cd->hasActiveSwapchain = cd->swapchain->createOrResize();
637 if (!cd->hasActiveSwapchain) {
638 cd->hasRenderableSwapchain = false;
639 if (data.rhi->isDeviceLost()) {
641 return;
642 } else if (previousOutputSize.isEmpty() && !swRastFallbackDueToSwapchainFailure && rhiSupport->attemptReinitWithSwRastUponFail()) {
643 qWarning("Failed to create swapchain."
644 " Retrying by requesting a software rasterizer, if applicable for the 3D API implementation.");
647 return;
648 }
649 qWarning("Failed to build or resize swapchain");
650 return;
651 }
652
653 cd->swapchainJustBecameRenderable = false;
654 data.swapchainOutOfDate = false;
655 cd->hasRenderableSwapchain = cd->hasActiveSwapchain;
656
657 // surface size atomicity: now that createOrResize() succeeded,
658 // query the size that was used in there by the swapchain, and
659 // that is the size we will use while preparing the next frame.
660 effectiveOutputSize = cd->swapchain->currentPixelSize();
661 qCDebug(QSG_LOG_RENDERLOOP) << "rhi swapchain size" << effectiveOutputSize;
662 }
663
664 emit window->beforeFrameBegin();
665
666 Q_ASSERT(data.rhi == cd->rhi);
667 QRhi::FrameOpResult frameResult = data.rhi->beginFrame(cd->swapchain);
668 if (frameResult != QRhi::FrameOpSuccess) {
669 if (frameResult == QRhi::FrameOpDeviceLost)
671 else if (frameResult == QRhi::FrameOpError)
672 qWarning("Failed to start frame");
673 // out of date is not worth warning about - it may happen even during resizing on some platforms
674 emit window->afterFrameEnd();
675 if (frameResult == QRhi::FrameOpSwapChainOutOfDate) {
676 data.swapchainOutOfDate = true;
677 maybeUpdate(window);
678 }
679 return;
680 }
681 }
682
683 // Enable external OpenGL rendering connected to one of the
684 // QQuickWindow signals (beforeSynchronizing, beforeRendering,
685 // etc.) to function like it did on the direct OpenGL path,
686 // i.e. ensure there is a context current, just in case.
687 data.rhi->makeThreadLocalNativeContextCurrent();
688
689 cd->syncSceneGraph();
690 data.rc->endSync();
691
692 if (profileFrames)
693 syncTime = renderTimer.nsecsElapsed();
694
695 Q_TRACE(QSG_sync_exit);
696 Q_QUICK_SG_PROFILE_RECORD(QQuickProfiler::SceneGraphRenderLoopFrame,
697 QQuickProfiler::SceneGraphRenderLoopSync);
698 Q_TRACE(QSG_render_entry);
699
700 cd->renderSceneGraph();
701
702 if (profileFrames)
703 renderTime = renderTimer.nsecsElapsed();
704 Q_TRACE(QSG_render_exit);
705 Q_QUICK_SG_PROFILE_RECORD(QQuickProfiler::SceneGraphRenderLoopFrame,
706 QQuickProfiler::SceneGraphRenderLoopRender);
707 Q_TRACE(QSG_swap_entry);
708
709 const bool needsPresent = alsoSwap && window->isVisible();
710 double lastCompletedGpuTime = 0;
711 if (cd->swapchain) {
712 QRhi::EndFrameFlags flags;
713 if (!needsPresent)
714 flags |= QRhi::SkipPresent;
715 QRhi::FrameOpResult frameResult = data.rhi->endFrame(cd->swapchain, flags);
716 if (frameResult != QRhi::FrameOpSuccess) {
717 if (frameResult == QRhi::FrameOpDeviceLost)
719 else if (frameResult == QRhi::FrameOpError)
720 qWarning("Failed to end frame");
721 if (frameResult == QRhi::FrameOpSwapChainOutOfDate) {
722 data.swapchainOutOfDate = true;
723 data.updatePending = true;
724 }
725 } else {
726 lastCompletedGpuTime = cd->swapchain->currentFrameCommandBuffer()->lastCompletedGpuTime();
727 }
728 }
729 if (needsPresent)
730 cd->fireFrameSwapped();
731
732 emit window->afterFrameEnd();
733
734 qint64 swapTime = 0;
735 if (profileFrames)
736 swapTime = renderTimer.nsecsElapsed();
737
738 Q_TRACE(QSG_swap_exit);
739 Q_QUICK_SG_PROFILE_END(QQuickProfiler::SceneGraphRenderLoopFrame,
740 QQuickProfiler::SceneGraphRenderLoopSwap);
741
742 if (profileFrames) {
743 qCDebug(QSG_LOG_TIME_RENDERLOOP,
744 "[window %p][gui thread] syncAndRender: frame rendered in %dms, polish=%d, sync=%d, render=%d, swap=%d, perWindowFrameDelta=%d",
745 window,
746 int(swapTime / 1000000),
747 int(polishTime / 1000000),
748 int((syncTime - polishTime) / 1000000),
749 int((renderTime - syncTime) / 1000000),
750 int((swapTime - renderTime) / 1000000),
751 int(data.timeBetweenRenders.restart()));
752 if (!qFuzzyIsNull(lastCompletedGpuTime) && cd->graphicsConfig.timestampsEnabled()) {
753 qCDebug(QSG_LOG_TIME_RENDERLOOP, "[window %p][gui thread] syncAndRender: last retrieved GPU frame time was %.4f ms",
754 window,
755 lastCompletedGpuTime * 1000.0);
756 }
757 }
758
759 // Might have been set during syncSceneGraph()
760 if (data.updatePending)
761 maybeUpdate(window);
762}
763
764void QSGGuiThreadRenderLoop::exposureChanged(QQuickWindow *window)
765{
766 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(window);
767
768 // This is tricker than used to be. We want to detect having an empty
769 // surface size (which may be the case even when window->size() is
770 // non-empty, on some platforms with some graphics APIs!) as well as the
771 // case when the window just became "newly exposed" (e.g. after a
772 // minimize-restore on Windows, or when switching between fully obscured -
773 // not fully obscured on macOS)
774
775 if (!window->isExposed() || (wd->hasActiveSwapchain && wd->swapchain->surfacePixelSize().isEmpty()))
776 wd->hasRenderableSwapchain = false;
777
778 if (window->isExposed() && !wd->hasRenderableSwapchain && wd->hasActiveSwapchain
779 && !wd->swapchain->surfacePixelSize().isEmpty())
780 {
781 wd->hasRenderableSwapchain = true;
782 wd->swapchainJustBecameRenderable = true;
783 }
784
785 auto winDataIt = m_windows.find(window);
786 if (winDataIt != m_windows.end()) {
787 if (window->isExposed() && (!winDataIt->rhi || !wd->hasActiveSwapchain || wd->hasRenderableSwapchain)) {
788 winDataIt->updatePending = true;
789 renderWindow(window);
790 }
791 }
792}
793
794QImage QSGGuiThreadRenderLoop::grab(QQuickWindow *window)
795{
796 auto winDataIt = m_windows.find(window);
797 if (winDataIt == m_windows.end())
798 return QImage();
799
800 if (!ensureRhi(window, *winDataIt))
801 return QImage();
802
803 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
804 m_inPolish = true;
805 cd->polishItems();
806 m_inPolish = false;
807
808 // The assumption is that the swapchain is usable since on expose we do a
809 // renderWindow() so one cannot get to grab() without having done at least
810 // one on-screen frame.
811 cd->rhi->beginFrame(cd->swapchain);
812 cd->rhi->makeThreadLocalNativeContextCurrent(); // for custom GL rendering before/during/after sync
813 cd->syncSceneGraph();
814 cd->renderSceneGraph();
815 QImage image = QSGRhiSupport::instance()->grabAndBlockInCurrentFrame(cd->rhi, cd->swapchain->currentFrameCommandBuffer());
816 cd->rhi->endFrame(cd->swapchain, QRhi::SkipPresent);
817
818 image.setDevicePixelRatio(window->effectiveDevicePixelRatio());
819 return image;
820}
821
822void QSGGuiThreadRenderLoop::maybeUpdate(QQuickWindow *window)
823{
824 auto winDataIt = m_windows.find(window);
825 if (winDataIt == m_windows.end())
826 return;
827
828 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(window);
829 if (!cd->isRenderable())
830 return;
831
832 winDataIt->updatePending = true;
833
834 // An updatePolish() implementation may call update() to get the QQuickItem
835 // dirtied. That's fine but it also leads to calling this function.
836 // Requesting another update is a waste then since the updatePolish() call
837 // will be followed up with a round of sync and render.
838 if (m_inPolish)
839 return;
840
841 window->requestUpdate();
842}
843
845{
846 return sg;
847}
848
849QSGRenderContext *QSGGuiThreadRenderLoop::createRenderContext(QSGContext *sg) const
850{
851 QSGRenderContext *rc = sg->createRenderContext();
852 pendingRenderContexts.insert(rc);
853 return rc;
854}
855
857{
858 // No full invalidation of the rendercontext, just clear some caches.
859 QQuickWindowPrivate *d = QQuickWindowPrivate::get(w);
860 emit d->context->releaseCachedResourcesRequested();
861 if (d->renderer)
862 d->renderer->releaseCachedResources();
863#if QT_CONFIG(quick_shadereffect)
864 QSGRhiShaderEffectNode::garbageCollectMaterialTypeCache(w);
865#endif
866}
867
869{
870 renderWindow(window);
871}
872
873#endif // ENABLE_DEFAULT_BACKEND
874
875QT_END_NAMESPACE
876
877#include "qsgrenderloop.moc"
878#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)
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)