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
qssgcomputemanager.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
7#include "extensionapi/qssgrenderextensions.h"
9#include "private/qssgrendercomputepass_p.h"
12#include "private/qssgrenderbuffer_p.h"
13#include "private/qssgrenderer_p.h"
14#include "private/qssglayerrenderdata_p.h"
15
17
18static constexpr int s_maxDirectionalLights = 16384u / sizeof(QSSGShaderDirectionalLightData);
19static constexpr int s_maxPositionalLights = 16384u / sizeof(QSSGShaderLightData);
20
22{
23 QByteArrayLiteral("PROJECTION_MATRIX"), QByteArrayLiteral("qt_projectionMatrix"),
24 QByteArrayLiteral("INVERSE_PROJECTION_MATRIX"), QByteArrayLiteral("qt_inverseProjectionMatrix"),
25 QByteArrayLiteral("CAMERA_DIRECTION"), QByteArrayLiteral("qt_cameraDirection"),
26 QByteArrayLiteral("CAMERA_PROPERTIES"), QByteArrayLiteral("qt_cameraProperties"),
27 QByteArrayLiteral("CAMERA_POSITION"), QByteArrayLiteral("qt_cameraPosition"),
28 QByteArrayLiteral("VIEW_MATRIX"), QByteArrayLiteral("qt_viewMatrix"),
29 QByteArrayLiteral("INVERSE_VIEW_MATRIX"), QByteArrayLiteral("qt_inverseViewMatrix"),
30 QByteArrayLiteral("VIEWPROJECTION_MATRIX"), QByteArrayLiteral("qt_viewProjectionMatrix"),
31 QByteArrayLiteral("INVERSE_VIEWPROJECTION_MATRIX"), QByteArrayLiteral("qt_inverseViewProjectionMatrix")
32};
34{
35 QByteArrayLiteral("SCREEN_TEXTURE"),
36 QByteArrayLiteral("SCREEN_MIP_TEXTURE"),
37 QByteArrayLiteral("DEPTH_TEXTURE"),
38 QByteArrayLiteral("NORMAL_ROUGHNESS_TEXTURE"),
39 QByteArrayLiteral("AO_TEXTURE")
40};
41
43{
44 QByteArrayLiteral("FRAMEBUFFER_Y_UP"),
45 QByteArrayLiteral("NDC_Y_UP"),
46 QByteArrayLiteral("NEAR_CLIP_VALUE")
47};
48
50{
51 QByteArrayLiteral("DIRECTIONAL_LIGHT_COUNT"),
52 QByteArrayLiteral("DIRECTIONAL_LIGHT_DIFFUSE"),
53 QByteArrayLiteral("DIRECTIONAL_LIGHT_DIRECTION"),
54 QByteArrayLiteral("POINT_LIGHT_COUNT"),
55 QByteArrayLiteral("POINT_LIGHT_DIFFUSE"),
56 QByteArrayLiteral("POINT_LIGHT_POSITION"),
57 QByteArrayLiteral("POINT_LIGHT_ATTENUATION"),
58 QByteArrayLiteral("SPOT_LIGHT_COUNT"),
59 QByteArrayLiteral("SPOT_LIGHT_DIFFUSE"),
60 QByteArrayLiteral("SPOT_LIGHT_POSITION"),
61 QByteArrayLiteral("SPOT_LIGHT_ATTENUATION"),
62 QByteArrayLiteral("SPOT_LIGHT_DIRECTION"),
63 QByteArrayLiteral("SPOT_LIGHT_CONES")
64};
65
67{
68 QByteArrayLiteral("SPOT_LIGHT_SHADOW"),
69 QByteArrayLiteral("POINT_LIGHT_SHADOW"),
70};
71
72// The identifiers the shader code uses, outside comments.
73static QSet<QByteArray> shaderIdentifiers(const QByteArray &shaderCode)
74{
75 QSet<QByteArray> identifiers;
77 tok.initialize(shaderCode.constData());
78 for (auto t = tok.next(); t != QSSGShaderTokenizer::Token_EOF; t = tok.next()) {
79 if (t == QSSGShaderTokenizer::Token_Identifier)
80 identifiers.insert(QByteArray(tok.identifier, tok.pos - tok.identifier));
81 }
82 return identifiers;
83}
84
85static bool containsAny(const QSet<QByteArray> &identifiers, const QByteArrayList &list)
86{
87 for (const auto &a : list) {
88 if (identifiers.contains(a))
89 return true;
90 }
91 return false;
92}
93
94static quint32 softShadowQualityToInt(QSSGRenderLight::SoftShadowQuality quality)
95{
96 quint32 samplesCount = 0;
97 switch (quality) {
98 case QSSGRenderLight::SoftShadowQuality::Hard:
99 samplesCount = 0;
100 break;
101 case QSSGRenderLight::SoftShadowQuality::PCF4:
102 samplesCount = 4;
103 break;
104 case QSSGRenderLight::SoftShadowQuality::PCF8:
105 samplesCount = 8;
106 break;
107 case QSSGRenderLight::SoftShadowQuality::PCF16:
108 case QSSGRenderLight::SoftShadowQuality::PCF32:
109 case QSSGRenderLight::SoftShadowQuality::PCF64:
110 samplesCount = 16;
111 break;
112 }
113
114 return samplesCount;
115}
116
119 const QSSGRenderComputePass *pass,
120 const QSSGComputeLightContext &lightContext,
121 const bool multiview,
122 int viewCount)
123{
124 const auto &shaderCache = cif->shaderCache();
125 const auto &shaderLibraryManager = cif->shaderLibraryManager();
126 const auto &shaderProgramGenerator = cif->shaderProgramGenerator();
127 QByteArray finalKey = inKey;
128 finalKey += QByteArrayLiteral(";lights:");
129 if (pass->computeShader.needsLights)
130 finalKey += QByteArrayLiteral("true");
131 else
132 finalKey += QByteArrayLiteral("false");
133 finalKey += QByteArrayLiteral(";shadows:");
134 if (pass->computeShader.needsLights && (pass->computeShader.needsShadowsDirectional || pass->computeShader.needsShadowsPositional)) {
135 finalKey += QByteArrayLiteral("true");
136 finalKey += ";QSSG_SHADOW_SOFTNESS:"+QByteArray::number(softShadowQualityToInt(lightContext.maxSoftShadowQuality));
137 } else {
138 finalKey += QByteArrayLiteral("false");
139 }
140
141 // A shader that failed to compile is cached as null; return that instead of
142 // compiling it again on every frame.
143 if (shaderCache->hasRhiShaderPipeline(finalKey, {})) {
144 auto pipeline = shaderCache->tryGetRhiShaderPipeline(finalKey, {});
145 return (pipeline && !pipeline->isNull()) ? pipeline : nullptr;
146 }
147
148 // try persistent(disk based) cache
149 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(finalKey, {});
150 auto pipeline = shaderCache->tryNewPipelineFromPersistentCache(qsbcKey, finalKey, {});
151 if (pipeline && !pipeline->isNull())
152 return pipeline;
153
154 shaderProgramGenerator->beginProgram(QSSGShaderGeneratorStage::Compute);
155
156 auto *cs = shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Compute);
157 cs->addDefinition("QSSG_COMPUTE", "1");
158
159 for (const auto &uniform : std::as_const(pass->computeShader.propertyUniforms)) {
160 if (uniform.shaderDataType == QSSGRenderShaderValue::StorageBuffer) {
161 const QSSGShaderBuffer buffer(uniform.value.value<QSSGShaderBuffer>());
162 cs->addBuffer(uniform.name, buffer.dataType, buffer.qualifiers);
163 } else if (uniform.shaderDataType == QSSGRenderShaderValue::Image) {
164 const QSSGShaderImage image(uniform.value.value<QSSGShaderImage>());
165 cs->addImage(uniform.name, image.imageType, image.format, image.qualifiers);
166 } else {
167 cs->addUniform(uniform.name, uniform.typeName);
168 }
169 }
170 for (const auto &def : std::as_const(pass->computeShader.defines))
171 cs->addDefinition(def.name, def.value);
172
173 if (pass->computeShader.needsFrameIndex) {
174 cs->addUniform("qt_frame_num", "float");
175 cs->addDefinition("FRAME", "qt_frame_num");
176 }
177 if (pass->computeShader.needsCamera) {
178 for (int i = 0; i < cameraUniforms.size() / 2; i++) {
179 if (pass->computeShader.identifiers.contains(cameraUniforms[2 * i])) {
180 if (multiview && cameraUniforms[2 * i] != "CAMERA_PROPERTIES") {
181 cs->addUniformArray(cameraUniforms[2 * i + 1], cameraUniforms[2 * i].contains("MATRIX") ? "mat4" : "vec3", viewCount);
182 cs->addDefinition(cameraUniforms[2 * i], cameraUniforms[2 * i + 1]);
183 } else {
184 cs->addUniform(cameraUniforms[2 * i + 1], cameraUniforms[2 * i].contains("MATRIX") ? "mat4" : "vec3");
185 cs->addDefinition(cameraUniforms[2 * i], cameraUniforms[2 * i + 1]);
186 }
187 }
188 }
189 }
190 if (pass->computeShader.needsRhiProperties || pass->computeShader.needsLights) {
191 cs->addUniform("qt_rhi_properties", "vec3");
192 cs->addDefinition("FRAMEBUFFER_Y_UP", "qt_rhi_properties.x");
193 cs->addDefinition("NDC_Y_UP", "qt_rhi_properties.y");
194 cs->addDefinition("NEAR_CLIP_VALUE", "qt_rhi_properties.z");
195 }
196 if (pass->computeShader.needsScreenTextures) {
197 if (pass->computeShader.identifiers.contains(QByteArrayLiteral("SCREEN_TEXTURE"))
198 || pass->computeShader.identifiers.contains(QByteArrayLiteral("SCREEN_MIP_TEXTURE"))) {
199 cs->addUniform(multiview ? "qt_screenTextureArray" : "qt_screenTexture", multiview ? "sampler2DArray" : "sampler2D");
200 cs->addDefinition("SCREEN_TEXTURE", multiview ? "qt_screenTextureArray" : "qt_screenTexture");
201 cs->addDefinition("SCREEN_MIP_TEXTURE", multiview ? "qt_screenTextureArray" : "qt_screenTexture");
202 }
203 if (pass->computeShader.identifiers.contains(QByteArrayLiteral("DEPTH_TEXTURE"))) {
204 cs->addUniform(multiview ? "qt_depthTextureArray" : "qt_depthTexture", multiview ? "sampler2DArray" : "sampler2D");
205 cs->addDefinition("DEPTH_TEXTURE", multiview ? "qt_depthTextureArray" : "qt_depthTexture");
206 }
207 if (pass->computeShader.identifiers.contains(QByteArrayLiteral("AO_TEXTURE"))) {
208 cs->addUniform(multiview ? "qt_aoTextureArray" : "qt_aoTexture", multiview ? "sampler2DArray" : "sampler2D");
209 cs->addDefinition("AO_TEXTURE", multiview ? "qt_aoTextureArray" : "qt_aoTexture");
210 }
211 }
212 if (pass->computeShader.needsNormalTexture) {
213 cs->addUniform("qt_normalTexture", "sampler2D");
214 cs->addDefinition("NORMAL_ROUGHNESS_TEXTURE", "qt_normalTexture");
215 }
216 if (pass->computeShader.needsLights) {
217 cs->addUniform("qt_directionalLightCount", "uint");
218 cs->addDefinition("DIRECTIONAL_LIGHT_COUNT", "qt_directionalLightCount");
219 cs->addDefinition("DIRECTIONAL_LIGHT_DIFFUSE", "qt_directionalLightDiffuse");
220 cs->addDefinition("DIRECTIONAL_LIGHT_DIRECTION", "qt_directionalLightDirection");
221
222 cs->addUniform("qt_pointLightCount", "uint");
223 cs->addDefinition("POINT_LIGHT_COUNT", "qt_pointLightCount");
224 cs->addDefinition("POINT_LIGHT_DIFFUSE", "qt_pointLightDiffuse");
225 cs->addDefinition("POINT_LIGHT_POSITION", "qt_pointLightPosition");
226 cs->addDefinition("POINT_LIGHT_ATTENUATION", "qt_pointLightAttenuation");
227
228 cs->addUniform("qt_spotLightCount", "uint");
229 cs->addDefinition("SPOT_LIGHT_COUNT", "qt_spotLightCount");
230 cs->addDefinition("SPOT_LIGHT_DIFFUSE", "qt_spotLightDiffuse");
231 cs->addDefinition("SPOT_LIGHT_POSITION", "qt_spotLightPosition");
232 cs->addDefinition("SPOT_LIGHT_ATTENUATION", "qt_spotLightAttenuation");
233 cs->addDefinition("SPOT_LIGHT_DIRECTION", "qt_spotLightDirection");
234 cs->addDefinition("SPOT_LIGHT_CONES", "qt_spotLightCones");
235
236 cs->addDefinition("QSSG_MAX_POSITIONAL_LIGHTS", QByteArray::number(s_maxPositionalLights));
237 cs->addDefinition("QSSG_MAX_DIRECTIONAL_LIGHTS", QByteArray::number(s_maxDirectionalLights));
238
239 cs->addInclude("computeLights.glsllib");
240 if (pass->computeShader.needsShadowsDirectional || pass->computeShader.needsShadowsPositional) {
241 cs->addInclude("computeShadows.glsllib");
242 cs->addDefinition("QSSG_SHADOW_SOFTNESS", QByteArray::number(softShadowQualityToInt(lightContext.maxSoftShadowQuality)));
243 cs->addDefinition(QByteArrayLiteral("DIRECTIONAL_LIGHT_SHADOW"), QByteArrayLiteral("qt_dirLightShadowCompute"));
244 cs->addDefinition(QByteArrayLiteral("POINT_LIGHT_SHADOW"), QByteArrayLiteral("qt_pointLightShadowCompute"));
245 cs->addDefinition(QByteArrayLiteral("SPOT_LIGHT_SHADOW"), QByteArrayLiteral("qt_spotLightShadowCompute"));
246 }
247 }
248 cs->append("#line 1\n");
249 cs->append(pass->computeShader.body);
250 return shaderProgramGenerator->compileGeneratedRhiShader(finalKey, {}, *shaderLibraryManager,
251 *shaderCache, {}, {}, multiview ? viewCount : 0, false);
252}
253
254bool finalizeComputeShader(QSSGUserComputeShader &computeShader)
255{
256 if (computeShader.body.isEmpty())
257 return false;
258 const auto shaderData = computeShader.body;
259 QCryptographicHash hashData(QCryptographicHash::Algorithm::Sha1);
260 hashData.addData(shaderData);
261 // The declarations of images, buffers and plain uniforms are generated
262 // from the metadata and the QML property types, not from the body, so
263 // they all have to be part of the key.
264 for (const auto &prop : std::as_const(computeShader.propertyUniforms)) {
265 QByteArray u(prop.name + ":" + prop.typeName);
266 if (prop.shaderDataType == QSSGRenderShaderValue::StorageBuffer) {
267 const QSSGShaderBuffer buffer(prop.value.value<QSSGShaderBuffer>());
268 u += ":" + buffer.dataType + ":" + QSSGBaseTypeHelpers::toString(buffer.qualifiers);
269 } else if (prop.shaderDataType == QSSGRenderShaderValue::Image) {
270 const QSSGShaderImage image(prop.value.value<QSSGShaderImage>());
271 u += ":" + image.imageType + ":" + image.format + ":" + QSSGBaseTypeHelpers::toString(image.qualifiers);
272 }
273 u += ";";
274 hashData.addData(u);
275 }
276 computeShader.hash = hashData.result().toHex();
277 computeShader.identifiers = shaderIdentifiers(shaderData);
278 const auto &ids = computeShader.identifiers;
279 computeShader.needsCamera = containsAny(ids, cameraUniforms);
280 computeShader.needsRhiProperties = containsAny(ids, rhiProperties);
281 computeShader.needsScreenTextures = containsAny(ids, screenTextures);
282 computeShader.needsNormalTexture = ids.contains(QByteArrayLiteral("NORMAL_ROUGHNESS_TEXTURE"));
283 computeShader.needsFrameIndex = ids.contains(QByteArrayLiteral("FRAME"));
284 computeShader.needsShadowsPositional = containsAny(ids, positionalShadows);
285 computeShader.needsShadowsDirectional = ids.contains(QByteArrayLiteral("DIRECTIONAL_LIGHT_SHADOW"));
286 computeShader.needsLights = containsAny(ids, lightUniforms) || computeShader.needsShadowsPositional || computeShader.needsShadowsDirectional;
287 computeShader.supportsMultiview = ids.contains(QByteArrayLiteral("QSHADER_VIEW_COUNT"));
288 return true;
289}
290
291void prepareComputePass(QSSGRenderer &renderer, QSSGLayerRenderData &data, QSSGRenderComputePass *passNode, ComputeUserPassData &userData, QSSGPassKey key)
292{
293 const auto &rhiCtx = renderer.contextInterface()->rhiContext();
294 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx.get());
295 auto &bufferManager(renderer.contextInterface()->bufferManager());
296 if (!rhiCtx->rhi()->isFeatureSupported(QRhi::Compute)) {
297 if (data.warnOnce(QSSGLayerRenderData::OneShotWarning::ComputeUnsupported))
298 qWarning() << "Compute is not supported by the current RHI backend, ComputePass will be skipped.";
299 return;
300 }
301 if (!passNode->isReady())
302 return;
303 const bool multiview = data.layer.viewCount > 1;
304 const bool needsMultiview = passNode->computeShader.needsScreenTextures || passNode->computeShader.needsCamera;
305
306 if (!passNode->multiviewWarningShown && multiview && needsMultiview && !passNode->computeShader.supportsMultiview) {
307 qWarning() << "Multiview enabled, but compute shader doesn't use QSHADER_VIEW_COUNT";
308 passNode->multiviewWarningShown = true;
309 }
310
311 const int maxGroups = rhiCtx->rhi()->resourceLimit(QRhi::MaxThreadGroupsPerDimension);
312 bool dispatchSet = false;
313 bool noGroups = false;
314 for (const auto &command : std::as_const(passNode->commands)) {
315 switch (command->m_type) {
316 case CommandType::Dispatch: {
317 QSSGDispatch *disp = static_cast<QSSGDispatch*>(command);
318 if (dispatchSet) {
319 if (!passNode->dispatchMultiWarningShown) {
320 qWarning() << "Multiple dispatches in ComputePass. Using the first.";
321 passNode->dispatchMultiWarningShown = true;
322 }
323 continue;
324 }
325 if (!passNode->dispatchGroupsWarningShown
326 && (disp->m_groupCount.x > maxGroups || disp->m_groupCount.y > maxGroups || disp->m_groupCount.z > maxGroups)) {
327 qWarning() << "Dispatch exceeds maximum thread groups limit. " << maxGroups;
328 passNode->dispatchGroupsWarningShown = true;
329 }
330 userData.m_groupCount = {qMin(maxGroups, disp->m_groupCount.x),
331 qMin(maxGroups, disp->m_groupCount.y),
332 qMin(maxGroups, disp->m_groupCount.z)};
333 noGroups = userData.m_groupCount.x == 0 || userData.m_groupCount.y == 0 || userData.m_groupCount.z == 0;
334 dispatchSet = true;
335 } break;
336 case CommandType::AddShaderDefine:
337 {
338 const auto *define = static_cast<const QSSGAddShaderDefine *>(command);
339 const auto &defineName = define->m_name;
340 if (defineName.size() > 0) {
341 QByteArray value = QByteArray::number(define->m_value);
342 userData.m_shaderDefines.push_back({ defineName, value });
343 }
344 } break;
345 default:
346 break;
347 }
348 }
349
350 if (!dispatchSet || noGroups) {
351 if (!passNode->dispatchMissingWarningShown && !dispatchSet) {
352 qWarning() << "ComputePass has no Dispatch. ComputePass will be skipped";
353 passNode->dispatchMissingWarningShown = true;
354 }
355 return;
356 }
357
358 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
359 /* Lights are the same for all compute passes so we need do this only once per frame. */
360 if (passNode->computeShader.needsLights && !data.computeLightsUpdated) {
361 QList<QSSGShaderLight> dirs, spots, points;
362 const auto &globalLights = data.globalLights;
363 auto &lightContext = data.getComputeLightContext();
364 lightContext.maxSoftShadowQuality = QSSGRenderLight::SoftShadowQuality::Hard;
365
366 const auto lightIndex = [](const QSSGShaderLightList &lights, const QSSGShaderLight &light) -> int {
367 for (int i = 0; i < lights.size(); i++)
368 if (lights[i].light == light.light)
369 return i;
370 return -1;
371 };
372
373 bool dirWarn = false;
374 bool posWarn = false;
375
376 for (const auto &l : globalLights) {
377 if (l.shadows && l.light->m_softShadowQuality > lightContext.maxSoftShadowQuality)
378 lightContext.maxSoftShadowQuality = l.light->m_softShadowQuality;
379 if (l.light->type == QSSGRenderGraphObject::Type::DirectionalLight) {
380 if (dirs.size() < s_maxDirectionalLights) {
381 dirs.append(l);
382 } else if (!dirWarn) {
383 qWarning() << "ComputePass: Max directional lights reached.";
384 dirWarn = true;
385 }
386 } else if (l.light->type == QSSGRenderGraphObject::Type::SpotLight) {
387 if ((spots.size() + points.size()) < s_maxPositionalLights) {
388 spots.append(l);
389 } else if (!posWarn) {
390 qWarning() << "ComputePass: Max positional lights reached.";
391 posWarn = true;
392 }
393 } else if (l.light->type == QSSGRenderGraphObject::Type::PointLight) {
394 if ((spots.size() + points.size()) < s_maxPositionalLights) {
395 points.append(l);
396 } else if (!posWarn) {
397 qWarning() << "ComputePass: Max positional lights reached.";
398 posWarn = true;
399 }
400 }
401 }
402
403 if (!lightContext.dirLightBuffer) {
404 lightContext.dirLightBuffer = rhiCtx->rhi()->newBuffer(QRhiBuffer::Static,
405 QRhiBuffer::StorageBuffer,
406 quint32(sizeof(QSSGShaderDirectionalLightData) * s_maxDirectionalLights));
407 lightContext.dirLightBuffer->create();
408 lightContext.dirLightData.resize(sizeof(QSSGShaderDirectionalLightData) * s_maxDirectionalLights);
409 lightContext.dirLightData.fill(0);
410 }
411 if (!lightContext.lightBuffer) {
412 lightContext.lightBuffer = rhiCtx->rhi()->newBuffer(QRhiBuffer::Static,
413 QRhiBuffer::StorageBuffer,
414 quint32(sizeof(QSSGShaderLightData) * s_maxPositionalLights));
415 lightContext.lightBuffer->create();
416 lightContext.lightData.resize(sizeof(QSSGShaderLightData) * s_maxPositionalLights);
417 lightContext.lightData.fill(0);
418 }
419 lightContext.spotLights = spots.size();
420 lightContext.pointLights = points.size();
421 lightContext.dirLights = dirs.size();
422
423 QSSGShaderDirectionalLightData *dirLightDataPtr = reinterpret_cast<QSSGShaderDirectionalLightData*>(lightContext.dirLightData.data());
424 for (int idx = 0; idx < dirs.size(); idx++) {
425 auto light = dirs[idx].light;
426 auto &lightData = dirLightDataPtr[idx];
427 const bool lightShadows = dirs[idx].shadows;
428 const float brightness = light->m_brightness;
429 const QVector3D diffuseColor(light->m_diffuseColor.x() * brightness,
430 light->m_diffuseColor.y() * brightness,
431 light->m_diffuseColor.z() * brightness);
432 const QVector3D specularColor(light->m_specularColor.x() * brightness,
433 light->m_specularColor.y() * brightness,
434 light->m_specularColor.z() * brightness);
435 lightData.lightmapState = 0;
436 lightData.direction[0] = dirs[idx].direction.x();
437 lightData.direction[1] = dirs[idx].direction.y();
438 lightData.direction[2] = dirs[idx].direction.z();
439 lightData.shadowBias = 0.0f;
440 lightData.diffuseColor[0] = diffuseColor.x();
441 lightData.diffuseColor[1] = diffuseColor.y();
442 lightData.diffuseColor[2] = diffuseColor.z();
443 lightData.shadowFactor = 0.0f;
444 lightData.specularColor[0] = specularColor.x();
445 lightData.specularColor[1] = specularColor.y();
446 lightData.specularColor[2] = specularColor.z();
447 lightData.enableShadows = 0.0f;
448 if (lightShadows && data.getShadowMapManager()) {
449 QSSGShadowMapEntry *pEntry = data.getShadowMapManager()->shadowMapEntry(lightIndex(data.globalLights, dirs[idx]));
450 if (pEntry) {
451 const quint32 layerCount = pEntry->m_csmNumSplits + 1;
452
453 for (quint32 i = 0; i < layerCount; ++i)
454 memcpy(lightData.matrices[i], pEntry->m_fixedScaleBiasMatrix[i].constData(), 16 * sizeof(float));
455
456 lightData.shadowBias = light->m_shadowBias;
457 lightData.shadowFactor = light->m_shadowFactor;
458 lightData.shadowMapFar = light->m_shadowMapFar;
459 lightData.shadowPcfSamples = softShadowQualityToInt(light->m_softShadowQuality);
460 lightData.shadowPcfFactor = light->m_pcfFactor;
461
462 for (quint32 i = 0; i < layerCount; ++i) {
463 const auto &atlasInfo = pEntry->m_atlasInfo[i];
464 lightData.atlasLocations[i][0] = atlasInfo.uOffset;
465 lightData.atlasLocations[i][1] = atlasInfo.vOffset;
466 lightData.atlasLocations[i][2] = atlasInfo.uvScale;
467 lightData.atlasLocations[i][3] = atlasInfo.layerIndex;
468 }
469
470 lightData.csmNumSplits = pEntry->m_csmNumSplits;
471 memcpy(lightData.csmSplits, pEntry->m_csmSplits, 4 * sizeof(float));
472 memcpy(lightData.csmActive, pEntry->m_csmActive, 4 * sizeof(float));
473 lightData.csmBlendRatio = light->m_csmBlendRatio;
474 for (quint32 i = 0; i < layerCount; ++i)
475 memcpy(lightData.dimensionsInverted[i], &pEntry->m_dimensionsInverted[i], 4 * sizeof(float));
476 if (pEntry->hasActiveCascades())
477 lightData.enableShadows = 1.0f;
478 }
479 }
480 }
481
482 const auto handlePositionalLight = [&data, lightIndex](const QSSGShaderLight &shaderLight, QSSGShaderLightData &lightData) {
483 auto light = shaderLight.light;
484 const bool lightShadows = shaderLight.shadows;
485 const float brightness = light->m_brightness;
486 const QVector3D diffuseColor(light->m_diffuseColor.x() * brightness,
487 light->m_diffuseColor.y() * brightness,
488 light->m_diffuseColor.z() * brightness);
489 const QVector3D specularColor(light->m_specularColor.x() * brightness,
490 light->m_specularColor.y() * brightness,
491 light->m_specularColor.z() * brightness);
492 lightData.lightmapState = 0;
493 lightData.direction[0] = shaderLight.direction.x();
494 lightData.direction[1] = shaderLight.direction.y();
495 lightData.direction[2] = shaderLight.direction.z();
496 lightData.shadowBias = 0.0f;
497 lightData.diffuseColor[0] = diffuseColor.x();
498 lightData.diffuseColor[1] = diffuseColor.y();
499 lightData.diffuseColor[2] = diffuseColor.z();
500 lightData.shadowFactor = 0.0f;
501 lightData.specularColor[0] = specularColor.x();
502 lightData.specularColor[1] = specularColor.y();
503 lightData.specularColor[2] = specularColor.z();
504 const auto gt = data.getGlobalTransform(*light);
505 const QVector3D globalPos = QSSGRenderNode::getGlobalPos(gt);
506 lightData.position[0] = globalPos.x();
507 lightData.position[1] = globalPos.y();
508 lightData.position[2] = globalPos.z();
509 lightData.constantAttenuation = QSSGUtils::aux::translateConstantAttenuation(light->m_constantFade);
510 lightData.linearAttenuation = QSSGUtils::aux::translateLinearAttenuation(light->m_linearFade);
511 lightData.quadraticAttenuation = QSSGUtils::aux::translateQuadraticAttenuation(light->m_quadraticFade);
512 lightData.coneAngle = 360.0f;
513 if (light->type == QSSGRenderLight::Type::SpotLight) {
514 // NB: This is how we tell in the shader that this is a spot light
515 // PointLights have a coneAngle of 360.0f which is greater than 1.0
516 // Since cos(any value) will be between -1 and 1, we can use this.
517 const float coneAngle = light->m_coneAngle;
518 const float innerConeAngle = (light->m_innerConeAngle > coneAngle) ? coneAngle : light->m_innerConeAngle;
519 lightData.coneAngle = qCos(qDegreesToRadians(coneAngle));
520 lightData.innerConeAngle = qCos(qDegreesToRadians(innerConeAngle));
521 }
522 lightData.enableShadows = 0.0f;
523 if (lightShadows && data.getShadowMapManager()) {
524 QSSGShadowMapEntry *pEntry = data.getShadowMapManager()->shadowMapEntry(lightIndex(data.globalLights, shaderLight));
525 if (pEntry) {
526 lightData.enableShadows = 1.0f;
527 lightData.shadowPcfFactor = light->m_pcfFactor;
528 lightData.shadowPcfSamples = softShadowQualityToInt(light->m_softShadowQuality);
529 lightData.shadowFactor = light->m_shadowFactor;
530 lightData.shadowBias = light->m_shadowBias;
531 lightData.shadowClipNear = 1.0f;
532 lightData.shadowMapFar = pEntry->m_shadowMapFar;
533 lightData.shadowTextureSize = pEntry->m_atlasInfo[0].uvScale;
534
535 if (light->type == QSSGRenderLight::Type::SpotLight) {
536 // add fixed scale bias matrix
537 static const QMatrix4x4 bias = {
538 0.5, 0.0, 0.0, 0.5,
539 0.0, 0.5, 0.0, 0.5,
540 0.0, 0.0, 0.5, 0.5,
541 0.0, 0.0, 0.0, 1.0 };
542 const QMatrix4x4 m = bias * pEntry->m_lightViewProjection[0];
543 memcpy(lightData.shadowMatrix, m.constData(), 16 * sizeof(float));
544 lightData.shadowAtlasUV0[0] = pEntry->m_atlasInfo[0].uOffset;
545 lightData.shadowAtlasUV0[1] = pEntry->m_atlasInfo[0].vOffset;
546 lightData.shadowAtlasLayer0 = pEntry->m_atlasInfo[0].layerIndex;
547
548 } else {
549 Q_ASSERT(light->type == QSSGRenderLight::Type::PointLight);
550 memcpy(lightData.shadowMatrix, pEntry->m_lightView.constData(), 16 * sizeof(float));
551 lightData.shadowAtlasUV0[0] = pEntry->m_atlasInfo[0].uOffset;
552 lightData.shadowAtlasUV0[1] = pEntry->m_atlasInfo[0].vOffset;
553 lightData.shadowAtlasLayer0 = pEntry->m_atlasInfo[0].layerIndex;
554 lightData.shadowAtlasUV1[0] = pEntry->m_atlasInfo[1].uOffset;
555 lightData.shadowAtlasUV1[1] = pEntry->m_atlasInfo[1].vOffset;
556 lightData.shadowAtlasLayer1 = pEntry->m_atlasInfo[1].layerIndex;
557 }
558 }
559 }
560 };
561 QSSGShaderLightData *lightDataPtr = reinterpret_cast<QSSGShaderLightData*>(lightContext.lightData.data());
562 for (int i = 0; i < points.size(); i++)
563 handlePositionalLight(points[i], lightDataPtr[i]);
564 for (int i = 0; i < spots.size(); i++)
565 handlePositionalLight(spots[i], lightDataPtr[i + points.size()]);
566
567 if (lightContext.dirLightBuffer)
568 rub->uploadStaticBuffer(lightContext.dirLightBuffer, 0, lightContext.dirLightData);
569 if (lightContext.lightBuffer)
570 rub->uploadStaticBuffer(lightContext.lightBuffer, 0, lightContext.lightData);
571 data.computeLightsUpdated = true;
572 }
573
574 passNode->computeShader.defines = userData.m_shaderDefines;
575 QByteArray defineKey;
576 for (const auto &def : std::as_const(userData.m_shaderDefines))
577 defineKey.append(def.name + "=" + def.value + ";");
578
579 // Add viewCount
580 if (multiview)
581 defineKey.append("viewCount=" + QByteArray::number(data.layer.viewCount) + ";");
582
583 userData.m_computePipeline = generateRhiShaderPipeline("compute - " + passNode->computeShader.hash + " - " + defineKey,
584 renderer.contextInterface(), passNode, data.getComputeLightContextConst(),
585 multiview && needsMultiview,
586 data.layer.viewCount);
587 if (userData.m_computePipeline == nullptr) {
588 if (!std::exchange(passNode->pipelineWarningShown, true))
589 qWarning() << "Unable to initialize compute pass.";
590 rhiCtx->commandBuffer()->resourceUpdate(rub);
591 return;
592 }
593 passNode->pipelineWarningShown = false;
594
595 QSSGRhiDrawCallData &dcd(rhiCtxD->drawCallData({ key, passNode, nullptr, nullptr, 0 }));
596 userData.m_computePipeline->ensureUniformBuffer(&dcd.ubuf);
597 {
598 QSSGRhiShaderResourceBindingList bindings;
599 bindings.addUniformBuffer(0, QRhiShaderResourceBinding::ComputeStage, dcd.ubuf);
600
601 for (const auto &prop : std::as_const(passNode->computeShader.propertyUniforms)) {
602 switch (prop.shaderDataType) {
603 case QSSGRenderShaderValue::Texture: {
604 QSSGRenderImage *image = prop.value.value<QSSGRenderImage*>();
605 int binding = userData.m_computePipeline->bindingForTexture(prop.name);
606 if (binding == -1)
607 continue;
608 bool dummyRequired = true;
609 if (image) {
610 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(image);
611 if (texture.m_texture) {
612 dummyRequired = false;
613 QSSGRhiSamplerDescription desc{
614 QSSGRhiHelpers::toRhi(image->m_minFilterType),
615 QSSGRhiHelpers::toRhi(image->m_magFilterType),
616 image->m_mipFilterType != QSSGRenderTextureFilterOp::None ? QSSGRhiHelpers::toRhi(image->m_mipFilterType) : QRhiSampler::None,
617 QSSGRhiHelpers::toRhi(image->m_horizontalTilingMode),
618 QSSGRhiHelpers::toRhi(image->m_verticalTilingMode),
619 QSSGRhiHelpers::toRhi(image->m_depthTilingMode)};
620 QRhiSampler *sampler = rhiCtx->sampler(desc);
621 bindings.addTexture(binding, QRhiShaderResourceBinding::ComputeStage, texture.m_texture, sampler);
622 }
623 }
624 if (dummyRequired) {
625 // Match the type the sampler is declared with, a null CubeMapTexture
626 // property for example declares a samplerCube.
627 const auto samplerType = QSSGRhiHelpers::samplerType(*userData.m_computePipeline, prop.name);
628 QRhiTexture *texture = QSSGRhiHelpers::dummyTextureForSampler(rhiCtx.get(), samplerType, rub, 2,
629 QSize(4, 4), Qt::white);
630 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
631 QRhiSampler::Nearest,
632 QRhiSampler::None,
633 QRhiSampler::ClampToEdge,
634 QRhiSampler::ClampToEdge,
635 QRhiSampler::Repeat
636 });
637 bindings.addTexture(binding, QRhiShaderResourceBinding::ComputeStage, texture, sampler);
638 }
639 } break;
640 case QSSGRenderShaderValue::Image:
641 {
642 const QSSGShaderImage image(prop.value.value<QSSGShaderImage>());
643 int binding = userData.m_computePipeline->bindingForStorageImage(prop.name);
644 if (binding == -1)
645 continue;
646 QRhiTexture *rhiTex = nullptr;
647 if (image.image)
648 rhiTex = bufferManager->loadRenderImage(image.image).m_texture;
649 if (rhiTex) {
650 if (image.imageType.contains("Cube") && !(rhiTex->flags() & QRhiTexture::CubeMap)) {
651 // We should bail out as running the shader is not safe with incorrect texture type
652 userData.m_computePipeline = nullptr;
653 if (!std::exchange(passNode->bindingWarningShown, true))
654 qWarning() << "Unable to run compute shader: bound image is not CubeMap: " << prop.name;
655 rhiCtx->commandBuffer()->resourceUpdate(rub);
656 return;
657 }
658 if (image.qualifiers.testFlag(QSSGMemoryQualifier::Readonly))
659 bindings.addImageLoad(binding, QRhiShaderResourceBinding::ComputeStage, rhiTex, 0);
660 else if (image.qualifiers.testFlag(QSSGMemoryQualifier::Writeonly))
661 bindings.addImageStore(binding, QRhiShaderResourceBinding::ComputeStage, rhiTex, 0);
662 else
663 bindings.addImageLoadStore(binding, QRhiShaderResourceBinding::ComputeStage, rhiTex, 0);
664 } else {
665 // We should bail out as running the shader is not safe with incorrect sized image
666 userData.m_computePipeline = nullptr;
667 if (!std::exchange(passNode->bindingWarningShown, true))
668 qWarning() << "Unable to run compute shader: image not bound: " << prop.name;
669 rhiCtx->commandBuffer()->resourceUpdate(rub);
670 return;
671 }
672 } break;
673 case QSSGRenderShaderValue::StorageBuffer:
674 {
675 const QSSGShaderBuffer buffer(prop.value.value<QSSGShaderBuffer>());
676 int binding = userData.m_computePipeline->bindingForStorageBuffer(prop.name);
677 if (binding == -1)
678 continue;
679 QRhiBuffer *rhiBuf = nullptr;
680 if (buffer.buffer)
681 rhiBuf = bufferManager->loadBuffer(*buffer.buffer);
682 if (rhiBuf) {
683 if (buffer.qualifiers.testFlag(QSSGMemoryQualifier::Readonly))
684 bindings.addStorageBufferLoad(binding, QRhiShaderResourceBinding::ComputeStage, rhiBuf);
685 else if (buffer.qualifiers.testFlag(QSSGMemoryQualifier::Writeonly))
686 bindings.addStorageBufferStore(binding, QRhiShaderResourceBinding::ComputeStage, rhiBuf);
687 else
688 bindings.addStorageBufferLoadStore(binding, QRhiShaderResourceBinding::ComputeStage, rhiBuf);
689 } else {
690 // We should bail out as running the shader is not safe with incorrect sized buffer
691 userData.m_computePipeline = nullptr;
692 if (!std::exchange(passNode->bindingWarningShown, true))
693 qWarning() << "Unable to run compute shader: buffer not bound: " << prop.name;
694 rhiCtx->commandBuffer()->resourceUpdate(rub);
695 return;
696 }
697 } break;
698 default:
699 break;
700 }
701 }
702 bufferManager->commitBufferResourceUpdates();
703 // Everything got bound, so warn again if binding fails later on.
704 passNode->bindingWarningShown = false;
705
706 if (passNode->computeShader.needsLights) {
707 bindings.addStorageBufferLoad(1, QRhiShaderResourceBinding::ComputeStage, data.getComputeLightContextConst().lightBuffer);
708 bindings.addStorageBufferLoad(2, QRhiShaderResourceBinding::ComputeStage, data.getComputeLightContextConst().dirLightBuffer);
709 }
710 if (passNode->computeShader.needsShadowsDirectional || passNode->computeShader.needsShadowsPositional) {
711 auto smMgr = data.getShadowMapManager();
712 auto atlasTexture = smMgr ? data.getShadowMapManager()->shadowMapAtlasTexture() : nullptr;
713 auto noiseTexture = smMgr ? data.getShadowMapManager()->shadowMapBlueNoiseTexture() : nullptr;
714 int binding = userData.m_computePipeline->bindingForTexture("qt_shadowmap_texture");
715 if (binding >= 0) {
716 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
717 QRhiSampler::Linear,
718 QRhiSampler::None,
719 QRhiSampler::ClampToEdge,
720 QRhiSampler::ClampToEdge,
721 QRhiSampler::Repeat });
722 if (!atlasTexture)
723 atlasTexture = rhiCtx->dummyTexture({ }, rub, QSize(1, 1), Qt::black, 2);
724 bindings.addTexture(binding, QRhiShaderResourceBinding::ComputeStage, atlasTexture, sampler);
725 }
726 binding = userData.m_computePipeline->bindingForTexture("qt_shadowmap_blue_noise_texture");
727 if (binding >= 0) {
728 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
729 QRhiSampler::Linear,
730 QRhiSampler::None,
731 QRhiSampler::Repeat,
732 QRhiSampler::Repeat,
733 QRhiSampler::Repeat });
734 if (!noiseTexture)
735 noiseTexture = rhiCtx->dummyTexture({}, rub);
736 bindings.addTexture(binding, QRhiShaderResourceBinding::ComputeStage, noiseTexture, sampler);
737 }
738 }
739 if (passNode->computeShader.needsScreenTextures) {
740 const QSSGRhiRenderableTexture *depthTexture = data.getRenderResult(QSSGRenderResult::Key::DepthTexture);
741 const QSSGRhiRenderableTexture *normalTexture = data.getRenderResult(QSSGRenderResult::Key::NormalTexture);
742 const QSSGRhiRenderableTexture *ssaoTexture = data.getRenderResult(QSSGRenderResult::Key::AoTexture);
743 const QSSGRhiRenderableTexture *screenTexture = data.getRenderResult(QSSGRenderResult::Key::ScreenTexture);
744 const int screenTextureBinding = userData.m_computePipeline->bindingForTexture("qt_screenTexture", int(QSSGRhiSamplerBindingHints::ScreenTexture));
745 const int screenTextureArrayBinding = userData.m_computePipeline->bindingForTexture("qt_screenTextureArray", int(QSSGRhiSamplerBindingHints::ScreenTextureArray));
746 if (screenTextureBinding >= 0 || screenTextureArrayBinding >= 0) {
747 QRhiSampler::Filter mipFilter = QRhiSampler::None;
748 if (screenTexture->texture) {
749 mipFilter = screenTexture->texture->flags().testFlag(QRhiTexture::MipMapped)
750 ? QRhiSampler::Linear : QRhiSampler::None;
751 }
752 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, mipFilter,
753 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
754 QRhiTexture *texture = screenTexture->texture;
755 if (!texture)
756 texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
757 if (screenTextureBinding >= 0) {
758 bindings.addTexture(screenTextureBinding, QRhiShaderResourceBinding::ComputeStage, texture, sampler);
759 } else if (screenTextureArrayBinding >= 0) {
760 bindings.addTexture(screenTextureArrayBinding, QRhiShaderResourceBinding::ComputeStage, texture, sampler);
761 }
762 }
763 const int depthTextureBinding = userData.m_computePipeline->bindingForTexture("qt_depthTexture", int(QSSGRhiSamplerBindingHints::DepthTexture));
764 const int depthTextureArrayBinding = userData.m_computePipeline->bindingForTexture("qt_depthTextureArray", int(QSSGRhiSamplerBindingHints::DepthTextureArray));
765 if (depthTextureBinding >= 0 || depthTextureArrayBinding >= 0) {
766 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
767 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
768 QRhiTexture *texture = depthTexture->texture;
769 if (!texture)
770 texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
771 if (depthTextureBinding >= 0) {
772 bindings.addTexture(depthTextureBinding, QRhiShaderResourceBinding::ComputeStage, texture, sampler);
773 } else if (depthTextureArrayBinding >= 0) {
774 bindings.addTexture(depthTextureArrayBinding, QRhiShaderResourceBinding::ComputeStage, texture, sampler);
775 }
776 }
777 const int aoTextureBinding = userData.m_computePipeline->bindingForTexture("qt_aoTexture", int(QSSGRhiSamplerBindingHints::AoTexture));
778 const int aoTextureArrayBinding = userData.m_computePipeline->bindingForTexture("qt_aoTextureArray", int(QSSGRhiSamplerBindingHints::AoTextureArray));
779 if (aoTextureBinding >= 0 || aoTextureArrayBinding >= 0) {
780 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
781 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
782 QRhiTexture *texture = ssaoTexture->texture;
783 if (!texture)
784 texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
785 if (aoTextureBinding >= 0) {
786 bindings.addTexture(aoTextureBinding, QRhiShaderResourceBinding::ComputeStage, texture, sampler);
787 } else if (aoTextureArrayBinding >= 0) {
788 bindings.addTexture(aoTextureArrayBinding, QRhiShaderResourceBinding::ComputeStage, texture, sampler);
789 }
790 }
791 const int normalTextureBinding = userData.m_computePipeline->bindingForTexture("qt_normalTexture", int(QSSGRhiSamplerBindingHints::NormalTexture));
792 if (normalTextureBinding >= 0) {
793 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
794 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
795 QRhiTexture *texture = normalTexture->texture;
796 if (!texture)
797 texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
798 bindings.addTexture(normalTextureBinding, QRhiShaderResourceBinding::ComputeStage, texture, sampler);
799 }
800 }
801 if (!dcd.srb || bindings != dcd.bindings) {
802 dcd.srb = rhiCtxD->srb(bindings);
803 rhiCtxD->releaseCachedSrb(dcd.bindings);
804 dcd.bindings = bindings;
805 }
806 }
807
808 userData.m_computeBindings = dcd.srb;
809
810 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
811
812 auto *p = userData.m_computePipeline.get();
813 for (const auto &prop : std::as_const(passNode->computeShader.propertyUniforms)) {
814 switch (prop.shaderDataType) {
815 case QSSGRenderShaderValue::Texture:
816 case QSSGRenderShaderValue::StorageBuffer:
817 case QSSGRenderShaderValue::Unknown:
818 case QSSGRenderShaderValue::Image:
819 break;
820 default:
821 userData.m_computePipeline->setUniformValue(ubufData, prop.name, prop.value, prop.shaderDataType);
822 break;
823 }
824 }
825
826 if (passNode->computeShader.needsFrameIndex) {
827 float fc = float(renderer.frameCount());
828 userData.m_computePipeline->setUniformValue(ubufData, "qt_frame_num", fc, QSSGRenderShaderValue::Float);
829 }
830
831 if (passNode->computeShader.needsRhiProperties || passNode->computeShader.needsLights) {
832 QVector3D qt_rhi_properties;
833 const auto globalRenderData = QSSGLayerRenderData::globalRenderProperties(*renderer.contextInterface());
834 qt_rhi_properties.setX(globalRenderData.isYUpInFramebuffer ? 1.0f : -1.0f);
835 qt_rhi_properties.setY(globalRenderData.isYUpInNDC ? 1.0f : -1.0f);
836 qt_rhi_properties.setZ(globalRenderData.isClipDepthZeroToOne ? 0.0f : -1.0f);
837 userData.m_computePipeline->setUniformValue(ubufData, "qt_rhi_properties", qt_rhi_properties, QSSGRenderShaderValue::Vec3);
838 }
839 if (passNode->computeShader.needsCamera) {
840 QSSG_ASSERT(!data.renderedCameras.isEmpty(),
841 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
842 rhiCtx->commandBuffer()->resourceUpdate(rub);
843 return);
844 const QVector3D camProperties(data.renderedCameras[0]->clipPlanes[0], data.renderedCameras[0]->clipPlanes[1], 0.0f);
845 p->setUniformValue(ubufData, "qt_cameraProperties", camProperties, QSSGRenderShaderValue::Vec3);
846 const auto clipCorrMatrix = rhiCtx->rhi()->clipSpaceCorrMatrix();
847
848 if (multiview) {
849 int viewCount = data.layer.viewCount;
850 QVarLengthArray<QMatrix4x4> cameraGlobalMatrix(viewCount);
851 QVarLengthArray<QMatrix4x4> projection(viewCount);
852 QVarLengthArray<QMatrix4x4> invProjection(viewCount);
853 QVarLengthArray<QVector3D> dir(viewCount);
854 QVarLengthArray<QMatrix4x4> viewMatrix(viewCount);
855 QVarLengthArray<QMatrix4x4> viewProjection(viewCount);
856 QVarLengthArray<QMatrix4x4> invViewMatrix(viewCount);
857 QVarLengthArray<QMatrix4x4> invViewProjection(viewCount);
858 QVarLengthArray<QVector3D> camGlobalPos(viewCount);
859
860 for (int i = 0; i < viewCount; i++) {
861 QSSGRenderCamera *camera = data.renderedCameras[i];
862 cameraGlobalMatrix[i] = data.getGlobalTransform(*camera);
863 projection[i] = clipCorrMatrix * camera->projection;
864 invProjection[i] = projection[i].inverted();
865 dir[i] = data.renderedCameraData.value()[i].direction;
866 viewMatrix[i] = cameraGlobalMatrix[i].inverted();
867 camera->calculateViewProjectionMatrix(cameraGlobalMatrix[i], viewProjection[i]);
868 viewProjection[i] = clipCorrMatrix * viewProjection[i];
869 invViewMatrix[i] = cameraGlobalMatrix[i];
870 invViewProjection[i] = viewProjection[i].inverted();
871 camGlobalPos[i] = QSSGRenderNode::getGlobalPos(cameraGlobalMatrix[i]);
872 }
873 p->setUniformArray(ubufData, "qt_viewMatrix", viewMatrix.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
874 p->setUniformArray(ubufData, "qt_viewProjectionMatrix", viewProjection.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
875 p->setUniformArray(ubufData, "qt_inverseViewMatrix", invViewMatrix.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
876 p->setUniformArray(ubufData, "qt_inverseViewProjectionMatrix", invViewProjection.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
877 p->setUniformArray(ubufData, "qt_projectionMatrix", projection.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
878 p->setUniformArray(ubufData, "qt_inverseProjectionMatrix", invProjection.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4);
879 p->setUniformArray(ubufData, "qt_cameraPosition", camGlobalPos.constData(), viewCount, QSSGRenderShaderValue::Vec3);
880 p->setUniformArray(ubufData, "qt_cameraDirection", dir.constData(), viewCount, QSSGRenderShaderValue::Vec3);
881 } else {
882 QSSGRenderCamera *camera = data.renderedCameras[0];
883 QMatrix4x4 cameraGlobalMatrix = data.getGlobalTransform(*camera);
884 QMatrix4x4 projection = clipCorrMatrix * camera->projection;
885 QMatrix4x4 invProjection = projection.inverted();
886 auto &dir = data.renderedCameraData.value()[0].direction;
887 QMatrix4x4 viewMatrix = cameraGlobalMatrix.inverted();
888 QMatrix4x4 viewProjection(Qt::Uninitialized);
889 camera->calculateViewProjectionMatrix(cameraGlobalMatrix, viewProjection);
890 viewProjection = clipCorrMatrix * viewProjection;
891 QMatrix4x4 invViewMatrix = cameraGlobalMatrix;
892 QMatrix4x4 invViewProjection = viewProjection.inverted();
893 p->setUniformValue(ubufData, "qt_viewMatrix", viewMatrix, QSSGRenderShaderValue::Matrix4x4);
894 p->setUniformValue(ubufData, "qt_viewProjectionMatrix", viewProjection, QSSGRenderShaderValue::Matrix4x4);
895 p->setUniformValue(ubufData, "qt_inverseViewMatrix", invViewMatrix, QSSGRenderShaderValue::Matrix4x4);
896 p->setUniformValue(ubufData, "qt_inverseViewProjectionMatrix", invViewProjection, QSSGRenderShaderValue::Matrix4x4);
897 p->setUniformValue(ubufData, "qt_projectionMatrix", projection, QSSGRenderShaderValue::Matrix4x4);
898 p->setUniformValue(ubufData, "qt_inverseProjectionMatrix", invProjection, QSSGRenderShaderValue::Matrix4x4);
899 const QVector3D camGlobalPos = QSSGRenderNode::getGlobalPos(cameraGlobalMatrix);
900 p->setUniformValue(ubufData, "qt_cameraPosition", camGlobalPos, QSSGRenderShaderValue::Vec3);
901 p->setUniformValue(ubufData, "qt_cameraDirection", dir, QSSGRenderShaderValue::Vec3);
902 }
903 }
904 if (passNode->computeShader.needsLights) {
905 const auto &lc = data.getComputeLightContextConst();
906 p->setUniformValue(ubufData, "qt_directionalLightCount", lc.dirLights, QSSGRenderShaderValue::UnsignedInteger);
907 p->setUniformValue(ubufData, "qt_spotLightCount", lc.spotLights, QSSGRenderShaderValue::UnsignedInteger);
908 p->setUniformValue(ubufData, "qt_pointLightCount", lc.pointLights, QSSGRenderShaderValue::UnsignedInteger);
909 }
910
911 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
912 rhiCtx->commandBuffer()->resourceUpdate(rub);
913}
914
915QT_END_NAMESPACE
friend class QSSGRenderContextInterface
Combined button and popup list for selecting options.
static QSet< QByteArray > shaderIdentifiers(const QByteArray &shaderCode)
void prepareComputePass(QSSGRenderer &renderer, QSSGLayerRenderData &data, QSSGRenderComputePass *passNode, ComputeUserPassData &userData, QSSGPassKey key)
static const QByteArrayList rhiProperties
static const QByteArrayList cameraUniforms
static const QByteArrayList lightUniforms
static QT_BEGIN_NAMESPACE constexpr int s_maxDirectionalLights
static const QByteArrayList positionalShadows
static constexpr int s_maxPositionalLights
static QSSGRhiShaderPipelinePtr generateRhiShaderPipeline(const QByteArray &inKey, QSSGRenderContextInterface *cif, const QSSGRenderComputePass *pass, const QSSGComputeLightContext &lightContext, const bool multiview, int viewCount)
static const QByteArrayList screenTextures
bool finalizeComputeShader(QSSGUserComputeShader &computeShader)
static bool containsAny(const QSet< QByteArray > &identifiers, const QByteArrayList &list)
static quint32 softShadowQualityToInt(QSSGRenderLight::SoftShadowQuality quality)