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
qssgrhiparticles.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
8
9#include <qfloat16.h>
10
11#include <QtQuick3DUtils/private/qssgutils_p.h>
12
13#include <QtQuick3DRuntimeRender/private/qssgrenderer_p.h>
14#include <QtQuick3DRuntimeRender/private/qssgrendercamera_p.h>
15#include <QtQuick3DRuntimeRender/private/qssglayerrenderdata_p.h>
16#include <QtQuick3DRuntimeRender/private/qssgrenderhelpers_p.h>
17#include <QtQuick3DRuntimeRender/private/qssgshaderresourcemergecontext_p.h>
18
19#include <ssg/qssgrendercontextcore.h>
21
22#include "qtquick3d_tracepoints_p.h"
23
25
27 QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage;
28
30{
32 float pointLightConstantAtt[4] = {1.0f, 1.0f, 1.0f, 1.0f};
33 float pointLightLinearAtt[4] = {0.0f};
34 float pointLightQuadAtt[4] = {0.0f};
37 float spotLightConstantAtt[4] = {1.0f, 1.0f, 1.0f, 1.0f};
38 float spotLightLinearAtt[4] = {0.0f};
39 float spotLightQuadAtt[4] = {0.0f};
42 float spotLightConeAngle[4] = {0.0f};
43 float spotLightInnerConeAngle[4] = {0.0f};
44};
45
46static bool s_shaderCacheEnabled = true;
47void QSSGParticleRenderer::setShaderCacheEnabled(bool enabled)
48{
49 s_shaderCacheEnabled = enabled;
50}
51
52void QSSGParticleRenderer::updateUniformsForParticles(const QSSGLayerRenderData &inData,
53 QSSGRhiShaderPipeline &shaders,
54 QSSGRhiContext *rhiCtx,
55 char *ubufData,
56 QSSGParticlesRenderable &renderable,
57 const QSSGRenderCameraList &cameras)
58{
59 const QMatrix4x4 clipSpaceCorrMatrix = rhiCtx->rhi()->clipSpaceCorrMatrix();
60
61 QSSGRhiShaderPipeline::CommonUniformIndices &cui = shaders.commonUniformIndices;
62
63 const int viewCount = cameras.count();
64
65 // Pull the camera transforms from the render data once.
66 QMatrix4x4 camGlobalTransforms[2] { QMatrix4x4{Qt::Uninitialized}, QMatrix4x4{Qt::Uninitialized} };
67 if (viewCount < 2) {
68 camGlobalTransforms[0] = inData.getGlobalTransform(*cameras[0]);
69 } else {
70 for (size_t viewIndex = 0; viewIndex != std::size(camGlobalTransforms); ++viewIndex)
71 camGlobalTransforms[viewIndex] = inData.getGlobalTransform(*cameras[viewIndex]);
72 }
73
74 if (viewCount < 2) {
75 const QMatrix4x4 projection = clipSpaceCorrMatrix * cameras[0]->projection;
76 shaders.setUniform(ubufData, "qt_projectionMatrix", projection.constData(), 16 * sizeof(float), &cui.projectionMatrixIdx);
77 const QMatrix4x4 viewMatrix = camGlobalTransforms[0].inverted();
78 shaders.setUniform(ubufData, "qt_viewMatrix", viewMatrix.constData(), 16 * sizeof(float), &cui.viewMatrixIdx);
79 } else {
80 QVarLengthArray<QMatrix4x4, 2> projectionMatrices(viewCount);
81 QVarLengthArray<QMatrix4x4, 2> viewMatrices(viewCount);
82 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) {
83 projectionMatrices[viewIndex] = clipSpaceCorrMatrix * cameras[viewIndex]->projection;
84 viewMatrices[viewIndex] = camGlobalTransforms[viewIndex].inverted();
85 }
86 shaders.setUniformArray(ubufData, "qt_projectionMatrix", projectionMatrices.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4, &cui.projectionMatrixIdx);
87 shaders.setUniformArray(ubufData, "qt_viewMatrix", viewMatrices.constData(), viewCount, QSSGRenderShaderValue::Matrix4x4, &cui.viewMatrixIdx);
88 }
89
90 const QMatrix4x4 &modelMatrix = renderable.globalTransform;
91 shaders.setUniform(ubufData, "qt_modelMatrix", modelMatrix.constData(), 16 * sizeof(float), &cui.modelMatrixIdx);
92
93 const QVector2D camProperties(cameras[0]->clipPlanes);
94 shaders.setUniform(ubufData, "qt_cameraProperties", &camProperties, 2 * sizeof(float), &cui.cameraPropertiesIdx);
95
96 QVector2D oneOverSize = QVector2D(1.0f, 1.0f);
97 auto &particleBuffer = renderable.particles.m_particleBuffer;
98 const quint32 particlesPerSlice = particleBuffer.particlesPerSlice();
99 oneOverSize = QVector2D(1.0f / particleBuffer.size().width(), 1.0f / particleBuffer.size().height());
100 shaders.setUniform(ubufData, "qt_oneOverParticleImageSize", &oneOverSize, 2 * sizeof(float));
101 shaders.setUniform(ubufData, "qt_countPerSlice", &particlesPerSlice, 1 * sizeof(quint32));
102
103 // Global opacity of the particles node
104 shaders.setUniform(ubufData, "qt_opacity", &renderable.opacity, 1 * sizeof(float));
105
106 float blendImages = renderable.particles.m_blendImages ? 1.0f : 0.0f;
107 float imageCount = float(renderable.particles.m_spriteImageCount);
108 float ooImageCount = 1.0f / imageCount;
109
110 QVector4D spriteConfig(imageCount, ooImageCount, 0.0f, blendImages);
111 shaders.setUniform(ubufData, "qt_spriteConfig", &spriteConfig, 4 * sizeof(float));
112
113 const float billboard = renderable.particles.m_billboard ? 1.0f : 0.0f;
114 shaders.setUniform(ubufData, "qt_billboard", &billboard, 1 * sizeof(float));
115
116 // Lights
117 QVector3D theLightAmbientTotal;
118 bool hasLights = !renderable.particles.m_lights.isEmpty();
119 int pointLight = 0;
120 int spotLight = 0;
121 if (hasLights) {
122 ParticleLightData lightData;
123 auto &lights = renderable.lights;
124 for (quint32 lightIdx = 0, lightEnd = lights.size();
125 lightIdx < lightEnd && lightIdx < QSSG_MAX_NUM_LIGHTS; ++lightIdx) {
126 QSSGRenderLight *theLight(lights[lightIdx].light);
127 // Ignore lights which are not specified for the particle
128 if (!renderable.particles.m_lights.contains(theLight))
129 continue;
130
131 const QMatrix4x4 lightGlobalTransform = inData.getGlobalTransform(*theLight);
132
133 if (theLight->type == QSSGRenderLight::Type::DirectionalLight) {
134 theLightAmbientTotal += theLight->m_diffuseColor * theLight->m_brightness;
135 } else if (theLight->type == QSSGRenderLight::Type::PointLight && pointLight < 4) {
136 lightData.pointLightColor[pointLight] = QVector4D(theLight->m_diffuseColor * theLight->m_brightness, 1.0f);
137 lightData.pointLightPos[pointLight] = QVector4D(QSSGRenderNode::getGlobalPos(lightGlobalTransform), 1.0f);
138 lightData.pointLightConstantAtt[pointLight] = QSSGUtils::aux::translateConstantAttenuation(theLight->m_constantFade);
139 lightData.pointLightLinearAtt[pointLight] = QSSGUtils::aux::translateLinearAttenuation(theLight->m_linearFade);
140 lightData.pointLightQuadAtt[pointLight] = QSSGUtils::aux::translateQuadraticAttenuation(theLight->m_quadraticFade);
141 pointLight++;
142 } else if (theLight->type == QSSGRenderLight::Type::SpotLight && spotLight < 4) {
143 lightData.spotLightColor[spotLight] = QVector4D(theLight->m_diffuseColor * theLight->m_brightness, 1.0f);
144 lightData.spotLightPos[spotLight] = QVector4D(QSSGRenderNode::getGlobalPos(lightGlobalTransform), 1.0f);
145 lightData.spotLightDir[spotLight] = QVector4D(lights[lightIdx].direction, 0.0f);
146 lightData.spotLightConstantAtt[spotLight] = QSSGUtils::aux::translateConstantAttenuation(theLight->m_constantFade);
147 lightData.spotLightLinearAtt[spotLight] = QSSGUtils::aux::translateLinearAttenuation(theLight->m_linearFade);
148 lightData.spotLightQuadAtt[spotLight] = QSSGUtils::aux::translateQuadraticAttenuation(theLight->m_quadraticFade);
149 float coneAngle = theLight->m_coneAngle;
150 // Inner cone angle must always be < cone angle, to not have possible undefined behavior for shader smoothstep
151 float innerConeAngle = std::min(theLight->m_innerConeAngle, coneAngle - 0.01f);
152 lightData.spotLightConeAngle[spotLight] = qDegreesToRadians(coneAngle);
153 lightData.spotLightInnerConeAngle[spotLight] = qDegreesToRadians(innerConeAngle);
154 spotLight++;
155 }
156 theLightAmbientTotal += theLight->m_ambientColor;
157 }
158 // Copy light data
159 int lightOffset = shaders.offsetOfUniform("lightData");
160 if (lightOffset >= 0)
161 memcpy(ubufData + lightOffset, &lightData, sizeof(ParticleLightData));
162 }
163 shaders.setUniform(ubufData, "qt_light_ambient_total", &theLightAmbientTotal, 3 * sizeof(float), &cui.light_ambient_totalIdx);
164 int enablePointLights = pointLight > 0 ? 1 : 0;
165 int enableSpotLights = spotLight > 0 ? 1 : 0;
166 shaders.setUniform(ubufData, "qt_pointLights", &enablePointLights, sizeof(int));
167 shaders.setUniform(ubufData, "qt_spotLights", &enableSpotLights, sizeof(int));
168
169 // Line particle uniform
170 int segmentCount = particleBuffer.segments();
171 if (segmentCount) {
172 shaders.setUniform(ubufData, "qt_lineSegmentCount", &segmentCount, sizeof(int));
173 float alphaFade = renderable.particles.m_alphaFade;
174 float sizeModifier = renderable.particles.m_sizeModifier;
175 float texcoordScale = renderable.particles.m_texcoordScale;
176 auto image = renderable.firstImage;
177 if (image && image->m_texture.m_texture) {
178 const auto size = image->m_texture.m_texture->pixelSize();
179 texcoordScale *= float(size.height()) / float(size.width());
180 }
181 shaders.setUniform(ubufData, "qt_alphaFade", &alphaFade, sizeof(float));
182 shaders.setUniform(ubufData, "qt_sizeModifier", &sizeModifier, sizeof(float));
183 shaders.setUniform(ubufData, "qt_texcoordScale", &texcoordScale, sizeof(float));
184 }
185
186#ifdef QSSG_OIT_USE_BUFFERS
187 shaders.setOITImages((QRhiTexture*)inData.oitRenderContext.aBuffer,
188 (QRhiTexture*)inData.oitRenderContext.auxBuffer,
189 (QRhiTexture*)inData.oitRenderContext.counterBuffer);
190 if (inData.oitRenderContext.aBuffer) {
191 int abufWidth = 0;
192 int listNodeCount = inData.layer.oitNodeCount;
193#else
194 const QSSGRhiRenderableTexture *abuf = inData.getRenderResult(QSSGRenderResult::Key::ABufferImage);
195 const QSSGRhiRenderableTexture *aux = inData.getRenderResult(QSSGRenderResult::Key::AuxiliaryImage);
196 const QSSGRhiRenderableTexture *counter = inData.getRenderResult(QSSGRenderResult::Key::CounterImage);
197 shaders.setOITImages(abuf->texture, aux->texture, counter->texture);
198 if (abuf->texture) {
199 int abufWidth = RenderHelpers::rhiCalculateABufferSize(inData.layer.oitNodeCount);
200 int listNodeCount = abufWidth * abufWidth;
201#endif
202 shaders.setUniform(ubufData, "qt_ABufImageWidth", &abufWidth, sizeof(int), &cui.abufImageWidth);
203 shaders.setUniform(ubufData, "qt_listNodeCount", &listNodeCount, sizeof(int), &cui.listNodeCount);
204 int viewSize[2] = {inData.layerPrepResult.textureDimensions().width(), inData.layerPrepResult.textureDimensions().height()};
205 shaders.setUniform(ubufData, "qt_viewSize", viewSize, sizeof(int) * 2, &cui.viewSize);
206 QVector2D vpOrigin;
207 if (inData.m_currentOrigin == QSSGLayerRenderData::WindowOrigin)
208 vpOrigin = inData.m_viewportOrigin;
209 shaders.setUniform(ubufData, "qt_viewportOrigin", &vpOrigin, sizeof(float) * 2, &cui.viewportOrigin);
210 int samples = rhiCtx->mainPassSampleCount();
211 shaders.setUniform(ubufData, "qt_samples", &samples, sizeof(int), &cui.samples);
212 }
213
214}
215
216void QSSGParticleRenderer::updateUniformsForParticleModel(QSSGRhiShaderPipeline &shaderPipeline,
217 char *ubufData,
218 const QSSGRenderModel *model,
219 quint32 offset)
220{
221 auto &particleBuffer = *model->particleBuffer;
222 const quint32 particlesPerSlice = particleBuffer.particlesPerSlice();
223 const QVector2D oneOverSize = QVector2D(1.0f / particleBuffer.size().width(), 1.0f / particleBuffer.size().height());
224 shaderPipeline.setUniform(ubufData, "qt_oneOverParticleImageSize", &oneOverSize, 2 * sizeof(float));
225 shaderPipeline.setUniform(ubufData, "qt_countPerSlice", &particlesPerSlice, sizeof(quint32));
226 const QMatrix4x4 &particleMatrix = model->particleMatrix;
227 shaderPipeline.setUniform(ubufData, "qt_particleMatrix", &particleMatrix, 16 * sizeof(float));
228 shaderPipeline.setUniform(ubufData, "qt_particleIndexOffset", &offset, sizeof(quint32));
229}
230
231static void fillTargetBlend(QRhiGraphicsPipeline::TargetBlend &targetBlend, QSSGRenderParticles::BlendMode mode)
232{
233 switch (mode) {
234 case QSSGRenderParticles::BlendMode::Screen:
235 targetBlend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
236 targetBlend.dstColor = QRhiGraphicsPipeline::One;
237 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
238 targetBlend.dstAlpha = QRhiGraphicsPipeline::One;
239 break;
240 case QSSGRenderParticles::BlendMode::Multiply:
241 targetBlend.srcColor = QRhiGraphicsPipeline::DstColor;
242 targetBlend.dstColor = QRhiGraphicsPipeline::Zero;
243 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
244 targetBlend.dstAlpha = QRhiGraphicsPipeline::One;
245 break;
246 default:
247 // Source over as default
248 targetBlend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
249 targetBlend.dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha;
250 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
251 targetBlend.dstAlpha = QRhiGraphicsPipeline::OneMinusSrcAlpha;
252 break;
253
254 }
255}
256
257static void sortParticles(const QSSGLayerRenderData &renderData, QByteArray &result, QList<QSSGRhiSortData> &sortData,
258 const QSSGParticleBuffer &buffer, const QSSGRenderParticles &particles,
259 const QVector3D &cameraDirection, bool animatedParticles)
260{
261 const QMatrix4x4 &modelMatrix = renderData.getGlobalTransform(particles);
262 const QMatrix4x4 &invModelMatrix = modelMatrix.inverted();
263 QVector3D dir = invModelMatrix.map(cameraDirection);
264 QVector3D n = dir.normalized();
265 const auto segments = buffer.segments();
266 auto particleCount = buffer.particleCount();
267 const bool lineParticles = segments > 0;
268 if (lineParticles)
269 particleCount /= segments;
270 sortData.resize(particleCount);
271 sortData.fill({});
272
273 const auto srcParticlePointer = [](int line, int segment, int sc, int ss, int pps, const char *source) -> const QSSGLineParticle * {
274 int pi = (line * sc + segment) / pps;
275 int i = (line * sc + segment) % pps;
276 const QSSGLineParticle *sp = reinterpret_cast<const QSSGLineParticle *>(source + pi * ss);
277 return sp + i;
278 };
279
280 // create sort data
281 {
282 const auto slices = buffer.sliceCount();
283 const auto ss = buffer.sliceStride();
284 const auto pps = buffer.particlesPerSlice();
285
286 QSSGRhiSortData *dst = sortData.data();
287 const char *source = buffer.pointer();
288 const char *begin = source;
289 int i = 0;
290 if (lineParticles) {
291 for (i = 0; i < particleCount; i++) {
292 QSSGRhiSortData lineData;
293 const QSSGLineParticle *lineBegin = srcParticlePointer(i, 0, segments, ss, pps, source);
294 lineData.indexOrOffset = i;
295 lineData.d = QVector3D::dotProduct(lineBegin->position, n);
296 for (int j = 1; j < buffer.segments(); j++) {
297 const QSSGLineParticle *p = srcParticlePointer(i, j, segments, ss, pps, source);
298 lineData.d = qMin(lineData.d, QVector3D::dotProduct(p->position, n));
299 }
300 *dst++ = lineData;
301 }
302 } else if (animatedParticles) {
303 for (int s = 0; s < slices; s++) {
304 const QSSGParticleAnimated *sp = reinterpret_cast<const QSSGParticleAnimated *>(source);
305 for (int p = 0; p < pps && i < particleCount; p++) {
306 *dst = { QVector3D::dotProduct(sp->position, n), int(reinterpret_cast<const char *>(sp) - begin)};
307 sp++;
308 dst++;
309 i++;
310 }
311 source += ss;
312 }
313 } else {
314 for (int s = 0; s < slices; s++) {
315 const QSSGParticleSimple *sp = reinterpret_cast<const QSSGParticleSimple *>(source);
316 for (int p = 0; p < pps && i < particleCount; p++) {
317 *dst = { QVector3D::dotProduct(sp->position, n), int(reinterpret_cast<const char *>(sp) - begin)};
318 sp++;
319 dst++;
320 i++;
321 }
322 source += ss;
323 }
324 }
325 }
326
327 // sort
328 result.resize(buffer.bufferSize());
329 std::sort(sortData.begin(), sortData.end(), [](const QSSGRhiSortData &a, const QSSGRhiSortData &b){
330 return a.d > b.d;
331 });
332
333 auto copyParticles = [&](QByteArray &dst, const QList<QSSGRhiSortData> &data, const QSSGParticleBuffer &buffer) {
334 const auto slices = buffer.sliceCount();
335 const auto ss = buffer.sliceStride();
336 const auto pps = buffer.particlesPerSlice();
337 const QSSGRhiSortData *sdata = data.data();
338 char *dest = dst.data();
339 const char *source = buffer.pointer();
340 int i = 0;
341 if (lineParticles) {
342 int seg = 0;
343 for (int s = 0; s < slices; s++) {
344 QSSGLineParticle *dp = reinterpret_cast<QSSGLineParticle *>(dest);
345 for (int p = 0; p < pps && i < particleCount; p++) {
346 *dp = *srcParticlePointer(sdata->indexOrOffset, seg, segments, ss, pps, source);
347 dp++;
348 seg++;
349 if (seg == segments) {
350 sdata++;
351 i++;
352 seg = 0;
353 }
354 }
355 dest += ss;
356 }
357 } else if (animatedParticles) {
358 for (int s = 0; s < slices; s++) {
359 QSSGParticleAnimated *dp = reinterpret_cast<QSSGParticleAnimated *>(dest);
360 for (int p = 0; p < pps && i < particleCount; p++) {
361 *dp = *reinterpret_cast<const QSSGParticleAnimated *>(source + sdata->indexOrOffset);
362 dp++;
363 sdata++;
364 i++;
365 }
366 dest += ss;
367 }
368 } else {
369 for (int s = 0; s < slices; s++) {
370 QSSGParticleSimple *dp = reinterpret_cast<QSSGParticleSimple *>(dest);
371 for (int p = 0; p < pps && i < particleCount; p++) {
372 *dp = *reinterpret_cast<const QSSGParticleSimple *>(source + sdata->indexOrOffset);
373 dp++;
374 sdata++;
375 i++;
376 }
377 dest += ss;
378 }
379 }
380 };
381
382 // write result
383 copyParticles(result, sortData, buffer);
384}
385
386static QByteArray convertParticleData(QByteArray &dest, const QByteArray &data, bool convert)
387{
388 if (!convert)
389 return data;
390 int count = data.size() / 4;
391 if (dest.size() != count * 2)
392 dest.resize(2 * count);
393 qFloatToFloat16(reinterpret_cast<qfloat16 *>(dest.data()), reinterpret_cast<const float *>(data.constData()), count);
394 return dest;
395}
396
397void QSSGParticleRenderer::rhiPrepareRenderable(QSSGRhiShaderPipeline &shaderPipeline,
398 QSSGPassKey passKey,
399 QSSGRhiContext *rhiCtx,
400 QSSGRhiGraphicsPipelineState *ps,
401 QSSGParticlesRenderable &renderable,
402 const QSSGLayerRenderData &inData,
403 QRhiRenderPassDescriptor *renderPassDescriptor,
404 int samples,
405 int viewCount,
406 QSSGRenderCamera *alteredCamera,
407 QSSGRenderTextureCubeFace cubeFace,
408 QSSGReflectionMapEntry *entry,
409 bool oit)
410{
411 const void *node = &renderable.particles;
412 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
413
414 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
415 QSSGRhiDrawCallData &dcd = QSSGRhiContextPrivate::get(rhiCtx)->drawCallData({ passKey, node, nullptr, entry,
416 cubeFaceIdx });
417 shaderPipeline.ensureUniformBuffer(&dcd.ubuf);
418
419 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
420 if (!alteredCamera) {
421 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, inData.renderedCameras);
422 } else {
423 QSSGRenderCameraList cameras({ alteredCamera });
424 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, cameras);
425 }
426 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
427
428 QSSGRhiParticleData &particleData = QSSGRhiContextPrivate::get(rhiCtx)->particleData(&renderable.particles);
429 const QSSGParticleBuffer &particleBuffer = renderable.particles.m_particleBuffer;
430 int particleCount = particleBuffer.particleCount();
431 if (particleData.texture == nullptr || particleData.particleCount != particleCount) {
432 QSize size(particleBuffer.size());
433 if (!particleData.texture) {
434 particleData.texture = rhiCtx->rhi()->newTexture(needsConversion ? QRhiTexture::RGBA16F : QRhiTexture::RGBA32F, size);
435 particleData.texture->create();
436 } else {
437 particleData.texture->setPixelSize(size);
438 particleData.texture->create();
439 }
440 particleData.particleCount = particleCount;
441 }
442
443 bool sortingChanged = particleData.sorting != renderable.particles.m_depthSorting;
444 if (sortingChanged && !renderable.particles.m_depthSorting) {
445 particleData.sortData.clear();
446 particleData.sortedData.clear();
447 }
448 particleData.sorting = renderable.particles.m_depthSorting;
449
450 QByteArray uploadData;
451
452 if (renderable.particles.m_depthSorting) {
453 bool animatedParticles = renderable.particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Animated;
454 if (!alteredCamera) {
455 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, inData.renderedCameraData.value()[0].direction, animatedParticles);
456 } else {
457 const QMatrix4x4 globalTransform = inData.getGlobalTransform(*alteredCamera);
458 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, QSSGRenderNode::getScalingCorrectDirection(globalTransform), animatedParticles);
459 }
460 uploadData = convertParticleData(particleData.convertData, particleData.sortedData, needsConversion);
461 } else {
462 uploadData = convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion);
463 }
464
465 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
466 QRhiTextureSubresourceUploadDescription upload;
467 upload.setData(uploadData);
468 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, upload));
469 rub->uploadTexture(particleData.texture, uploadDesc);
470 rhiCtx->commandBuffer()->resourceUpdate(rub);
471
472 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
473 ia.topology = QRhiGraphicsPipeline::TriangleStrip;
474 ia.inputLayout = QRhiVertexInputLayout();
475 ia.inputs.clear();
476
477 ps->samples = samples;
478 ps->viewCount = viewCount;
479 ps->cullMode = QRhiGraphicsPipeline::None;
480
481 if (inData.orderIndependentTransparencyEnabled == false) {
482 if (renderable.renderableFlags.hasTransparency())
483 fillTargetBlend(ps->targetBlend[0], renderable.particles.m_blendMode);
484 else
485 ps->targetBlend[0] = QRhiGraphicsPipeline::TargetBlend();
486 }
487
488 QSSGRhiShaderResourceBindingList bindings;
489 bindings.addUniformBuffer(0, VISIBILITY_ALL, dcd.ubuf, 0, shaderPipeline.ub0Size());
490
491 // Texture maps
492 // we only have one image
493 QSSGRenderableImage *renderableImage = renderable.firstImage;
494
495 int samplerBinding = shaderPipeline.bindingForTexture("qt_sprite");
496 if (samplerBinding >= 0) {
497 QRhiTexture *texture = renderableImage ? renderableImage->m_texture.m_texture : nullptr;
498 if (samplerBinding >= 0 && texture) {
499 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
500 QRhiSampler *sampler = rhiCtx->sampler({ QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
501 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
502 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
503 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
504 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
505 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
506 });
507 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
508 } else {
509 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
510 QRhiTexture *texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
511 rhiCtx->commandBuffer()->resourceUpdate(rub);
512 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
513 QRhiSampler::Nearest,
514 QRhiSampler::None,
515 QRhiSampler::ClampToEdge,
516 QRhiSampler::ClampToEdge,
517 QRhiSampler::Repeat
518 });
519 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
520 }
521 }
522
523 samplerBinding = shaderPipeline.bindingForTexture("qt_particleTexture");
524 if (samplerBinding >= 0) {
525 QRhiTexture *texture = particleData.texture;
526 if (samplerBinding >= 0 && texture) {
527 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
528 QRhiSampler::Nearest,
529 QRhiSampler::None,
530 QRhiSampler::ClampToEdge,
531 QRhiSampler::ClampToEdge,
532 QRhiSampler::Repeat
533 });
534 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
535 }
536 }
537
538 samplerBinding = shaderPipeline.bindingForTexture("qt_colorTable");
539 if (samplerBinding >= 0) {
540 bool hasTexture = false;
541 if (renderable.colorTable) {
542 QRhiTexture *texture = renderable.colorTable->m_texture.m_texture;
543 if (texture) {
544 hasTexture = true;
545 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
546 QRhiSampler::Nearest,
547 QRhiSampler::None,
548 QRhiSampler::ClampToEdge,
549 QRhiSampler::ClampToEdge,
550 QRhiSampler::Repeat
551 });
552 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
553 }
554 }
555
556 if (!hasTexture) {
557 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
558 QRhiTexture *texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
559 rhiCtx->commandBuffer()->resourceUpdate(rub);
560 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
561 QRhiSampler::Nearest,
562 QRhiSampler::None,
563 QRhiSampler::ClampToEdge,
564 QRhiSampler::ClampToEdge,
565 QRhiSampler::Repeat
566 });
567 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
568 }
569 }
570
571 if (oit && inData.layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
572 RenderHelpers::addAccumulatorImageBindings(&shaderPipeline, bindings);
573
574 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
575
576 // TODO: This is identical to other renderables. Make into a function?
577 QRhiShaderResourceBindings *&srb = dcd.srb;
578 bool srbChanged = false;
579 if (!srb || bindings != dcd.bindings) {
580 srb = rhiCtxD->srb(bindings);
581 rhiCtxD->releaseCachedSrb(dcd.bindings);
582 dcd.bindings = bindings;
583 srbChanged = true;
584 }
585
586 if (cubeFace == QSSGRenderTextureCubeFaceNone)
587 renderable.rhiRenderData.mainPass.srb = srb;
588 else
589 renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx] = srb;
590
591 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
592 if (dcd.pipeline
593 && !srbChanged
594 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash
595 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
596 && dcd.ps == *ps)
597 {
598 if (cubeFace == QSSGRenderTextureCubeFaceNone)
599 renderable.rhiRenderData.mainPass.pipeline = dcd.pipeline;
600 else
601 renderable.rhiRenderData.reflectionPass.pipeline = dcd.pipeline;
602 } else {
603 if (cubeFace == QSSGRenderTextureCubeFaceNone) {
604 renderable.rhiRenderData.mainPass.pipeline = rhiCtxD->pipeline(pipelineKey,
605 renderPassDescriptor,
606 srb);
607 dcd.pipeline = renderable.rhiRenderData.mainPass.pipeline;
608 } else {
609 renderable.rhiRenderData.reflectionPass.pipeline = rhiCtxD->pipeline(pipelineKey,
610 renderPassDescriptor,
611 srb);
612 dcd.pipeline = renderable.rhiRenderData.reflectionPass.pipeline;
613 }
614 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
615 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
616 dcd.ps = *ps;
617 }
618}
619
620void QSSGParticleRenderer::prepareParticlesForModel(QSSGRhiShaderPipeline &shaderPipeline,
621 QSSGRhiContext *rhiCtx,
622 QSSGRhiShaderResourceBindingList &bindings,
623 const QSSGRenderModel *model)
624{
625 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
626 QSSGRhiParticleData &particleData = rhiCtxD->particleData(model);
627 const QSSGParticleBuffer &particleBuffer = *model->particleBuffer;
628 int particleCount = particleBuffer.particleCount();
629 bool update = particleBuffer.serial() != particleData.serial;
630 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
631 if (particleData.texture == nullptr || particleData.particleCount != particleCount) {
632 QSize size(particleBuffer.size());
633 if (!particleData.texture) {
634 particleData.texture = rhiCtx->rhi()->newTexture(needsConversion ? QRhiTexture::RGBA16F : QRhiTexture::RGBA32F, size);
635 particleData.texture->create();
636 } else {
637 particleData.texture->setPixelSize(size);
638 particleData.texture->create();
639 }
640 particleData.particleCount = particleCount;
641 update = true;
642 }
643
644 if (update) {
645 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
646 QRhiTextureSubresourceUploadDescription upload;
647 upload.setData(convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion));
648 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, upload));
649 rub->uploadTexture(particleData.texture, uploadDesc);
650 rhiCtx->commandBuffer()->resourceUpdate(rub);
651 }
652 particleData.serial = particleBuffer.serial();
653 int samplerBinding = shaderPipeline.bindingForTexture("qt_particleTexture");
654 if (samplerBinding >= 0) {
655 QRhiTexture *texture = particleData.texture;
656 if (samplerBinding >= 0 && texture) {
657 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
658 QRhiSampler::Nearest,
659 QRhiSampler::None,
660 QRhiSampler::ClampToEdge,
661 QRhiSampler::ClampToEdge,
662 QRhiSampler::Repeat
663 });
664 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
665 }
666 }
667}
668
669static QByteArray particlesLogPrefix() { return QByteArrayLiteral("particle material pipeline-- "); }
670
672{
680 void addUniform(const QByteArray &name, const QByteArray &type)
681 {
682 vs->addUniform(name, type);
683 fs->addUniform(name, type);
684 }
685 void addUniformArray(const QByteArray &name, const QByteArray &type, quint32 size)
686 {
687 vs->addUniformArray(name, type, size);
688 fs->addUniformArray(name, type, size);
689 }
690 void addDefinition(const QByteArray &name, const QByteArray &value)
691 {
692 vs->addDefinition(name, value);
693 fs->addDefinition(name, value);
694 }
695 void addInterpolant(const QByteArray &name, const QByteArray &type)
696 {
697 vs->addOutgoing(name, type);
698 fs->addIncoming(name, type);
699 }
700 void addFlatInterpolant(const QByteArray &name, const QByteArray &type)
701 {
702 vs->addFlatOutgoing(name, type);
703 fs->addFlatIncoming(name, type);
704 }
705 void addPrefix(const QByteArray &prefix)
706 {
707 vs->addPrefix(prefix);
708 fs->addPrefix(prefix);
709 }
710};
711
713{
715 int indent = 0;
716 AutoFormatGenerator(QSSGStageGeneratorBase &g)
717 : gen(g)
718 {
719
720 }
721 AutoFormatGenerator &operator<<(const QByteArray &data)
722 {
723 for (int i = 0; i < indent; i++)
724 gen << " ";
725 gen << data << "\n";
726 return *this;
727 }
729 {
730 indent++;
731 }
733 {
734 indent--;
735 Q_ASSERT(indent >= 0);
736 }
737};
738
739static const char *s_lightPrefix = {
740 "struct ParticleLightData\n"
741 "{\n"
742 " vec4 qt_pointLightPosition[4];\n"
743 " vec4 qt_pointLightConstantAtt;\n"
744 " vec4 qt_pointLightLinearAtt;\n"
745 " vec4 qt_pointLightQuadAtt;\n"
746 " vec4 qt_pointLightColor[4];\n"
747 " vec4 qt_spotLightPosition[4];\n"
748 " vec4 qt_spotLightConstantAtt;\n"
749 " vec4 qt_spotLightLinearAtt;\n"
750 " vec4 qt_spotLightQuadAtt;\n"
751 " vec4 qt_spotLightColor[4];\n"
752 " vec4 qt_spotLightDirection[4];\n"
753 " vec4 qt_spotLightConeAngle;\n"
754 " vec4 qt_spotLightInnerConeAngle;\n"
755 "};\n"
756};
757
758QSSGShaderFeatures QSSGParticleRenderer::particleShaderFeatures(const QSSGShaderFeatures& features)
759{
760#define COPY_FEATURE(f) ret.set(f, features.isSet(f));
761 QSSGShaderFeatures ret;
762 COPY_FEATURE(QSSGShaderFeatures::Feature::LinearTonemapping);
763 COPY_FEATURE(QSSGShaderFeatures::Feature::AcesTonemapping);
764 COPY_FEATURE(QSSGShaderFeatures::Feature::HejlDawsonTonemapping);
765 COPY_FEATURE(QSSGShaderFeatures::Feature::FilmicTonemapping);
766 COPY_FEATURE(QSSGShaderFeatures::Feature::DisableMultiView);
767#undef COPY_FEATURE
768 return ret;
769}
770
771QSSGRhiShaderPipelinePtr QSSGParticleRenderer::generateRhiShaderPipeline(QSSGRenderer &renderer,
772 QSSGParticlesRenderable &inRenderable,
773 const QSSGShaderFeatures &inFeatureSet,
774 QByteArray &shaderString,
775 const QSSGShaderParticleMaterialKeyProperties &shaderKeyProperties)
776{
777 const auto &m_contextInterface = renderer.m_contextInterface;
778 const auto &shaderCache = m_contextInterface->shaderCache();
779 const auto &shaderProgramGenerator = m_contextInterface->shaderProgramGenerator();
780 const auto &shaderLibraryManager = m_contextInterface->shaderLibraryManager();
781
782 shaderString = particlesLogPrefix();
783 QSSGShaderParticleMaterialKey theKey(inRenderable.shaderDescription);
784
785 theKey.toString(shaderString, shaderKeyProperties);
786
787 if (s_shaderCacheEnabled) {
788 if (const auto &maybePipeline = shaderCache->tryGetRhiShaderPipeline(shaderString, inFeatureSet))
789 return maybePipeline;
790
791 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(shaderString, QQsbCollection::toFeatureSet(inFeatureSet));
792 // Check if there's a pre-built (offline generated) shader for available.
793 if (renderer.m_currentLayer) {
794 QQsbCollection::EntryMap &pregenEntries = renderer.m_currentLayer->m_particleShaderEntries;
795 if (pregenEntries.isEmpty()) {
796 renderer.m_currentLayer->m_particleShaderEntries = shaderLibraryManager->getParticleShaderEntries();
797 pregenEntries = renderer.m_currentLayer->m_particleShaderEntries;
798 }
799 if (!pregenEntries.isEmpty()) {
800 const auto foundIt = pregenEntries.constFind(QQsbCollection::Entry(qsbcKey));
801 if (foundIt != pregenEntries.cend())
802 return shaderCache->newPipelineFromPregenerated(shaderString, inFeatureSet, *foundIt, inRenderable.particles);
803 }
804 }
805
806 // Try the persistent (disk-based) cache then.
807 if (const auto &maybePipeline = shaderCache->tryNewPipelineFromPersistentCache(qsbcKey, shaderString, inFeatureSet))
808 return maybePipeline;
809 }
810
811 // generate shader code
812 shaderProgramGenerator->beginProgram();
813 auto &vertex = *shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Vertex);
814 auto &fragment = *shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Fragment);
815 ShaderGeneratorCommon common(*shaderProgramGenerator);
816 const bool isSpriteLinear = shaderKeyProperties.m_isSpriteLinear.getValue(theKey);
817 const bool isColorTableLinear = shaderKeyProperties.m_isColorTableLinear.getValue(theKey);
818 const bool lighting = shaderKeyProperties.m_hasLighting.getValue(theKey);
819 const bool isMapped = shaderKeyProperties.m_isMapped.getValue(theKey);
820 const bool isLineParticle = shaderKeyProperties.m_isLineParticle.getValue(theKey);
821 const bool isAnimated = shaderKeyProperties.m_isAnimated.getValue(theKey);
822 const int viewCount = inFeatureSet.isSet(QSSGShaderFeatures::Feature::DisableMultiView)
823 ? 1 : shaderKeyProperties.m_viewCount.getValue(theKey);
824 const int oit = shaderKeyProperties.m_orderIndependentTransparency.getValue(theKey);
825 const bool oitMSAA = shaderKeyProperties.m_oitMSAA.getValue(theKey);
826
827 if (isAnimated)
828 common.addDefinition("QSSG_PARTICLES_ENABLE_ANIMATED", "1");
829 if (isLineParticle)
830 common.addDefinition("QSSG_PARTICLES_ENABLE_LINE_PARTICLE", "1");
831 if (oit)
832 common.addDefinition("QSSG_OIT_METHOD", QStringLiteral("%1").arg(oit).toUtf8());
833 if (oitMSAA)
834 common.addDefinition("QSSG_MULTISAMPLE", "1");
835
836 common.addUniform("qt_modelMatrix", "mat4");
837 if (viewCount >= 2) {
838 common.addUniformArray("qt_viewMatrix", "mat4", viewCount);
839 common.addUniformArray("qt_projectionMatrix", "mat4", viewCount);
840 } else {
841 common.addUniform("qt_viewMatrix", "mat4");
842 common.addUniform("qt_projectionMatrix", "mat4");
843 }
844 if (lighting) {
845 common.addPrefix(s_lightPrefix);
846 common.addUniform("lightData", "ParticleLightData");
847 }
848 common.addUniform("qt_spriteConfig", "vec4");
849 common.addUniform("qt_light_ambient_total", "vec3");
850 common.addUniform("qt_oneOverParticleImageSize", "vec2");
851 common.addUniform("qt_countPerSlice", "uint");
852 if (isLineParticle)
853 common.addUniform("qt_lineSegmentCount", "uint");
854 common.addUniform("qt_billboard", "float");
855 common.addUniform("qt_opacity", "float");
856 if (isLineParticle) {
857 common.addUniform("qt_alphaFade", "float");
858 common.addUniform("qt_sizeModifier", "float");
859 common.addUniform("qt_texcoordScale", "float");
860 }
861 if (lighting) {
862 common.addUniform("qt_pointLights", "bool");
863 common.addUniform("qt_spotLights", "bool");
864 }
865 if (oit == (int)QSSGRenderLayer::OITMethod::WeightedBlended) {
866 common.addUniform("qt_cameraProperties", "vec2");
867 } else if (oit == (int)QSSGRenderLayer::OITMethod::LinkedList) {
868 common.addUniform("qt_viewSize", "ivec2");
869 common.addUniform("qt_ABufImageWidth", "uint");
870 common.addUniform("qt_viewportOrigin", "vec2");
871 common.addUniform("qt_listNodeCount", "uint");
872#ifdef QSSG_OIT_USE_BUFFERS
873 common.addUniform("qt_samples", "uint");
874#endif
875 }
876
877 if (lighting)
878 vertex.addInclude("particleLighting.glsllib");
879
880 vertex.addUniform("qt_particleTexture", "sampler2D");
881
882 vertex.addInclude("particleLoading.glsllib");
883
884 common.addInterpolant("color", "vec4");
885 common.addInterpolant("spriteData", "vec2");
886 common.addInterpolant("texcoord", "vec2");
887 common.addFlatInterpolant("instanceIndex", "uint");
888 if (oit == (int)QSSGRenderLayer::OITMethod::LinkedList && viewCount >= 2)
889 common.addFlatInterpolant("v_viewIndex", "uint");
890
891 AutoFormatGenerator vg(vertex);
892 if (!isLineParticle)
893 vg << "const vec2 corners[4] = {{0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {1.0, 1.0}};";
894
895 // vertex shader main
896 vg << "out gl_PerVertex {"
897 << " vec4 gl_Position;"
898 << "};";
899
900 vg << "void main() {";
901 vg.incIndent();
902 if (isLineParticle) {
903 vg << "uint segmentIndex = gl_VertexIndex / 2;"
904 << "uint particleIndex = segmentIndex + gl_InstanceIndex * qt_lineSegmentCount;";
905 } else {
906 vg << "uint particleIndex = gl_InstanceIndex;"
907 << "uint cornerIndex = gl_VertexIndex;"
908 << "vec2 corner = corners[cornerIndex];";
909 }
910 vg << "instanceIndex = particleIndex;"
911 << "Particle p = qt_loadParticle(particleIndex);";
912
913 if (isLineParticle) {
914 vg << "float side = float(mod(gl_VertexIndex, 2)) - 0.5;"
915 << "float size = p.size * qt_calcSizeFactor(segmentIndex);"
916 << "vec3 o = p.binormal * side * size;"
917 << "vec4 worldPos = qt_modelMatrix * vec4(p.position + (1.0 - qt_billboard) * o, 1.0);";
918 if (viewCount >= 2) {
919 vg << "vec4 viewPos = qt_viewMatrix[gl_ViewIndex] * worldPos;"
920 << "vec3 viewBN = (transpose(inverse(qt_viewMatrix[gl_ViewIndex] * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
921 } else {
922 vg << "vec4 viewPos = qt_viewMatrix * worldPos;"
923 << "vec3 viewBN = (transpose(inverse(qt_viewMatrix * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
924 }
925 vg << "viewBN.z = 0;"
926 << "viewBN = normalize(viewBN) * side * size;"
927 << "viewPos = viewPos + vec4(viewBN, 0.0) * qt_billboard;"
928 << "texcoord.x = p.segmentLength * qt_texcoordScale;"
929 << "texcoord.y = float(mod(gl_VertexIndex, 2));"
930 << "color = p.color;"
931 << "color.a *= qt_opacity * qt_calcAlphaFade(segmentIndex);";
932 } else {
933 vg << "mat3 rotMat = qt_fromEulerRotation(p.rotation);"
934 << "vec4 worldPos = qt_modelMatrix * vec4(p.position, 1.0);"
935 << "vec4 viewPos = worldPos;"
936 << "vec3 offset = (p.size * vec3(corner - vec2(0.5), 0.0));"
937 << "viewPos.xyz += offset * rotMat * (1.0 - qt_billboard);";
938 if (viewCount >= 2)
939 vg << "viewPos = qt_viewMatrix[gl_ViewIndex] * viewPos;";
940 else
941 vg << "viewPos = qt_viewMatrix * viewPos;";
942 vg << "viewPos.xyz += rotMat * offset * qt_billboard;"
943 << "texcoord = corner;"
944 << "color = p.color;"
945 << "color.a *= qt_opacity;";
946 }
947 if (lighting)
948 vg << "color.rgb *= qt_calcLightColor(worldPos.xyz);";
949 if (viewCount >= 2) {
950 if (oit == int(QSSGRenderLayer::OITMethod::LinkedList))
951 vg << "v_viewIndex = gl_ViewIndex;";
952 vg << "gl_Position = qt_projectionMatrix[gl_ViewIndex] * viewPos;";
953 } else {
954 vg << "gl_Position = qt_projectionMatrix * viewPos;";
955 }
956 if (isMapped)
957 vg << "spriteData.x = qt_ageToSpriteFactor(p.age);";
958 if (isAnimated)
959 vg << "spriteData.y = p.animationFrame;";
960 vg.decIndent();
961 vg << "}";
962
963 // fragment shader main
964 fragment.addInclude("tonemapping.glsllib");
965 fragment.addInclude("particleSprite.glsllib");
966 fragment.addUniform("qt_sprite", "sampler2D");
967
968 AutoFormatGenerator fg(fragment);
969
970 if (oit == int(QSSGRenderLayer::OITMethod::WeightedBlended)) {
971 fragment.addInclude("oitweightedblended.glsllib");
972 fg << "layout(location = 1) out vec4 revealageOutput;";
973 } else if (oit == int(QSSGRenderLayer::OITMethod::LinkedList)) {
974#ifdef QSSG_OIT_USE_BUFFERS
975 fragment.addInclude("oitlinkedlist_buf.glsllib");
976 QSSGShaderResourceMergeContext::setAdditionalBufferAmount(3);
977#else
978 fragment.addInclude("oitlinkedlist.glsllib");
979#endif
980 }
981 if (isSpriteLinear)
982 fg << "#define spriteFunc";
983 else
984 fg << "#define spriteFunc qt_sRGBToLinear";
985 if (isMapped) {
986 fragment.addUniform("qt_colorTable", "sampler2D");
987 if (isColorTableLinear)
988 fg << "#define colorTableFunc";
989 else
990 fg << "#define colorTableFunc qt_sRGBToLinear";
991 }
992
993 fg << "vec4 qt_readSprite() {";
994 fg.incIndent();
995 if (isAnimated) {
996 fg << "vec2 coords[2];"
997 << "float factor = qt_spriteCoords(coords);"
998 << "return mix(spriteFunc(texture(qt_sprite, coords[0])), spriteFunc(texture(qt_sprite, coords[1])), factor);";
999 } else {
1000 fg << "return spriteFunc(texture(qt_sprite, texcoord));";
1001 }
1002 fg.decIndent();
1003 fg << "}";
1004 fg << "vec4 qt_readColor() {";
1005 fg.incIndent();
1006 if (isMapped)
1007 fg << "return color * colorTableFunc(texture(qt_colorTable, vec2(spriteData.x, qt_rand(vec2(instanceIndex, 0)))));";
1008 else
1009 fg << "return color;";
1010 fg.decIndent();
1011 fg << "}";
1012 fg << "void main() {";
1013 fg.incIndent();
1014 fg << "vec4 ret = qt_readColor() * qt_readSprite();";
1015 if (oit) {
1016 if (oit == int(QSSGRenderLayer::OITMethod::WeightedBlended)) {
1017 fg << "float z = abs(gl_FragCoord.z);"
1018 << "float distWeight = qt_transparencyWeight(z, ret.a, qt_cameraProperties.y);"
1019 << "fragOutput = distWeight * qt_tonemap(ret);"
1020 << "revealageOutput = vec4(ret.a);";
1021 } else if (oit == int(QSSGRenderLayer::OITMethod::LinkedList)) {
1022#ifdef QSSG_OIT_USE_BUFFERS
1023 if (viewCount >= 2)
1024 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex, qt_samples);";
1025 else
1026 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0, qt_samples);";
1027#else
1028 if (viewCount >= 2)
1029 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex);";
1030 else
1031 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0);";
1032#endif
1033 }
1034 } else {
1035 fg << "fragOutput = qt_tonemap(ret);";
1036 }
1037 fg.decIndent();
1038 fg << "}";
1039
1040
1041 return shaderProgramGenerator->compileGeneratedRhiShader(shaderString,
1042 inFeatureSet,
1043 *shaderLibraryManager,
1044 *shaderCache,
1045 QSSGRhiShaderPipeline::UsedWithoutIa,
1046 {},
1047 shaderKeyProperties.m_viewCount.getValue(inRenderable.shaderDescription),
1048 false);
1049}
1050
1051QSSGRhiShaderPipelinePtr QSSGParticleRenderer::getShaderPipelineParticles(QSSGRenderer &renderer,
1052 QSSGParticlesRenderable &inRenderable,
1053 const QSSGShaderFeatures &inFeatureSet)
1054{
1055 const auto features = particleShaderFeatures(inFeatureSet);
1056 auto *m_currentLayer = renderer.m_currentLayer;
1057 QSSG_ASSERT(m_currentLayer != nullptr, return {});
1058
1059 auto &shaderMap = m_currentLayer->particleShaderMap;
1060
1061 QElapsedTimer timer;
1062 timer.start();
1063
1064 QSSGRhiShaderPipelinePtr shaderPipeline;
1065
1066 // This just references inFeatureSet and inRenderable.shaderDescription -
1067 // cheap to construct and is good enough for the find()
1068 QSSGParticleShaderMapKey skey = QSSGParticleShaderMapKey(QByteArray(),
1069 features,
1070 inRenderable.shaderDescription);
1071 auto it = shaderMap.find(skey);
1072 if (it == shaderMap.end()) {
1073 Q_TRACE_SCOPE(QSSG_generateShader);
1074 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DGenerateShader);
1075 auto &shaderString = renderer.m_currentLayer->generatedShaderString;
1076 shaderPipeline = QSSGParticleRenderer::generateRhiShaderPipeline(renderer, inRenderable, features, shaderString, m_currentLayer->particleMaterialShaderKeyProperties);
1077 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DGenerateShader, 0, inRenderable.particles.profilingId);
1078 // make skey useable as a key for the QHash (makes a copy of the materialKey, instead of just referencing)
1079 skey.detach();
1080 // insert it no matter what, no point in trying over and over again
1081 shaderMap.insert(skey, shaderPipeline);
1082 } else {
1083 shaderPipeline = it.value();
1084 }
1085
1086 if (shaderPipeline != nullptr) {
1087 if (m_currentLayer && !m_currentLayer->renderedCameras.isEmpty())
1088 m_currentLayer->ensureCachedCameraDatas();
1089 }
1090
1091 const auto &rhiContext = renderer.m_contextInterface->rhiContext();
1092 QSSGRhiContextStats::get(*rhiContext).registerMaterialShaderGenerationTime(timer.elapsed());
1093
1094 return shaderPipeline;
1095}
1096
1097void QSSGParticleRenderer::rhiRenderRenderable(QSSGRhiContext *rhiCtx,
1098 QSSGParticlesRenderable &renderable,
1099 bool *needsSetViewport,
1100 QSSGRenderTextureCubeFace cubeFace,
1101 const QSSGRhiGraphicsPipelineState &state)
1102{
1103 QRhiGraphicsPipeline *ps = renderable.rhiRenderData.mainPass.pipeline;
1104 QRhiShaderResourceBindings *srb = renderable.rhiRenderData.mainPass.srb;
1105
1106 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1107 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
1108 ps = renderable.rhiRenderData.reflectionPass.pipeline;
1109 srb = renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx];
1110 }
1111
1112 if (!ps || !srb)
1113 return;
1114
1115 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
1116
1117 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1118 // QRhi optimizes out unnecessary binding of the same pipline
1119 cb->setGraphicsPipeline(ps);
1120 cb->setVertexInput(0, 0, nullptr);
1121 cb->setShaderResources(srb);
1122
1123 if (needsSetViewport && *needsSetViewport) {
1124 cb->setViewport(state.viewport);
1125 *needsSetViewport = false;
1126 }
1127 if (renderable.particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line) {
1128 // draw triangle strip with 2 * segmentCount vertices N times
1129 int S = renderable.particles.m_particleBuffer.segments();
1130 int N = renderable.particles.m_particleBuffer.particleCount() / S;
1131 cb->draw(2 * S, N);
1132 QSSGRHICTX_STAT(rhiCtx, draw(2 * S, N));
1133 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (2 * S | quint64(N) << 32), renderable.particles.profilingId);
1134 } else {
1135 // draw triangle strip with 2 triangles N times
1136 cb->draw(4, renderable.particles.m_particleBuffer.particleCount());
1137 QSSGRHICTX_STAT(rhiCtx, draw(4, renderable.particles.m_particleBuffer.particleCount()));
1138 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (4 | quint64(renderable.particles.m_particleBuffer.particleCount()) << 32), renderable.particles.profilingId);
1139 }
1140}
1141
1142QT_END_NAMESPACE
\keyword 16-bit Floating Point Support\inmodule QtCore \inheaderfile QFloat16
Definition qfloat16.h:62
Combined button and popup list for selecting options.
Q_CORE_EXPORT void qFloatToFloat16(qfloat16 *, const float *, qsizetype length) noexcept
#define QSSGRHICTX_STAT(ctx, f)
#define QSSG_MAX_NUM_LIGHTS
static QByteArray particlesLogPrefix()
static const char * s_lightPrefix
static QByteArray convertParticleData(QByteArray &dest, const QByteArray &data, bool convert)
static void fillTargetBlend(QRhiGraphicsPipeline::TargetBlend &targetBlend, QSSGRenderParticles::BlendMode mode)
static bool s_shaderCacheEnabled
static void sortParticles(const QSSGLayerRenderData &renderData, QByteArray &result, QList< QSSGRhiSortData > &sortData, const QSSGParticleBuffer &buffer, const QSSGRenderParticles &particles, const QVector3D &cameraDirection, bool animatedParticles)
static QT_BEGIN_NAMESPACE const QRhiShaderResourceBinding::StageFlags VISIBILITY_ALL
#define COPY_FEATURE(f)
AutoFormatGenerator(QSSGStageGeneratorBase &g)
QSSGStageGeneratorBase & gen
QVector4D spotLightPos[4]
QVector4D spotLightColor[4]
QVector4D pointLightColor[4]
QVector4D pointLightPos[4]
QVector4D spotLightDir[4]
void addUniformArray(const QByteArray &name, const QByteArray &type, quint32 size)
void addInterpolant(const QByteArray &name, const QByteArray &type)
ShaderGeneratorCommon(QSSGProgramGenerator &gen)
void addUniform(const QByteArray &name, const QByteArray &type)
void addFlatInterpolant(const QByteArray &name, const QByteArray &type)
QSSGStageGeneratorBase * vs
QSSGStageGeneratorBase * fs
void addPrefix(const QByteArray &prefix)
void addDefinition(const QByteArray &name, const QByteArray &value)