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
qssgrhieffectsystem.cpp
Go to the documentation of this file.
1// Copyright (C) 2008-2012 NVIDIA Corporation.
2// Copyright (C) 2020 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6
7#include <QtQuick3DRuntimeRender/private/qssgrhieffectsystem_p.h>
8#include <QtQuick3DRuntimeRender/private/qssgrenderer_p.h>
9#include <QtQuick3DRuntimeRender/private/qssgrhiquadrenderer_p.h>
10#include <QtQuick3DRuntimeRender/private/qssgrendercamera_p.h>
11#include <QtQuick3DRuntimeRender/private/qssglayerrenderdata_p.h>
12#include <QtQuick3DRuntimeRender/private/qssgrenderbuffer_p.h>
13#include <QtQuick3DRuntimeRender/private/qssgrenderimage_p.h>
14
17#include <qtquick3d_tracepoints_p.h>
18
19#include <QtQuick3DUtils/private/qssgassert_p.h>
20
21#include <QtCore/qloggingcategory.h>
22
24
25Q_DECLARE_LOGGING_CATEGORY(lcEffectSystem);
26Q_LOGGING_CATEGORY(lcEffectSystem, "qt.quick3d.effects");
27
47
48QSSGRhiEffectSystem::QSSGRhiEffectSystem(const std::shared_ptr<QSSGRenderContextInterface> &sgContext)
49 : m_sgContext(sgContext)
50{
51}
52
53QSSGRhiEffectSystem::~QSSGRhiEffectSystem()
54{
55 // The uniform buffers for the effect passes are keyed on this object.
56 if (const auto &rhiCtx = m_sgContext->rhiContext(); rhiCtx && rhiCtx->isValid())
57 QSSGRhiContextPrivate::get(rhiCtx.get())->cleanupDrawCallDataForCid(this);
58 releaseResources();
59}
60
61void QSSGRhiEffectSystem::setup(QSize outputSize)
62{
63 if (outputSize.isEmpty()) {
64 releaseResources();
65 return;
66 }
67 m_outSize = outputSize;
68}
69
70QSSGRhiEffectTexture *QSSGRhiEffectSystem::findTexture(const QByteArray &bufferName)
71{
72 auto findTexture = [bufferName](const QSSGRhiEffectTexture *rt){ return rt->name == bufferName; };
73 const auto foundIt = std::find_if(m_textures.cbegin(), m_textures.cend(), findTexture);
74 QSSGRhiEffectTexture *result = foundIt == m_textures.cend() ? nullptr : *foundIt;
75 return result;
76}
77
78QSSGRhiEffectTexture *QSSGRhiEffectSystem::getTexture(const QByteArray &bufferName,
79 const QSize &size,
80 QRhiTexture::Format format,
81 bool isFinalOutput,
82 const QSSGRenderEffect *inEffect,
83 quint8 viewCount)
84{
85 QSSGRhiEffectTexture *result = findTexture(bufferName);
86 const bool gotMatch = result != nullptr;
87
88 // If not found, look for an unused texture. Prefer one that already has
89 // the right size and format. Failing that, pick one that has not been
90 // used in this frame, so that it can be rebuilt in place. Unused textures
91 // that were used earlier in this frame (e.g. the output of a previous
92 // effect) are still referenced by the commands recorded for the frame, so
93 // rather than rebuilding those, add a new texture to the pool. This way
94 // the pool settles after a frame or two (for Effects with Buffers with
95 // sizeMultipliers on them, or ones that use different formats), the
96 // QRhiTexture objects stay the same, and rebuilds only happen when the
97 // output size changes.
98 const quint32 currentFrame = m_sgContext->renderer()->frameCount();
99 if (!result) {
100 QSSGRhiEffectTexture *notUsedInFrame = nullptr;
101 for (QSSGRhiEffectTexture *t : std::as_const(m_textures)) {
102 if (!t->name.isEmpty())
103 continue;
104 if (t->texture->pixelSize() == size && t->texture->format() == format) {
105 result = t;
106 break;
107 }
108 if (!notUsedInFrame && t->lastUsedFrame != currentFrame)
109 notUsedInFrame = t;
110 }
111 if (!result)
112 result = notUsedInFrame;
113 if (result)
114 result->desc = {};
115 }
116
117 if (!result) {
118 result = new QSSGRhiEffectTexture {};
119 m_textures.append(result);
120 }
121
122 const auto &rhiCtx = m_sgContext->rhiContext();
123 QRhi *rhi = rhiCtx->rhi();
124 const bool formatChanged = result->texture && result->texture->format() != format;
125 const bool needsRebuild = result->texture && (result->texture->pixelSize() != size || formatChanged);
126
127 QRhiTexture::Flags flags = QRhiTexture::RenderTarget;
128 if (isFinalOutput) // play nice with progressive/temporal AA
129 flags |= QRhiTexture::UsedAsTransferSource;
130
131 if (needsRebuild && result->lastUsedFrame == currentFrame) {
132 // The texture may be referenced by commands already recorded for this
133 // frame. Calling create() on it again would release its native
134 // resources right away (e.g. the SRV with D3D11, where the commands
135 // are only executed in endFrame()). Replace the objects instead, and
136 // let the old ones go away when the frame is submitted.
137 m_pendingClears.remove(result->renderTarget);
138 result->renderTarget->deleteLater();
139 result->renderTarget = nullptr;
140 result->renderPassDescriptor->deleteLater();
141 result->renderPassDescriptor = nullptr;
142 result->texture->deleteLater();
143 result->texture = nullptr;
144 }
145
146 if (!result->texture) {
147 if (viewCount >= 2)
148 result->texture = rhi->newTextureArray(format, viewCount, size, 1, flags);
149 else
150 result->texture = rhi->newTexture(format, size, 1, flags);
151 result->texture->create();
152 } else if (needsRebuild) {
153 result->texture->setFlags(flags);
154 result->texture->setPixelSize(size);
155 result->texture->setFormat(format);
156 result->texture->create();
157 }
158
159 const bool newRenderTarget = !result->renderTarget;
160 if (newRenderTarget) {
161 QRhiColorAttachment colorAttachment(result->texture);
162 colorAttachment.setMultiViewCount(viewCount);
163 QRhiTextureRenderTargetDescription desc(colorAttachment);
164 result->renderTarget = rhi->newTextureRenderTarget(desc);
165 result->renderPassDescriptor = result->renderTarget->newCompatibleRenderPassDescriptor();
166 result->renderTarget->setRenderPassDescriptor(result->renderPassDescriptor);
167 result->renderTarget->create();
168 m_pendingClears.insert(result->renderTarget);
169 } else if (needsRebuild) {
170 if (formatChanged) {
171 delete result->renderPassDescriptor;
172 result->renderPassDescriptor = result->renderTarget->newCompatibleRenderPassDescriptor();
173 result->renderTarget->setRenderPassDescriptor(result->renderPassDescriptor);
174 }
175 result->renderTarget->create();
176 m_pendingClears.insert(result->renderTarget);
177 }
178
179 if (!gotMatch || newRenderTarget) {
180 QByteArray rtName = inEffect->debugObjectName.toLatin1();
181 rtName += QByteArrayLiteral(" effect pass ");
182 rtName += bufferName;
183 result->renderTarget->setName(rtName);
184 }
185
186 result->name = bufferName;
187 result->lastUsedFrame = currentFrame;
188 return result;
189}
190
191void QSSGRhiEffectSystem::releaseTexture(QSSGRhiEffectTexture *texture)
192{
193 // Mark as unused by setting the name to empty, unless the Buffer had scene
194 // lifetime on it (then it needs to live on for ever).
195 if (!texture->flags.isSceneLifetime())
196 texture->name = {};
197}
198
199void QSSGRhiEffectSystem::releaseTextures()
200{
201 for (auto *t : std::as_const(m_textures))
202 releaseTexture(t);
203}
204
205QRhiTexture *QSSGRhiEffectSystem::process(const QSSGRenderLayer &layer,
206 QRhiTexture *inTexture,
207 QRhiTexture *inDepthTexture,
208 QRhiTexture *inNormalTexture,
209 QRhiTexture *inMotionVectorTexture)
210{
211 QSSG_ASSERT(m_sgContext != nullptr, return inTexture);
212 QSSG_ASSERT(layer.firstEffect != nullptr, return inTexture);
213 const auto &rhiContext = m_sgContext->rhiContext();
214 const auto &renderer = m_sgContext->renderer();
215 QSSG_ASSERT(rhiContext && renderer, return inTexture);
216
217 const auto viewCount = layer.viewCount;
218
219 m_depthTexture = inDepthTexture;
220 m_normalTexture = inNormalTexture;
221 m_motionVectorTexture = inMotionVectorTexture;
222 m_cameraClipRange = layer.renderedCameras[0]->clipPlanes;
223
224 bool usesProjectionMatrix = false;
225 bool usesViewMatrix = false;
226 for (const QSSGRenderEffect *eff = layer.firstEffect; eff; eff = eff->m_nextEffect) {
227 if (eff->testFlag(QSSGRenderEffect::Flags::UsesProjectionMatrix)
228 || eff->testFlag(QSSGRenderEffect::Flags::UsesInverseProjectionMatrix))
229 {
230 usesProjectionMatrix = true;
231 }
232 if (eff->testFlag(QSSGRenderEffect::Flags::UsesViewMatrix))
233 usesViewMatrix = true;
234 }
235
236 if (usesProjectionMatrix) {
237 m_projectionMatrices.resize(viewCount);
238 const QMatrix4x4 clipSpaceCorrMatrix = rhiContext->rhi()->clipSpaceCorrMatrix();
239 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
240 m_projectionMatrices[viewIndex] = clipSpaceCorrMatrix * layer.renderedCameras[viewIndex]->projection;
241 }
242
243 if (usesViewMatrix) {
244 QMatrix4x4 camGlobalTransforms[2] { QMatrix4x4{Qt::Uninitialized}, QMatrix4x4{Qt::Uninitialized} };
245 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
246 camGlobalTransforms[viewIndex] = layer.renderData->getGlobalTransform(*layer.renderedCameras[viewIndex]);
247 m_viewMatrices.resize(viewCount);
248 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
249 m_viewMatrices[viewIndex] = camGlobalTransforms[viewIndex].inverted();
250 }
251
252 m_currentUbufIndex = 0;
253 // FIXME: Keeping the change minimal for now, but we should avoid the need for this cast.
254 QSSGRenderEffect *currentEffect = const_cast<QSSGRenderEffect *>(layer.firstEffect);
255 QSSGRhiEffectTexture firstTex{ inTexture, nullptr, nullptr, {}, {}, {} };
256 auto *latestOutput = doRenderEffect(currentEffect, &firstTex, viewCount);
257 firstTex.texture = nullptr; // make sure we don't delete inTexture when we go out of scope
258
259 while ((currentEffect = currentEffect->m_nextEffect)) {
260 QSSGRhiEffectTexture *effectOut = doRenderEffect(currentEffect, latestOutput, viewCount);
261 releaseTexture(latestOutput);
262 latestOutput = effectOut;
263 }
264
265 releaseTextures();
266 return latestOutput ? latestOutput->texture : nullptr;
267}
268
269void QSSGRhiEffectSystem::releaseResources()
270{
271 qDeleteAll(m_textures);
272 m_textures.clear();
273
274 m_shaderPipelines.clear();
275}
276
277QSSGRenderTextureFormat::Format QSSGRhiEffectSystem::overriddenOutputFormat(const QSSGRenderEffect *inEffect)
278{
279 QSSGRenderTextureFormat::Format format = QSSGRenderTextureFormat::Unknown;
280 for (const QSSGCommand *cmd : inEffect->commands) {
281 if (cmd->m_type == CommandType::BindTarget) {
282 const QSSGBindTarget *targetCmd = static_cast<const QSSGBindTarget *>(cmd);
283 format = targetCmd->m_outputFormat == QSSGRenderTextureFormat::Unknown
284 ? inEffect->outputFormat : targetCmd->m_outputFormat.format;
285 }
286 }
287 return format;
288}
289
290QSSGRhiEffectTexture *QSSGRhiEffectSystem::doRenderEffect(const QSSGRenderEffect *inEffect,
291 QSSGRhiEffectTexture *inTexture,
292 quint8 viewCount)
293{
294 // Run through the effect commands and render the effect.
295 qCDebug(lcEffectSystem) << "START effect " << inEffect->className;
296 QSSGRhiEffectTexture *finalOutputTexture = nullptr;
297 QSSGRhiEffectTexture *currentOutput = nullptr;
298 QSSGRhiEffectTexture *currentInput = inTexture;
299 for (const QSSGCommand *theCommand : inEffect->commands) {
300 qCDebug(lcEffectSystem).noquote() << " >" << theCommand->typeAsString() << "--" << theCommand->debugString();
301
302 switch (theCommand->m_type) {
303 case CommandType::AllocateBuffer:
304 allocateBufferCmd(static_cast<const QSSGAllocateBuffer *>(theCommand), inTexture, inEffect, viewCount);
305 break;
306
307 case CommandType::ApplyBufferValue: {
308 auto *applyCommand = static_cast<const QSSGApplyBufferValue *>(theCommand);
309
310 /*
311 BufferInput { buffer: buf }
312 -> INPUT (qt_inputTexture) in the shader samples the texture for Buffer buf in the pass
313 BufferInput { sampler: "ttt" }
314 -> ttt in the shader samples the input texture for the pass
315 (ttt also needs to be a TextureInput with a Texture{} to get the sampler declared in the shader code,
316 beware that without the BufferInput the behavior would change: ttt would then sample a dummy texture)
317 BufferInput { buffer: buf; sampler: "ttt" }
318 -> ttt in the shader samples the texture for Buffer buf in the pass
319 */
320
321 auto *buffer = applyCommand->m_bufferName.isEmpty() ? inTexture : findTexture(applyCommand->m_bufferName);
322 if (applyCommand->m_samplerName.isEmpty())
323 currentInput = buffer;
324 else
325 addTextureToShaderPipeline(applyCommand->m_samplerName, buffer->texture, buffer->desc);
326 break;
327 }
328
329 case CommandType::ApplyInstanceValue:
330 applyInstanceValueCmd(static_cast<const QSSGApplyInstanceValue *>(theCommand), inEffect);
331 break;
332
333 case CommandType::ApplyValue:
334 applyValueCmd(static_cast<const QSSGApplyValue *>(theCommand), inEffect);
335 break;
336
337 case CommandType::BindBuffer: {
338 auto *bindCmd = static_cast<const QSSGBindBuffer *>(theCommand);
339 currentOutput = findTexture(bindCmd->m_bufferName);
340 break;
341 }
342
343 case CommandType::BindShader:
344 bindShaderCmd(static_cast<const QSSGBindShader *>(theCommand), inEffect, viewCount);
345 break;
346
347 case CommandType::BindTarget: {
348 auto targetCmd = static_cast<const QSSGBindTarget*>(theCommand);
349 // matches overriddenOutputFormat()
350 QSSGRenderTextureFormat::Format f = targetCmd->m_outputFormat == QSSGRenderTextureFormat::Unknown ?
351 inEffect->outputFormat : targetCmd->m_outputFormat.format;
352 // f is now either Unknown (common case), or if the effect overrides the output format, then that
353 QRhiTexture::Format rhiFormat = f == QSSGRenderTextureFormat::Unknown ?
354 currentInput->texture->format() : QSSGBufferManager::toRhiFormat(f);
355 qCDebug(lcEffectSystem) << " Target format override" << QSSGBaseTypeHelpers::toString(f) << "Effective RHI format" << rhiFormat;
356 // Make sure we use different names for each effect inside one frame
357 QByteArray tmpName = QByteArrayLiteral("__output_").append(QByteArray::number(m_currentUbufIndex));
358 currentOutput = getTexture(tmpName, m_outSize, rhiFormat, true, inEffect, viewCount);
359 finalOutputTexture = currentOutput;
360 break;
361 }
362
363 case CommandType::Render:
364 renderCmd(inEffect, currentInput, currentOutput, viewCount);
365 currentInput = inTexture; // default input for each new pass is defined to be original input
366 break;
367
368 default:
369 qWarning() << "Effect command" << theCommand->typeAsString() << "not implemented";
370 break;
371 }
372 }
373 // TODO: release textures used by this effect now, instead of after processing all the effects
374 qCDebug(lcEffectSystem) << "END effect " << inEffect->className;
375 return finalOutputTexture;
376}
377
378void QSSGRhiEffectSystem::allocateBufferCmd(const QSSGAllocateBuffer *inCmd,
379 QSSGRhiEffectTexture *inTexture,
380 const QSSGRenderEffect *inEffect,
381 quint8 viewCount)
382{
383 // Note: Allocate is used both to allocate new, and refer to buffer created earlier
384 QSize bufferSize(m_outSize * qreal(inCmd->m_sizeMultiplier));
385
386 QSSGRenderTextureFormat f = inCmd->m_format;
387 QRhiTexture::Format rhiFormat = (f == QSSGRenderTextureFormat::Unknown) ? inTexture->texture->format()
388 : QSSGBufferManager::toRhiFormat(f);
389
390 QSSGRhiEffectTexture *buf = getTexture(inCmd->m_name, bufferSize, rhiFormat, false, inEffect, viewCount);
391 auto filter = QSSGRhiHelpers::toRhi(inCmd->m_filterOp);
392 auto tiling = QSSGRhiHelpers::toRhi(inCmd->m_texCoordOp);
393 buf->desc = { filter, filter, QRhiSampler::None, tiling, tiling, QRhiSampler::Repeat };
394 buf->flags = inCmd->m_bufferFlags;
395}
396
397void QSSGRhiEffectSystem::applyInstanceValueCmd(const QSSGApplyInstanceValue *inCmd, const QSSGRenderEffect *inEffect)
398{
399 if (!m_currentShaderPipeline)
400 return;
401
402 const bool setAll = inCmd->m_propertyName.isEmpty();
403 for (const QSSGRenderEffect::Property &property : std::as_const(inEffect->properties)) {
404 if (setAll || property.name == inCmd->m_propertyName) {
405 if (property.shaderDataType == QSSGRenderShaderValue::StorageBuffer
406 || property.shaderDataType == QSSGRenderShaderValue::Image) {
407 m_currentShaderPipeline->setShaderResources(m_currentUBufData, *m_sgContext->bufferManager(),
408 property.name, property.value, property.shaderDataType);
409 } else {
410 m_currentShaderPipeline->setUniformValue(m_currentUBufData, property.name, property.value, property.shaderDataType);
411 }
412 //qCDebug(lcEffectSystem) << "setUniformValue" << property.name << toString(property.shaderDataType) << "to" << property.value;
413 }
414 }
415 for (const QSSGRenderEffect::TextureProperty &textureProperty : std::as_const(inEffect->textureProperties)) {
416 if (setAll || textureProperty.name == inCmd->m_propertyName) {
417 bool texAdded = false;
418 QSSGRenderImage *image = textureProperty.texImage;
419 if (image) {
420 const auto &theBufferManager(m_sgContext->bufferManager());
421 const QSSGRenderImageTexture texture = theBufferManager->loadRenderImage(image);
422 if (texture.m_texture) {
423 const QSSGRhiSamplerDescription desc{
424 QSSGRhiHelpers::toRhi(textureProperty.minFilterType),
425 QSSGRhiHelpers::toRhi(textureProperty.magFilterType),
426 textureProperty.mipFilterType != QSSGRenderTextureFilterOp::None ? QSSGRhiHelpers::toRhi(textureProperty.mipFilterType) : QRhiSampler::None,
427 QSSGRhiHelpers::toRhi(textureProperty.horizontalClampType),
428 QSSGRhiHelpers::toRhi(textureProperty.verticalClampType),
429 QSSGRhiHelpers::toRhi(textureProperty.zClampType)
430 };
431 addTextureToShaderPipeline(textureProperty.name, texture.m_texture, desc);
432 texAdded = true;
433 }
434 }
435 if (!texAdded) {
436 // Something went wrong, e.g. image file not found. Still need to add a dummy texture for the shader
437 qCDebug(lcEffectSystem) << "Using dummy texture for property" << textureProperty.name;
438 addTextureToShaderPipeline(textureProperty.name, nullptr, {});
439 }
440 }
441 }
442}
443
444void QSSGRhiEffectSystem::applyValueCmd(const QSSGApplyValue *inCmd, const QSSGRenderEffect *inEffect)
445{
446 if (!m_currentShaderPipeline)
447 return;
448
449 const auto &properties = inEffect->properties;
450 const auto foundIt = std::find_if(properties.cbegin(), properties.cend(), [inCmd](const QSSGRenderEffect::Property &prop) {
451 return (prop.name == inCmd->m_propertyName);
452 });
453
454 if (foundIt != properties.cend())
455 m_currentShaderPipeline->setUniformValue(m_currentUBufData, inCmd->m_propertyName, inCmd->m_value, foundIt->shaderDataType);
456 else
457 qWarning() << "Could not find effect property" << inCmd->m_propertyName;
458}
459
460static const char *effect_builtin_textureMapUV =
461 "vec2 qt_effectTextureMapUV(vec2 uv)\n"
462 "{\n"
463 " return uv;\n"
464 "}\n";
465
467 "vec2 qt_effectTextureMapUV(vec2 uv)\n"
468 "{\n"
469 " return vec2(uv.x, 1.0 - uv.y);\n"
470 "}\n";
471
472QSSGRhiShaderPipelinePtr QSSGRhiEffectSystem::buildShaderForEffect(const QSSGBindShader &inCmd,
473 QSSGProgramGenerator &generator,
474 QSSGShaderLibraryManager &shaderLib,
475 QSSGShaderCache &shaderCache,
476 bool isYUpInFramebuffer,
477 int viewCount)
478{
479 const auto &key = inCmd.m_shaderPathKey;
480 qCDebug(lcEffectSystem) << " generating new shader pipeline for: " << key;
481
482 generator.beginProgram();
483
484 {
485 const QByteArray src = shaderLib.getShaderSource(inCmd.m_shaderPathKey, QSSGShaderCache::ShaderType::Vertex);
486 QSSGStageGeneratorBase *vStage = generator.getStage(QSSGShaderGeneratorStage::Vertex);
487 // The variation based on isYUpInFramebuffer is captured in 'key' as
488 // well, so it is safe to vary the source code here.
489 vStage->append(isYUpInFramebuffer ? effect_builtin_textureMapUV : effect_builtin_textureMapUVFlipped);
490 vStage->append(src);
491 }
492 {
493 const QByteArray src = shaderLib.getShaderSource(inCmd.m_shaderPathKey, QSSGShaderCache::ShaderType::Fragment);
494 QSSGStageGeneratorBase *fStage = generator.getStage(QSSGShaderGeneratorStage::Fragment);
495 fStage->append(src);
496 }
497
498 return generator.compileGeneratedRhiShader(key,
499 shaderLib.getShaderMetaData(inCmd.m_shaderPathKey, QSSGShaderCache::ShaderType::Fragment).features,
500 shaderLib,
501 shaderCache,
502 QSSGRhiShaderPipeline::UsedWithoutIa,
503 {},
504 viewCount,
505 false);
506}
507
508void QSSGRhiEffectSystem::bindShaderCmd(const QSSGBindShader *inCmd, const QSSGRenderEffect *inEffect, quint8 viewCount)
509{
510 QElapsedTimer timer;
511 timer.start();
512
513 m_currentTextures.clear();
514 m_pendingClears.clear();
515 m_currentShaderPipeline = nullptr;
516
517 const auto &rhiCtx = m_sgContext->rhiContext();
518 QRhi *rhi = rhiCtx->rhi();
519 const auto &shaderLib = m_sgContext->shaderLibraryManager();
520 const auto &shaderCache = m_sgContext->shaderCache();
521
522 // Now we need a proper unique key (unique in the scene), the filenames are
523 // not sufficient. This means that using the same shader source files in
524 // multiple Effects in the same scene will work. It wouldn't if all those
525 // Effects reused the same QSSGRhiShaderPipeline (i.e. if the only cache
526 // key was the m_shaderPathKey).
527 QSSGEffectSceneCacheKey cacheKey;
528 cacheKey.m_shaderPathKey = inCmd->m_shaderPathKey;
529 cacheKey.m_cmd = quintptr(inCmd);
530 cacheKey.m_ubufIndex = m_currentUbufIndex;
531 cacheKey.updateHashCode();
532
533 // look for a runtime pipeline
534 const auto it = m_shaderPipelines.constFind(cacheKey);
535 if (it != m_shaderPipelines.cend())
536 m_currentShaderPipeline = (*it).get();
537
538 QByteArray qsbcKey;
539 QSSGShaderFeatures features;
540 if (!m_currentShaderPipeline) { // don't spend time if already got the pipeline
541 features = shaderLib->getShaderMetaData(inCmd->m_shaderPathKey, QSSGShaderCache::ShaderType::Fragment).features;
542 qsbcKey = QQsbCollection::EntryDesc::generateSha(inCmd->m_shaderPathKey, QQsbCollection::toFeatureSet(features));
543 }
544
545 // Check if there's a build-time generated entry for this effect
546 if (!m_currentShaderPipeline && !shaderLib->m_preGeneratedShaderEntries.isEmpty()) {
547 const QQsbCollection::EntryMap &pregenEntries = shaderLib->m_preGeneratedShaderEntries;
548 const auto foundIt = pregenEntries.constFind(QQsbCollection::Entry(qsbcKey));
549 if (foundIt != pregenEntries.cend()) {
550 // The result here is always a new QSSGRhiShaderPipeline, which
551 // fulfills the requirements of our local cache (cmd/ubufIndex in
552 // cacheKey, not needed here since the result is a new object).
553 const auto &shader = shaderCache->newPipelineFromPregenerated(inCmd->m_shaderPathKey,
554 features,
555 *foundIt,
556 *inEffect,
557 QSSGRhiShaderPipeline::UsedWithoutIa);
558 m_shaderPipelines.insert(cacheKey, shader);
559 m_currentShaderPipeline = shader.get();
560 }
561 }
562
563 if (!m_currentShaderPipeline) {
564 // Try the persistent (disk-based) cache then. The result here is
565 // always a new QSSGRhiShaderPipeline, which fulfills the requirements
566 // of our local cache (cmd/ubufIndex in cacheKey, not needed here since
567 // the result is a new object). Alternatively, the result may be null
568 // if there was no hit.
569 const auto &shaderPipeline = shaderCache->tryNewPipelineFromPersistentCache(qsbcKey,
570 inCmd->m_shaderPathKey,
571 features,
572 QSSGRhiShaderPipeline::UsedWithoutIa);
573 if (shaderPipeline) {
574 m_shaderPipelines.insert(cacheKey, shaderPipeline);
575 m_currentShaderPipeline = shaderPipeline.get();
576 }
577 }
578
579 if (!m_currentShaderPipeline) {
580 // Final option, generate the shader pipeline
581 Q_TRACE_SCOPE(QSSG_generateShader);
582 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DGenerateShader);
583 const auto &generator = m_sgContext->shaderProgramGenerator();
584 if (auto stages = buildShaderForEffect(*inCmd, *generator, *shaderLib, *shaderCache, rhi->isYUpInFramebuffer(), viewCount)) {
585 m_shaderPipelines.insert(cacheKey, stages);
586 m_currentShaderPipeline = stages.get();
587 }
588 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DGenerateShader, 0, inEffect->profilingId);
589 }
590
591 const auto &rhiContext = m_sgContext->rhiContext();
592
593 if (m_currentShaderPipeline) {
594 const void *cacheKey1 = reinterpret_cast<const void *>(this);
595 const void *cacheKey2 = reinterpret_cast<const void *>(qintptr(m_currentUbufIndex));
596 QSSGRhiDrawCallData &dcd = QSSGRhiContextPrivate::get(rhiContext.get())->drawCallData({ cacheKey1, cacheKey2,
597 nullptr, nullptr, 0 });
598 m_currentShaderPipeline->ensureCombinedUniformBuffer(&dcd.ubuf);
599 m_currentUBufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
600 } else {
601 m_currentUBufData = nullptr;
602 }
603
604 QSSGRhiContextStats::get(*rhiContext).registerEffectShaderGenerationTime(timer.elapsed());
605}
606
607void QSSGRhiEffectSystem::renderCmd(const QSSGRenderEffect *inEffect, QSSGRhiEffectTexture *inTexture, QSSGRhiEffectTexture *target, quint8 viewCount)
608{
609 if (!m_currentShaderPipeline)
610 return;
611
612 if (!target) {
613 qWarning("No effect render target?");
614 return;
615 }
616
617 // the shader only uses one of these (or none)
618 addTextureToShaderPipeline(QByteArrayLiteral("qt_inputTexture"), inTexture->texture, inTexture->desc);
619 addTextureToShaderPipeline(QByteArrayLiteral("qt_inputTextureArray"), inTexture->texture, inTexture->desc);
620
621 const auto &rhiContext = m_sgContext->rhiContext();
622 const auto &renderer = m_sgContext->renderer();
623 m_sgContext->bufferManager()->commitBufferResourceUpdates();
624
625 QRhiCommandBuffer *cb = rhiContext->commandBuffer();
626 cb->debugMarkBegin(QByteArrayLiteral("Post-processing effect"));
627 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
628
629 for (QRhiTextureRenderTarget *rt : std::as_const(m_pendingClears)) {
630 // Effects like motion blur use an accumulator texture that should
631 // start out empty (and they are sampled in the first pass), so such
632 // textures need an explicit clear. It is not applicable for the common
633 // case of outputting into a texture because that will get a clear
634 // anyway when rendering the quad.
635 if (rt != target->renderTarget) {
636 cb->beginPass(rt, Qt::transparent, { 1.0f, 0 }, nullptr, rhiContext->commonPassFlags());
637 QSSGRHICTX_STAT(rhiContext, beginRenderPass(rt));
638 cb->endPass();
639 QSSGRHICTX_STAT(rhiContext, endRenderPass());
640 }
641 }
642 m_pendingClears.clear();
643
644 const QSize inputSize = inTexture->texture->pixelSize();
645 const QSize outputSize = target->texture->pixelSize();
646 addCommonEffectUniforms(inEffect, inputSize, outputSize, viewCount);
647
648 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiContext.get());
649
650 const void *cacheKey1 = reinterpret_cast<const void *>(this);
651 const void *cacheKey2 = reinterpret_cast<const void *>(qintptr(m_currentUbufIndex));
652 QSSGRhiDrawCallData &dcd = rhiCtxD->drawCallData({ cacheKey1, cacheKey2, nullptr, nullptr, 0 });
653 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
654 m_currentUBufData = nullptr;
655
656 QRhiResourceUpdateBatch *rub = rhiContext->rhi()->nextResourceUpdateBatch();
657
658 // do resource bindings
659 const QRhiShaderResourceBinding::StageFlags VISIBILITY_ALL =
660 QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage;
661 QSSGRhiShaderResourceBindingList bindings;
662 for (const QSSGRhiTexture &rhiTex : std::as_const(m_currentTextures)) {
663 int binding = m_currentShaderPipeline->bindingForTexture(rhiTex.name);
664 if (binding < 0) // may not be used in the shader (think qt_inputTexture, it's not given a shader samples INPUT)
665 continue;
666 qCDebug(lcEffectSystem) << " -> texture binding" << binding << "for" << rhiTex.name;
667 // Make sure to bind all samplers even if the texture is missing, otherwise we can get crash on some graphics APIs
668 QRhiTexture *texture = rhiTex.texture ? rhiTex.texture
669 : QSSGRhiHelpers::dummyTextureForSampler(
670 rhiContext.get(),
671 QSSGRhiHelpers::samplerType(*m_currentShaderPipeline, rhiTex.name),
672 rub, viewCount);
673 bindings.addTexture(binding,
674 QRhiShaderResourceBinding::FragmentStage,
675 texture,
676 rhiContext->sampler(rhiTex.samplerDesc));
677 }
678 bindings.addUniformBuffer(0, VISIBILITY_ALL, dcd.ubuf);
679 m_currentShaderPipeline->applyAndClearStorageBindings(VISIBILITY_ALL, bindings);
680
681 // Submits the batch, so this must come after the dummy textures above have
682 // queued their contents into it.
683 renderer->rhiQuadRenderer()->prepareQuad(rhiContext.get(), rub);
684
685 QRhiShaderResourceBindings *srb = rhiCtxD->srb(bindings);
686
687 QSSGRhiGraphicsPipelineState ps;
688 ps.viewport = QRhiViewport(0, 0, float(outputSize.width()), float(outputSize.height()));
689 ps.samples = target->renderTarget->sampleCount();
690 ps.viewCount = viewCount;
691 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(ps, m_currentShaderPipeline);
692
693 renderer->rhiQuadRenderer()->recordRenderQuadPass(rhiContext.get(), &ps, srb, target->renderTarget, QSSGRhiQuadRenderer::UvCoords);
694 m_currentUbufIndex++;
695 cb->debugMarkEnd();
696 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, 0, QByteArrayLiteral("post_processing_effect"));
697}
698
699void QSSGRhiEffectSystem::addCommonEffectUniforms(const QSSGRenderEffect *inEffect, const QSize &inputSize, const QSize &outputSize, quint8 viewCount)
700{
701 const auto &rhiContext = m_sgContext->rhiContext();
702 QRhi *rhi = rhiContext->rhi();
703
704 QMatrix4x4 mvp;
705 if (rhi->isYUpInFramebuffer() != rhi->isYUpInNDC())
706 mvp.data()[5] = -1.0f;
707 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_modelViewProjection", mvp, QSSGRenderShaderValue::Matrix4x4);
708
709 const bool usesProjectionMatrix = inEffect->testFlag(QSSGRenderEffect::Flags::UsesProjectionMatrix);
710 const bool usesInverseProjectionMatrix = inEffect->testFlag(QSSGRenderEffect::Flags::UsesInverseProjectionMatrix);
711 if (usesProjectionMatrix || usesInverseProjectionMatrix) {
712 if (viewCount < 2) {
713 if (usesProjectionMatrix)
714 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_projectionMatrix", m_projectionMatrices[0], QSSGRenderShaderValue::Matrix4x4);
715 if (usesInverseProjectionMatrix)
716 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_inverseProjectionMatrix", m_projectionMatrices[0].inverted(), QSSGRenderShaderValue::Matrix4x4);
717 } else {
718 if (usesProjectionMatrix)
719 m_currentShaderPipeline->setUniformArray(m_currentUBufData, "qt_projectionMatrix", m_projectionMatrices.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
720 if (usesInverseProjectionMatrix) {
721 QVarLengthArray<QMatrix4x4, 2> invertedProjections(viewCount);
722 for (quint8 viewIndex = 0; viewIndex < viewCount; ++viewIndex)
723 invertedProjections[viewIndex] = m_projectionMatrices[viewIndex].inverted();
724 m_currentShaderPipeline->setUniformArray(m_currentUBufData, "qt_inverseProjectionMatrix", invertedProjections.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
725 }
726 }
727 }
728
729 if (inEffect->testFlag(QSSGRenderEffect::Flags::UsesViewMatrix)) {
730 if (viewCount < 2)
731 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_viewMatrix", m_viewMatrices[0], QSSGRenderShaderValue::Matrix4x4);
732 else
733 m_currentShaderPipeline->setUniformArray(m_currentUBufData, "qt_viewMatrix", m_viewMatrices.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
734 }
735
736 QVector2D size(inputSize.width(), inputSize.height());
737 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_inputSize", size, QSSGRenderShaderValue::Vec2);
738
739 size = QVector2D(outputSize.width(), outputSize.height());
740 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_outputSize", size, QSSGRenderShaderValue::Vec2);
741
742 float fc = float(m_sgContext->renderer()->frameCount());
743 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_frame_num", fc, QSSGRenderShaderValue::Float);
744
745 // Bames and values for uniforms that are also used by default and/or
746 // custom materials must always match, effects must not deviate.
747
748 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_cameraProperties", m_cameraClipRange, QSSGRenderShaderValue::Vec2);
749
750 float vp = rhi->isYUpInFramebuffer() ? 1.0f : -1.0f;
751 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_normalAdjustViewportFactor", vp, QSSGRenderShaderValue::Float);
752
753 const float nearClip = rhi->isClipDepthZeroToOne() ? 0.0f : -1.0f;
754 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_nearClipValue", nearClip, QSSGRenderShaderValue::Float);
755
756 const QVector4D rhiProperties(
757 rhi->isYUpInFramebuffer() ? 1.0f : -1.0f,
758 rhi->isYUpInNDC() ? 1.0f : -1.0f,
759 rhi->isClipDepthZeroToOne() ? 0.0f : -1.0f,
760 0.0f // unused
761 );
762 m_currentShaderPipeline->setUniformValue(m_currentUBufData, "qt_rhi_properties", rhiProperties, QSSGRenderShaderValue::Vec4);
763
764 if (m_depthTexture) {
765 static const QSSGRhiSamplerDescription depthSamplerDesc {
766 QRhiSampler::Nearest, QRhiSampler::Nearest,
767 QRhiSampler::None,
768 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat
769 };
770 addTextureToShaderPipeline("qt_depthTexture", m_depthTexture, depthSamplerDesc);
771 addTextureToShaderPipeline("qt_depthTextureArray", m_depthTexture, depthSamplerDesc);
772 }
773
774 if (m_normalTexture) {
775 static const QSSGRhiSamplerDescription normalSamplerDesc {
776 QRhiSampler::Nearest, QRhiSampler::Nearest,
777 QRhiSampler::None,
778 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat
779 };
780 addTextureToShaderPipeline("qt_normalTexture", m_normalTexture, normalSamplerDesc);
781 }
782 if (m_motionVectorTexture) {
783 static const QSSGRhiSamplerDescription motionVectorSamplerDesc {
784 QRhiSampler::Linear, QRhiSampler::Linear,
785 QRhiSampler::None,
786 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat
787 };
788 addTextureToShaderPipeline("qt_motionVectorTexture", m_motionVectorTexture, motionVectorSamplerDesc);
789 }
790}
791
792void QSSGRhiEffectSystem::addTextureToShaderPipeline(const QByteArray &name,
793 QRhiTexture *texture,
794 const QSSGRhiSamplerDescription &samplerDescription)
795{
796 if (!m_currentShaderPipeline)
797 return;
798
799 static const QSSGRhiSamplerDescription defaultDescription { QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
800 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat };
801 bool validDescription = samplerDescription.magFilter != QRhiSampler::None;
802
803 // This is a map for a reason: there can be multiple calls to this function
804 // for the same 'name', with a different 'texture', take the last value
805 // into account only.
806 m_currentTextures.insert(name, { name, texture, validDescription ? samplerDescription : defaultDescription});
807}
808
809QT_END_NAMESPACE
Combined button and popup list for selecting options.
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
static const char * effect_builtin_textureMapUVFlipped
static const char * effect_builtin_textureMapUV
QSSGRhiSamplerDescription desc
QSSGAllocateBufferFlags flags
QRhiTextureRenderTarget * renderTarget
QRhiRenderPassDescriptor * renderPassDescriptor
QSSGRhiEffectTexture & operator=(const QSSGRhiEffectTexture &)=delete