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
qbackingstoredefaultcompositor.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6#include <QtGui/qtransform.h>
7#include <QtGui/private/qmath_p.h>
8#include <QtGui/private/qwindow_p.h>
9#include <qpa/qplatformgraphicsbuffer.h>
10#include <QtCore/qfile.h>
11
13
14using namespace Qt::StringLiterals;
15
20
22{
23 m_rhi = nullptr;
24 m_psNoBlend.reset();
25 m_psBlend.reset();
26 m_psPremulBlend.reset();
27 m_samplerNearest.reset();
28 m_samplerLinear.reset();
29 m_vbuf.reset();
30 m_texture.reset();
31 m_widgetQuadData.reset();
32 for (PerQuadData &d : m_textureQuadData)
33 d.reset();
34}
35
36QRhiTexture *QBackingStoreDefaultCompositor::toTexture(const QPlatformBackingStore *backingStore,
37 QRhi *rhi,
38 QRhiResourceUpdateBatch *resourceUpdates,
39 const QRegion &dirtyRegion,
40 QPlatformBackingStore::TextureFlags *flags) const
41{
42 return toTexture(backingStore->toImage(), rhi, resourceUpdates, dirtyRegion, flags);
43}
44
45QRhiTexture *QBackingStoreDefaultCompositor::toTexture(const QImage &sourceImage,
46 QRhi *rhi,
47 QRhiResourceUpdateBatch *resourceUpdates,
48 const QRegion &dirtyRegion,
49 QPlatformBackingStore::TextureFlags *flags) const
50{
51 Q_ASSERT(rhi);
52 Q_ASSERT(resourceUpdates);
53 Q_ASSERT(flags);
54
55 if (!m_rhi) {
56 m_rhi = rhi;
57 } else if (m_rhi != rhi) {
58 qWarning("QBackingStoreDefaultCompositor: the QRhi has changed unexpectedly, this should not happen");
59 return nullptr;
60 }
61
62 QImage image = sourceImage;
63
64 bool needsConversion = false;
65 *flags = {};
66
67 switch (image.format()) {
68 case QImage::Format_ARGB32_Premultiplied:
69 *flags |= QPlatformBackingStore::TexturePremultiplied;
70 Q_FALLTHROUGH();
71 case QImage::Format_RGB32:
72 case QImage::Format_ARGB32:
73 *flags |= QPlatformBackingStore::TextureSwizzle;
74 break;
75 case QImage::Format_RGBA8888_Premultiplied:
76 *flags |= QPlatformBackingStore::TexturePremultiplied;
77 Q_FALLTHROUGH();
78 case QImage::Format_RGBX8888:
79 case QImage::Format_RGBA8888:
80 break;
81 case QImage::Format_BGR30:
82 case QImage::Format_A2BGR30_Premultiplied:
83 // no fast path atm
84 needsConversion = true;
85 break;
86 case QImage::Format_RGB30:
87 case QImage::Format_A2RGB30_Premultiplied:
88 // no fast path atm
89 needsConversion = true;
90 break;
91 default:
92 needsConversion = true;
93 break;
94 }
95
96 if (image.size().isEmpty())
97 return nullptr;
98
99 const bool resized = !m_texture || m_texture->pixelSize() != image.size();
100 if (dirtyRegion.isEmpty() && !resized)
101 return m_texture.get();
102
103 if (needsConversion)
104 image = image.convertToFormat(QImage::Format_RGBA8888);
105 else
106 image.detach(); // if it was just wrapping data, that's no good, we need ownership, so detach
107
108 if (resized) {
109 if (!m_texture)
110 m_texture.reset(rhi->newTexture(QRhiTexture::RGBA8, image.size()));
111 else
112 m_texture->setPixelSize(image.size());
113 if (!m_texture->create()) {
114 // Typically a lost device. Make sure to reset the null native resource
115 qWarning("QBackingStoreDefaultCompositor: Failed to create backing store texture");
116 m_texture.reset();
117 return nullptr;
118 }
119 resourceUpdates->uploadTexture(m_texture.get(), image);
120 } else {
121 QRect imageRect = image.rect();
122 QRect rect = dirtyRegion.boundingRect() & imageRect;
124 subresDesc.setSourceTopLeft(rect.topLeft());
125 subresDesc.setSourceSize(rect.size());
126 subresDesc.setDestinationTopLeft(rect.topLeft());
127 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, subresDesc));
128 resourceUpdates->uploadTexture(m_texture.get(), uploadDesc);
129 }
130
131 return m_texture.get();
132}
133
134static inline QRect scaledRect(const QRect &rect, qreal factor)
135{
136 return qt_mapFillRect(rect, QTransform::fromScale(factor, factor));
137}
138
139static inline QPoint scaledOffset(const QPoint &pt, qreal factor)
140{
141 return pt * factor;
142}
143
144static QRegion scaledDirtyRegion(const QRegion &region, qreal factor, const QPoint &offset)
145{
146 if (offset.isNull() && factor <= 1)
147 return region;
148
149 QTransform xf = QTransform::fromScale(factor, factor);
150 xf.translate(offset.x(), offset.y());
151 return xf.map(region);
152}
153
154static QMatrix4x4 targetTransform(const QRectF &target, const QRect &viewport, bool invertY)
155{
156 qreal x_scale = target.width() / viewport.width();
157 qreal y_scale = target.height() / viewport.height();
158
159 const QPointF relative_to_viewport = target.topLeft() - viewport.topLeft();
160 qreal x_translate = x_scale - 1 + ((relative_to_viewport.x() / viewport.width()) * 2);
161 qreal y_translate;
162 if (invertY)
163 y_translate = y_scale - 1 + ((relative_to_viewport.y() / viewport.height()) * 2);
164 else
165 y_translate = -y_scale + 1 - ((relative_to_viewport.y() / viewport.height()) * 2);
166
167 QMatrix4x4 matrix;
168 matrix(0,3) = x_translate;
169 matrix(1,3) = y_translate;
170
171 matrix(0,0) = x_scale;
172 matrix(1,1) = (invertY ? -1.0 : 1.0) * y_scale;
173
174 return matrix;
175}
176
181
182static QMatrix3x3 sourceTransform(const QRectF &subTexture,
183 const QSize &textureSize,
185{
186 qreal x_scale = subTexture.width() / textureSize.width();
187 qreal y_scale = subTexture.height() / textureSize.height();
188
189 const QPointF topLeft = subTexture.topLeft();
190 qreal x_translate = topLeft.x() / textureSize.width();
191 qreal y_translate = topLeft.y() / textureSize.height();
192
193 if (origin == SourceTransformOrigin::TopLeft) {
194 y_scale = -y_scale;
195 y_translate = 1 - y_translate;
196 }
197
198 QMatrix3x3 matrix;
199 matrix(0,2) = x_translate;
200 matrix(1,2) = y_translate;
201
202 matrix(0,0) = x_scale;
203 matrix(1,1) = y_scale;
204
205 return matrix;
206}
207
208static inline QRect toBottomLeftRect(const QRect &topLeftRect, int windowHeight)
209{
210 return QRect(topLeftRect.x(), windowHeight - topLeftRect.bottomRight().y() - 1,
211 topLeftRect.width(), topLeftRect.height());
212}
213
214static bool prepareDrawForRenderToTextureWidget(const QPlatformTextureList *textures,
215 int idx,
216 QWindow *window,
217 const QRect &deviceWindowRect,
218 const QPoint &offset,
219 bool invertTargetY,
220 bool invertSource,
221 QMatrix4x4 *target,
222 QMatrix3x3 *source)
223{
224 const QRect clipRect = textures->clipRect(idx);
225 if (clipRect.isEmpty())
226 return false;
227
228 QRect rectInWindow = textures->geometry(idx);
229 // relative to the TLW, not necessarily our window (if the flush is for a native child widget), have to adjust
230 rectInWindow.translate(-offset);
231
232 const QRect clippedRectInWindow = rectInWindow & clipRect.translated(rectInWindow.topLeft());
233 const QRect srcRect = toBottomLeftRect(clipRect, rectInWindow.height());
234
235 *target = targetTransform(scaledRect(clippedRectInWindow, window->devicePixelRatio()),
236 deviceWindowRect,
237 invertTargetY);
238
239 *source = sourceTransform(scaledRect(srcRect, window->devicePixelRatio()),
240 scaledRect(rectInWindow, window->devicePixelRatio()).size(),
241 invertSource ? SourceTransformOrigin::TopLeft : SourceTransformOrigin::BottomLeft);
242
243 return true;
244}
245
246static QShader getShader(const QString &name)
247{
248 QFile f(name);
249 if (f.open(QIODevice::ReadOnly))
250 return QShader::fromSerialized(f.readAll());
251
252 qWarning("QBackingStoreDefaultCompositor: Could not find built-in shader %s "
253 "(is something wrong with QtGui library resources?)",
254 qPrintable(name));
255 return QShader();
256}
257
258static void updateMatrix3x3(QRhiResourceUpdateBatch *resourceUpdates, QRhiBuffer *ubuf, const QMatrix3x3 &m)
259{
260 // mat3 is still 4 floats per column in the uniform buffer (but there is no
261 // 4th column), so 48 bytes altogether, not 36 or 64.
262
263 float f[12];
264 const float *src = static_cast<const float *>(m.constData());
265 float *dst = f;
266 memcpy(dst, src, 3 * sizeof(float));
267 memcpy(dst + 4, src + 3, 3 * sizeof(float));
268 memcpy(dst + 8, src + 6, 3 * sizeof(float));
269
270 resourceUpdates->updateDynamicBuffer(ubuf, 64, 48, f);
271}
272
278
280 QRhiShaderResourceBindings *srb,
281 QRhiRenderPassDescriptor *rpDesc,
282 PipelineBlend blend)
283{
284 QRhiGraphicsPipeline *ps = rhi->newGraphicsPipeline();
285
286 switch (blend) {
288 {
289 QRhiGraphicsPipeline::TargetBlend blend;
290 blend.enable = true;
291 blend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
292 blend.dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha;
293 blend.srcAlpha = QRhiGraphicsPipeline::One;
294 blend.dstAlpha = QRhiGraphicsPipeline::One;
295 ps->setTargetBlends({ blend });
296 }
297 break;
299 {
300 QRhiGraphicsPipeline::TargetBlend blend;
301 blend.enable = true;
302 blend.srcColor = QRhiGraphicsPipeline::One;
303 blend.dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha;
304 blend.srcAlpha = QRhiGraphicsPipeline::One;
305 blend.dstAlpha = QRhiGraphicsPipeline::One;
306 ps->setTargetBlends({ blend });
307 }
308 break;
309 default:
310 break;
311 }
312
313 ps->setShaderStages({
314 { QRhiShaderStage::Vertex, getShader(":/qt-project.org/gui/painting/shaders/backingstorecompose.vert.qsb"_L1) },
315 { QRhiShaderStage::Fragment, getShader(":/qt-project.org/gui/painting/shaders/backingstorecompose.frag.qsb"_L1) }
316 });
317 QRhiVertexInputLayout inputLayout;
318 inputLayout.setBindings({ { 5 * sizeof(float) } });
319 inputLayout.setAttributes({
320 { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
321 { 0, 1, QRhiVertexInputAttribute::Float2, quint32(3 * sizeof(float)) }
322 });
323 ps->setVertexInputLayout(inputLayout);
324 ps->setShaderResourceBindings(srb);
325 ps->setRenderPassDescriptor(rpDesc);
326
327 if (!ps->create()) {
328 qWarning("QBackingStoreDefaultCompositor: Failed to build graphics pipeline");
329 delete ps;
330 return nullptr;
331 }
332 return ps;
333}
334
335static const int UBUF_SIZE = 120;
336
337QBackingStoreDefaultCompositor::PerQuadData QBackingStoreDefaultCompositor::createPerQuadData(QRhiTexture *texture, QRhiTexture *textureExtra)
338{
339 PerQuadData d;
340
341 d.ubuf = m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, UBUF_SIZE);
342 if (!d.ubuf->create())
343 qWarning("QBackingStoreDefaultCompositor: Failed to create uniform buffer");
344
345 d.srb = m_rhi->newShaderResourceBindings();
346 d.srb->setBindings({
347 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d.ubuf, 0, UBUF_SIZE),
348 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, texture, m_samplerNearest.get())
349 });
350 if (!d.srb->create())
351 qWarning("QBackingStoreDefaultCompositor: Failed to create srb");
352 d.lastUsedTexture = texture;
353
354 if (textureExtra) {
355 d.srbExtra = m_rhi->newShaderResourceBindings();
356 d.srbExtra->setBindings({
357 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d.ubuf, 0, UBUF_SIZE),
358 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, textureExtra, m_samplerNearest.get())
359 });
360 if (!d.srbExtra->create())
361 qWarning("QBackingStoreDefaultCompositor: Failed to create srb");
362 }
363
364 d.lastUsedTextureExtra = textureExtra;
365
366 return d;
367}
368
369void QBackingStoreDefaultCompositor::updatePerQuadData(PerQuadData *d, QRhiTexture *texture, QRhiTexture *textureExtra,
370 UpdateQuadDataOptions options)
371{
372 // This whole check-if-texture-ptr-is-different is needed because there is
373 // nothing saying a QPlatformTextureList cannot return a different
374 // QRhiTexture* from the same index in a subsequent flush.
375
376 const QRhiSampler::Filter filter = options.testFlag(NeedsLinearFiltering) ? QRhiSampler::Linear : QRhiSampler::Nearest;
377 if ((d->lastUsedTexture == texture && d->lastUsedFilter == filter) || !d->srb)
378 return;
379
380 QRhiSampler *sampler = filter == QRhiSampler::Linear ? m_samplerLinear.get() : m_samplerNearest.get();
381 d->srb->setBindings({
382 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d->ubuf, 0, UBUF_SIZE),
383 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, texture, sampler)
384 });
385
386 d->srb->updateResources(QRhiShaderResourceBindings::BindingsAreSorted);
387 d->lastUsedTexture = texture;
388 d->lastUsedFilter = filter;
389
390 if (textureExtra) {
391 // The PerQuadData slot may be reused for a stereo (two-texture) widget
392 // after having been created for a non-stereo (single-texture) one, in
393 // which case srbExtra was never allocated.
394 const bool needsCreate = !d->srbExtra;
395 if (needsCreate)
396 d->srbExtra = m_rhi->newShaderResourceBindings();
397
398 d->srbExtra->setBindings({
399 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, d->ubuf, 0, UBUF_SIZE),
400 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, textureExtra, sampler)
401 });
402
403 if (needsCreate) {
404 if (!d->srbExtra->create())
405 qWarning("QBackingStoreDefaultCompositor: Failed to create srb");
406 } else {
407 d->srbExtra->updateResources(QRhiShaderResourceBindings::BindingsAreSorted);
408 }
409 d->lastUsedTextureExtra = textureExtra;
410 }
411}
412
413void QBackingStoreDefaultCompositor::updateUniforms(PerQuadData *d, QRhiResourceUpdateBatch *resourceUpdates,
414 const QMatrix4x4 &target, const QMatrix3x3 &source,
415 UpdateUniformOptions options)
416{
417 resourceUpdates->updateDynamicBuffer(d->ubuf, 0, 64, target.constData());
418 updateMatrix3x3(resourceUpdates, d->ubuf, source);
419 float opacity = 1.0f;
420 resourceUpdates->updateDynamicBuffer(d->ubuf, 112, 4, &opacity);
421 qint32 textureSwizzle = options;
422 resourceUpdates->updateDynamicBuffer(d->ubuf, 116, 4, &textureSwizzle);
423}
424
425void QBackingStoreDefaultCompositor::ensureResources(QRhiResourceUpdateBatch *resourceUpdates, QRhiRenderPassDescriptor *rpDesc)
426{
427 static const float vertexData[] = {
428 -1, -1, 0, 0, 0,
429 -1, 1, 0, 0, 1,
430 1, -1, 0, 1, 0,
431 -1, 1, 0, 0, 1,
432 1, -1, 0, 1, 0,
433 1, 1, 0, 1, 1
434 };
435
436 if (!m_vbuf) {
437 m_vbuf.reset(m_rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData)));
438 if (m_vbuf->create())
439 resourceUpdates->uploadStaticBuffer(m_vbuf.get(), vertexData);
440 else
441 qWarning("QBackingStoreDefaultCompositor: Failed to create vertex buffer");
442 }
443
444 if (!m_samplerNearest) {
445 m_samplerNearest.reset(m_rhi->newSampler(QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
446 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge));
447 if (!m_samplerNearest->create())
448 qWarning("QBackingStoreDefaultCompositor: Failed to create sampler (Nearest filtering)");
449 }
450
451 if (!m_samplerLinear) {
452 m_samplerLinear.reset(m_rhi->newSampler(QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
453 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge));
454 if (!m_samplerLinear->create())
455 qWarning("QBackingStoreDefaultCompositor: Failed to create sampler (Linear filtering)");
456 }
457
458 if (!m_widgetQuadData.isValid())
459 m_widgetQuadData = createPerQuadData(m_texture.get());
460
461 QRhiShaderResourceBindings *srb = m_widgetQuadData.srb; // just for the layout
462 if (!m_psNoBlend)
463 m_psNoBlend.reset(createGraphicsPipeline(m_rhi, srb, rpDesc, PipelineBlend::None));
464 if (!m_psBlend)
465 m_psBlend.reset(createGraphicsPipeline(m_rhi, srb, rpDesc, PipelineBlend::Alpha));
466 if (!m_psPremulBlend)
467 m_psPremulBlend.reset(createGraphicsPipeline(m_rhi, srb, rpDesc, PipelineBlend::PremulAlpha));
468}
469
471 QRhi *rhi,
472 QRhiSwapChain *swapchain,
473 QWindow *window,
474 qreal sourceDevicePixelRatio,
475 const QRegion &region,
476 const QPoint &offset,
477 QPlatformTextureList *textures,
478 bool translucentBackground,
479 qreal sourceTransformFactor)
480{
481 if (!rhi || !swapchain)
482 return QPlatformBackingStore::FlushFailed;
483
484 // Note, the sourceTransformFactor is different from the sourceDevicePixelRatio,
485 // as the former may reflect the fact that the region and offset is pre-transformed,
486 // in which case we don't need to do a full transform here based on the source DPR.
487 // In the default case where no explicit source transform has been passed, we fall
488 // back to the source device pixel ratio.
489 if (!sourceTransformFactor)
490 sourceTransformFactor = sourceDevicePixelRatio;
491
492 Q_ASSERT(textures); // may be empty if there are no render-to-texture widgets at all, but null it cannot be
493
494 if (!m_rhi) {
495 m_rhi = rhi;
496 } else if (m_rhi != rhi) {
497 qWarning("QBackingStoreDefaultCompositor: the QRhi has changed unexpectedly, this should not happen");
498 return QPlatformBackingStore::FlushFailed;
499 }
500
501 if (!qt_window_private(window)->receivedExpose)
502 return QPlatformBackingStore::FlushSuccess;
503
504 qCDebug(lcQpaBackingStore) << "Composing and flushing" << region << "of" << window
505 << "at offset" << offset << "with" << textures->count() << "texture(s) in" << textures
506 << "via swapchain" << swapchain;
507
508 QWindowPrivate::get(window)->lastComposeTime.start();
509
510 if (swapchain->currentPixelSize() != swapchain->surfacePixelSize()) {
511 if (!swapchain->createOrResize()) {
512 return rhi->isDeviceLost() ? QPlatformBackingStore::FlushFailedDueToLostDevice
513 : QPlatformBackingStore::FlushFailed;
514 }
515 }
516
517 // Start recording a new frame.
518 QRhi::FrameOpResult frameResult = rhi->beginFrame(swapchain);
519 if (frameResult == QRhi::FrameOpSwapChainOutOfDate) {
520 if (!swapchain->createOrResize())
521 return QPlatformBackingStore::FlushFailed;
522 frameResult = rhi->beginFrame(swapchain);
523 }
524 if (frameResult == QRhi::FrameOpDeviceLost)
525 return QPlatformBackingStore::FlushFailedDueToLostDevice;
526 if (frameResult != QRhi::FrameOpSuccess)
527 return QPlatformBackingStore::FlushFailed;
528
529 // Prepare resource updates.
530 QRhiResourceUpdateBatch *resourceUpdates = rhi->nextResourceUpdateBatch();
531 QPlatformBackingStore::TextureFlags flags;
532
533 const QRegion dirtyRegion = scaledDirtyRegion(region, sourceTransformFactor, offset);
534 bool gotTextureFromGraphicsBuffer = false;
535 if (QPlatformGraphicsBuffer *graphicsBuffer = backingStore->graphicsBuffer()) {
536 if (graphicsBuffer->lock(QPlatformGraphicsBuffer::SWReadAccess)) {
537 const QImage::Format format = QImage::toImageFormat(graphicsBuffer->format());
538 const QSize size = graphicsBuffer->size();
539 QImage wrapperImage(graphicsBuffer->data(), size.width(), size.height(), graphicsBuffer->bytesPerLine(), format);
540 toTexture(wrapperImage, rhi, resourceUpdates, dirtyRegion, &flags);
541 gotTextureFromGraphicsBuffer = true;
542 graphicsBuffer->unlock();
543 if (graphicsBuffer->origin() == QPlatformGraphicsBuffer::OriginBottomLeft)
544 flags |= QPlatformBackingStore::TextureFlip;
545 }
546 }
547 if (!gotTextureFromGraphicsBuffer)
548 toTexture(backingStore, rhi, resourceUpdates, dirtyRegion, &flags);
549
550 ensureResources(resourceUpdates, swapchain->renderPassDescriptor());
551
552 UpdateUniformOptions uniformOptions;
553#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
554 if (flags & QPlatformBackingStore::TextureSwizzle)
555 uniformOptions |= NeedsRedBlueSwap;
556#else
557 if (flags & QPlatformBackingStore::TextureSwizzle)
558 uniformOptions |= NeedsAlphaRotate;
559#endif
560 const bool premultiplied = (flags & QPlatformBackingStore::TexturePremultiplied) != 0;
562 if (flags & QPlatformBackingStore::TextureFlip)
564
565 const qreal dpr = window->devicePixelRatio();
566 const QRect deviceWindowRect = scaledRect(QRect(QPoint(), window->size()), dpr);
567 const QRect sourceWindowRect = scaledRect(QRect(QPoint(), window->size()), sourceDevicePixelRatio);
568 // If sourceWindowRect is larger than deviceWindowRect, we are doing high
569 // DPI downscaling. In that case Linear filtering is a must, whereas for the
570 // 1:1 case Nearest must be used for Qt 5 visual compatibility.
571 const bool needsLinearSampler = sourceWindowRect.width() > deviceWindowRect.width()
572 && sourceWindowRect.height() > deviceWindowRect.height();
573
574 const bool invertTargetY = !rhi->isYUpInNDC();
575 const bool invertSource = !rhi->isYUpInFramebuffer();
576
577 if (m_texture) {
578 // The backingstore is for the entire tlw. In case of native children, offset tells the position
579 // relative to the tlw. The window rect is scaled by the source device pixel ratio to get
580 // the source rect.
581 const QPoint sourceWindowOffset = scaledOffset(offset, sourceTransformFactor);
582 const QRect srcRect = toBottomLeftRect(sourceWindowRect.translated(sourceWindowOffset), m_texture->pixelSize().height());
583 const QMatrix3x3 source = sourceTransform(srcRect, m_texture->pixelSize(), origin);
584 QMatrix4x4 target; // identity
585 if (invertTargetY)
586 target.data()[5] = -1.0f;
587 updateUniforms(&m_widgetQuadData, resourceUpdates, target, source, uniformOptions);
588 if (needsLinearSampler)
589 updatePerQuadData(&m_widgetQuadData, m_texture.get(), nullptr, NeedsLinearFiltering);
590 }
591
592 const int textureWidgetCount = textures->count();
593 const int oldTextureQuadDataCount = m_textureQuadData.size();
594 if (oldTextureQuadDataCount != textureWidgetCount) {
595 for (int i = textureWidgetCount; i < oldTextureQuadDataCount; ++i)
596 m_textureQuadData[i].reset();
597 m_textureQuadData.resize(textureWidgetCount);
598 }
599
600 for (int i = 0; i < textureWidgetCount; ++i) {
601 const bool invertSourceForTextureWidget = textures->flags(i).testFlag(QPlatformTextureList::MirrorVertically)
602 ? !invertSource : invertSource;
603 QMatrix4x4 target;
604 QMatrix3x3 source;
605 if (!prepareDrawForRenderToTextureWidget(textures, i, window, deviceWindowRect,
606 offset, invertTargetY, invertSourceForTextureWidget,
607 &target, &source))
608 {
609 m_textureQuadData[i].reset();
610 continue;
611 }
612 QRhiTexture *t = textures->texture(i);
613 QRhiTexture *tExtra = textures->textureExtra(i);
614 if (t) {
615 if (!m_textureQuadData[i].isValid())
616 m_textureQuadData[i] = createPerQuadData(t, tExtra);
617 else
618 updatePerQuadData(&m_textureQuadData[i], t, tExtra);
619 updateUniforms(&m_textureQuadData[i], resourceUpdates, target, source);
620 if (needsLinearSampler)
621 updatePerQuadData(&m_textureQuadData[i], t, tExtra, NeedsLinearFiltering);
622 } else {
623 m_textureQuadData[i].reset();
624 }
625 }
626
627 // Record the render pass (with committing the resource updates).
628 QRhiCommandBuffer *cb = swapchain->currentFrameCommandBuffer();
629 const QSize outputSizeInPixels = swapchain->currentPixelSize();
630 QColor clearColor = translucentBackground ? Qt::transparent : Qt::black;
631
632 cb->resourceUpdate(resourceUpdates);
633
634 auto render = [&](std::optional<QRhiSwapChain::StereoTargetBuffer> buffer = std::nullopt) {
635 QRhiRenderTarget* target = nullptr;
636 if (buffer.has_value())
637 target = swapchain->currentFrameRenderTarget(buffer.value());
638 else
639 target = swapchain->currentFrameRenderTarget();
640
641 cb->beginPass(target, clearColor, { 1.0f, 0 });
642
643 cb->setGraphicsPipeline(m_psNoBlend.get());
644 cb->setViewport({ 0, 0, float(outputSizeInPixels.width()), float(outputSizeInPixels.height()) });
645 QRhiCommandBuffer::VertexInput vbufBinding(m_vbuf.get(), 0);
646 cb->setVertexInput(0, 1, &vbufBinding);
647
648 // Textures for renderToTexture widgets.
649 for (int i = 0; i < textureWidgetCount; ++i) {
650 if (!textures->flags(i).testFlag(QPlatformTextureList::StacksOnTop)) {
651 if (m_textureQuadData[i].isValid()) {
652
653 QRhiShaderResourceBindings* srb = m_textureQuadData[i].srb;
654 if (buffer == QRhiSwapChain::RightBuffer && m_textureQuadData[i].srbExtra)
655 srb = m_textureQuadData[i].srbExtra;
656
657 cb->setShaderResources(srb);
658 cb->draw(6);
659 }
660 }
661 }
662
663 cb->setGraphicsPipeline(premultiplied ? m_psPremulBlend.get() : m_psBlend.get());
664
665 // Backingstore texture with the normal widgets.
666 if (m_texture) {
667 cb->setShaderResources(m_widgetQuadData.srb);
668 cb->draw(6);
669 }
670
671 // Textures for renderToTexture widgets that have WA_AlwaysStackOnTop set.
672 for (int i = 0; i < textureWidgetCount; ++i) {
673 const QPlatformTextureList::Flags flags = textures->flags(i);
674 if (flags.testFlag(QPlatformTextureList::StacksOnTop)) {
675 if (m_textureQuadData[i].isValid()) {
676 if (flags.testFlag(QPlatformTextureList::NeedsPremultipliedAlphaBlending))
677 cb->setGraphicsPipeline(m_psPremulBlend.get());
678 else
679 cb->setGraphicsPipeline(m_psBlend.get());
680
681 QRhiShaderResourceBindings* srb = m_textureQuadData[i].srb;
682 if (buffer == QRhiSwapChain::RightBuffer && m_textureQuadData[i].srbExtra)
683 srb = m_textureQuadData[i].srbExtra;
684
685 cb->setShaderResources(srb);
686 cb->draw(6);
687 }
688 }
689 }
690
691 cb->endPass();
692 };
693
694 if (swapchain->window()->format().stereo()) {
695 render(QRhiSwapChain::LeftBuffer);
696 render(QRhiSwapChain::RightBuffer);
697 } else
698 render();
699
700 const QRhi::FrameOpResult endResult = rhi->endFrame(swapchain);
701 if (endResult == QRhi::FrameOpDeviceLost)
702 return QPlatformBackingStore::FlushFailedDueToLostDevice;
703 if (endResult != QRhi::FrameOpSuccess)
704 return QPlatformBackingStore::FlushFailed;
705
706 return QPlatformBackingStore::FlushSuccess;
707}
708
709QT_END_NAMESPACE
QRhiTexture * toTexture(const QPlatformBackingStore *backingStore, QRhi *rhi, QRhiResourceUpdateBatch *resourceUpdates, const QRegion &dirtyRegion, QPlatformBackingStore::TextureFlags *flags) const
QPlatformBackingStore::FlushResult flush(QPlatformBackingStore *backingStore, QRhi *rhi, QRhiSwapChain *swapchain, QWindow *window, qreal sourceDevicePixelRatio, const QRegion &region, const QPoint &offset, QPlatformTextureList *textures, bool translucentBackground, qreal sourceTransformFactor)
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:666
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:726
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:323
Combined button and popup list for selecting options.
static QMatrix4x4 targetTransform(const QRectF &target, const QRect &viewport, bool invertY)
static QRect scaledRect(const QRect &rect, qreal factor)
static QMatrix3x3 sourceTransform(const QRectF &subTexture, const QSize &textureSize, SourceTransformOrigin origin)
static void updateMatrix3x3(QRhiResourceUpdateBatch *resourceUpdates, QRhiBuffer *ubuf, const QMatrix3x3 &m)
static QRect toBottomLeftRect(const QRect &topLeftRect, int windowHeight)
static QShader getShader(const QString &name)
static QPoint scaledOffset(const QPoint &pt, qreal factor)
static bool prepareDrawForRenderToTextureWidget(const QPlatformTextureList *textures, int idx, QWindow *window, const QRect &deviceWindowRect, const QPoint &offset, bool invertTargetY, bool invertSource, QMatrix4x4 *target, QMatrix3x3 *source)
static const int UBUF_SIZE
static QRhiGraphicsPipeline * createGraphicsPipeline(QRhi *rhi, QRhiShaderResourceBindings *srb, QRhiRenderPassDescriptor *rpDesc, PipelineBlend blend)
static QRegion scaledDirtyRegion(const QRegion &region, qreal factor, const QPoint &offset)