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 int samples = rhiCtx->mainPassSampleCount();
207 shaders.setUniform(ubufData, "qt_samples", &samples, sizeof(int), &cui.samples);
208 }
209
210}
211
212void QSSGParticleRenderer::updateUniformsForParticleModel(QSSGRhiShaderPipeline &shaderPipeline,
213 char *ubufData,
214 const QSSGRenderModel *model,
215 quint32 offset)
216{
217 auto &particleBuffer = *model->particleBuffer;
218 const quint32 particlesPerSlice = particleBuffer.particlesPerSlice();
219 const QVector2D oneOverSize = QVector2D(1.0f / particleBuffer.size().width(), 1.0f / particleBuffer.size().height());
220 shaderPipeline.setUniform(ubufData, "qt_oneOverParticleImageSize", &oneOverSize, 2 * sizeof(float));
221 shaderPipeline.setUniform(ubufData, "qt_countPerSlice", &particlesPerSlice, sizeof(quint32));
222 const QMatrix4x4 &particleMatrix = model->particleMatrix;
223 shaderPipeline.setUniform(ubufData, "qt_particleMatrix", &particleMatrix, 16 * sizeof(float));
224 shaderPipeline.setUniform(ubufData, "qt_particleIndexOffset", &offset, sizeof(quint32));
225}
226
227static void fillTargetBlend(QRhiGraphicsPipeline::TargetBlend &targetBlend, QSSGRenderParticles::BlendMode mode)
228{
229 switch (mode) {
230 case QSSGRenderParticles::BlendMode::Screen:
231 targetBlend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
232 targetBlend.dstColor = QRhiGraphicsPipeline::One;
233 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
234 targetBlend.dstAlpha = QRhiGraphicsPipeline::One;
235 break;
236 case QSSGRenderParticles::BlendMode::Multiply:
237 targetBlend.srcColor = QRhiGraphicsPipeline::DstColor;
238 targetBlend.dstColor = QRhiGraphicsPipeline::Zero;
239 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
240 targetBlend.dstAlpha = QRhiGraphicsPipeline::One;
241 break;
242 default:
243 // Source over as default
244 targetBlend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
245 targetBlend.dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha;
246 targetBlend.srcAlpha = QRhiGraphicsPipeline::One;
247 targetBlend.dstAlpha = QRhiGraphicsPipeline::OneMinusSrcAlpha;
248 break;
249
250 }
251}
252
253static void sortParticles(const QSSGLayerRenderData &renderData, QByteArray &result, QList<QSSGRhiSortData> &sortData,
254 const QSSGParticleBuffer &buffer, const QSSGRenderParticles &particles,
255 const QVector3D &cameraDirection, bool animatedParticles)
256{
257 const QMatrix4x4 &modelMatrix = renderData.getGlobalTransform(particles);
258 const QMatrix4x4 &invModelMatrix = modelMatrix.inverted();
259 QVector3D dir = invModelMatrix.map(cameraDirection);
260 QVector3D n = dir.normalized();
261 const auto segments = buffer.segments();
262 auto particleCount = buffer.particleCount();
263 const bool lineParticles = segments > 0;
264 if (lineParticles)
265 particleCount /= segments;
266 sortData.resize(particleCount);
267 sortData.fill({});
268
269 const auto srcParticlePointer = [](int line, int segment, int sc, int ss, int pps, const char *source) -> const QSSGLineParticle * {
270 int pi = (line * sc + segment) / pps;
271 int i = (line * sc + segment) % pps;
272 const QSSGLineParticle *sp = reinterpret_cast<const QSSGLineParticle *>(source + pi * ss);
273 return sp + i;
274 };
275
276 // create sort data
277 {
278 const auto slices = buffer.sliceCount();
279 const auto ss = buffer.sliceStride();
280 const auto pps = buffer.particlesPerSlice();
281
282 QSSGRhiSortData *dst = sortData.data();
283 const char *source = buffer.pointer();
284 const char *begin = source;
285 int i = 0;
286 if (lineParticles) {
287 for (i = 0; i < particleCount; i++) {
288 QSSGRhiSortData lineData;
289 const QSSGLineParticle *lineBegin = srcParticlePointer(i, 0, segments, ss, pps, source);
290 lineData.indexOrOffset = i;
291 lineData.d = QVector3D::dotProduct(lineBegin->position, n);
292 for (int j = 1; j < buffer.segments(); j++) {
293 const QSSGLineParticle *p = srcParticlePointer(i, j, segments, ss, pps, source);
294 lineData.d = qMin(lineData.d, QVector3D::dotProduct(p->position, n));
295 }
296 *dst++ = lineData;
297 }
298 } else if (animatedParticles) {
299 for (int s = 0; s < slices; s++) {
300 const QSSGParticleAnimated *sp = reinterpret_cast<const QSSGParticleAnimated *>(source);
301 for (int p = 0; p < pps && i < particleCount; p++) {
302 *dst = { QVector3D::dotProduct(sp->position, n), int(reinterpret_cast<const char *>(sp) - begin)};
303 sp++;
304 dst++;
305 i++;
306 }
307 source += ss;
308 }
309 } else {
310 for (int s = 0; s < slices; s++) {
311 const QSSGParticleSimple *sp = reinterpret_cast<const QSSGParticleSimple *>(source);
312 for (int p = 0; p < pps && i < particleCount; p++) {
313 *dst = { QVector3D::dotProduct(sp->position, n), int(reinterpret_cast<const char *>(sp) - begin)};
314 sp++;
315 dst++;
316 i++;
317 }
318 source += ss;
319 }
320 }
321 }
322
323 // sort
324 result.resize(buffer.bufferSize());
325 std::sort(sortData.begin(), sortData.end(), [](const QSSGRhiSortData &a, const QSSGRhiSortData &b){
326 return a.d > b.d;
327 });
328
329 auto copyParticles = [&](QByteArray &dst, const QList<QSSGRhiSortData> &data, const QSSGParticleBuffer &buffer) {
330 const auto slices = buffer.sliceCount();
331 const auto ss = buffer.sliceStride();
332 const auto pps = buffer.particlesPerSlice();
333 const QSSGRhiSortData *sdata = data.data();
334 char *dest = dst.data();
335 const char *source = buffer.pointer();
336 int i = 0;
337 if (lineParticles) {
338 int seg = 0;
339 for (int s = 0; s < slices; s++) {
340 QSSGLineParticle *dp = reinterpret_cast<QSSGLineParticle *>(dest);
341 for (int p = 0; p < pps && i < particleCount; p++) {
342 *dp = *srcParticlePointer(sdata->indexOrOffset, seg, segments, ss, pps, source);
343 dp++;
344 seg++;
345 if (seg == segments) {
346 sdata++;
347 i++;
348 seg = 0;
349 }
350 }
351 dest += ss;
352 }
353 } else if (animatedParticles) {
354 for (int s = 0; s < slices; s++) {
355 QSSGParticleAnimated *dp = reinterpret_cast<QSSGParticleAnimated *>(dest);
356 for (int p = 0; p < pps && i < particleCount; p++) {
357 *dp = *reinterpret_cast<const QSSGParticleAnimated *>(source + sdata->indexOrOffset);
358 dp++;
359 sdata++;
360 i++;
361 }
362 dest += ss;
363 }
364 } else {
365 for (int s = 0; s < slices; s++) {
366 QSSGParticleSimple *dp = reinterpret_cast<QSSGParticleSimple *>(dest);
367 for (int p = 0; p < pps && i < particleCount; p++) {
368 *dp = *reinterpret_cast<const QSSGParticleSimple *>(source + sdata->indexOrOffset);
369 dp++;
370 sdata++;
371 i++;
372 }
373 dest += ss;
374 }
375 }
376 };
377
378 // write result
379 copyParticles(result, sortData, buffer);
380}
381
382static QByteArray convertParticleData(QByteArray &dest, const QByteArray &data, bool convert)
383{
384 if (!convert)
385 return data;
386 int count = data.size() / 4;
387 if (dest.size() != count * 2)
388 dest.resize(2 * count);
389 qFloatToFloat16(reinterpret_cast<qfloat16 *>(dest.data()), reinterpret_cast<const float *>(data.constData()), count);
390 return dest;
391}
392
393void QSSGParticleRenderer::rhiPrepareRenderable(QSSGRhiShaderPipeline &shaderPipeline,
394 QSSGPassKey passKey,
395 QSSGRhiContext *rhiCtx,
396 QSSGRhiGraphicsPipelineState *ps,
397 QSSGParticlesRenderable &renderable,
398 const QSSGLayerRenderData &inData,
399 QRhiRenderPassDescriptor *renderPassDescriptor,
400 int samples,
401 int viewCount,
402 QSSGRenderCamera *alteredCamera,
403 QSSGRenderTextureCubeFace cubeFace,
404 QSSGReflectionMapEntry *entry,
405 bool oit)
406{
407 const void *node = &renderable.particles;
408 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
409
410 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
411 QSSGRhiDrawCallData &dcd = QSSGRhiContextPrivate::get(rhiCtx)->drawCallData({ passKey, node, nullptr, entry,
412 cubeFaceIdx });
413 shaderPipeline.ensureUniformBuffer(&dcd.ubuf);
414
415 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
416 if (!alteredCamera) {
417 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, inData.renderedCameras);
418 } else {
419 QSSGRenderCameraList cameras({ alteredCamera });
420 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, cameras);
421 }
422 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
423
424 QSSGRhiParticleData &particleData = QSSGRhiContextPrivate::get(rhiCtx)->particleData(&renderable.particles);
425 const QSSGParticleBuffer &particleBuffer = renderable.particles.m_particleBuffer;
426 int particleCount = particleBuffer.particleCount();
427 if (particleData.texture == nullptr || particleData.particleCount != particleCount) {
428 QSize size(particleBuffer.size());
429 if (!particleData.texture) {
430 particleData.texture = rhiCtx->rhi()->newTexture(needsConversion ? QRhiTexture::RGBA16F : QRhiTexture::RGBA32F, size);
431 particleData.texture->create();
432 } else {
433 particleData.texture->setPixelSize(size);
434 particleData.texture->create();
435 }
436 particleData.particleCount = particleCount;
437 }
438
439 bool sortingChanged = particleData.sorting != renderable.particles.m_depthSorting;
440 if (sortingChanged && !renderable.particles.m_depthSorting) {
441 particleData.sortData.clear();
442 particleData.sortedData.clear();
443 }
444 particleData.sorting = renderable.particles.m_depthSorting;
445
446 QByteArray uploadData;
447
448 if (renderable.particles.m_depthSorting) {
449 bool animatedParticles = renderable.particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Animated;
450 if (!alteredCamera) {
451 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, inData.renderedCameraData.value()[0].direction, animatedParticles);
452 } else {
453 const QMatrix4x4 globalTransform = inData.getGlobalTransform(*alteredCamera);
454 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, QSSGRenderNode::getScalingCorrectDirection(globalTransform), animatedParticles);
455 }
456 uploadData = convertParticleData(particleData.convertData, particleData.sortedData, needsConversion);
457 } else {
458 uploadData = convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion);
459 }
460
461 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
462 QRhiTextureSubresourceUploadDescription upload;
463 upload.setData(uploadData);
464 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, upload));
465 rub->uploadTexture(particleData.texture, uploadDesc);
466 rhiCtx->commandBuffer()->resourceUpdate(rub);
467
468 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
469 ia.topology = QRhiGraphicsPipeline::TriangleStrip;
470 ia.inputLayout = QRhiVertexInputLayout();
471 ia.inputs.clear();
472
473 ps->samples = samples;
474 ps->viewCount = viewCount;
475 ps->cullMode = QRhiGraphicsPipeline::None;
476
477 if (inData.orderIndependentTransparencyEnabled == false) {
478 if (renderable.renderableFlags.hasTransparency())
479 fillTargetBlend(ps->targetBlend[0], renderable.particles.m_blendMode);
480 else
481 ps->targetBlend[0] = QRhiGraphicsPipeline::TargetBlend();
482 }
483
484 QSSGRhiShaderResourceBindingList bindings;
485 bindings.addUniformBuffer(0, VISIBILITY_ALL, dcd.ubuf, 0, shaderPipeline.ub0Size());
486
487 // Texture maps
488 // we only have one image
489 QSSGRenderableImage *renderableImage = renderable.firstImage;
490
491 int samplerBinding = shaderPipeline.bindingForTexture("qt_sprite");
492 if (samplerBinding >= 0) {
493 QRhiTexture *texture = renderableImage ? renderableImage->m_texture.m_texture : nullptr;
494 if (samplerBinding >= 0 && texture) {
495 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
496 QRhiSampler *sampler = rhiCtx->sampler({ QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
497 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
498 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
499 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
500 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
501 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
502 });
503 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
504 } else {
505 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
506 QRhiTexture *texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
507 rhiCtx->commandBuffer()->resourceUpdate(rub);
508 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
509 QRhiSampler::Nearest,
510 QRhiSampler::None,
511 QRhiSampler::ClampToEdge,
512 QRhiSampler::ClampToEdge,
513 QRhiSampler::Repeat
514 });
515 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
516 }
517 }
518
519 samplerBinding = shaderPipeline.bindingForTexture("qt_particleTexture");
520 if (samplerBinding >= 0) {
521 QRhiTexture *texture = particleData.texture;
522 if (samplerBinding >= 0 && texture) {
523 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
524 QRhiSampler::Nearest,
525 QRhiSampler::None,
526 QRhiSampler::ClampToEdge,
527 QRhiSampler::ClampToEdge,
528 QRhiSampler::Repeat
529 });
530 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
531 }
532 }
533
534 samplerBinding = shaderPipeline.bindingForTexture("qt_colorTable");
535 if (samplerBinding >= 0) {
536 bool hasTexture = false;
537 if (renderable.colorTable) {
538 QRhiTexture *texture = renderable.colorTable->m_texture.m_texture;
539 if (texture) {
540 hasTexture = true;
541 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
542 QRhiSampler::Nearest,
543 QRhiSampler::None,
544 QRhiSampler::ClampToEdge,
545 QRhiSampler::ClampToEdge,
546 QRhiSampler::Repeat
547 });
548 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
549 }
550 }
551
552 if (!hasTexture) {
553 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
554 QRhiTexture *texture = rhiCtx->dummyTexture({}, rub, QSize(4, 4), Qt::white);
555 rhiCtx->commandBuffer()->resourceUpdate(rub);
556 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
557 QRhiSampler::Nearest,
558 QRhiSampler::None,
559 QRhiSampler::ClampToEdge,
560 QRhiSampler::ClampToEdge,
561 QRhiSampler::Repeat
562 });
563 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
564 }
565 }
566
567 if (oit && inData.layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
568 RenderHelpers::addAccumulatorImageBindings(&shaderPipeline, bindings);
569
570 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
571
572 // TODO: This is identical to other renderables. Make into a function?
573 QRhiShaderResourceBindings *&srb = dcd.srb;
574 bool srbChanged = false;
575 if (!srb || bindings != dcd.bindings) {
576 srb = rhiCtxD->srb(bindings);
577 rhiCtxD->releaseCachedSrb(dcd.bindings);
578 dcd.bindings = bindings;
579 srbChanged = true;
580 }
581
582 if (cubeFace == QSSGRenderTextureCubeFaceNone)
583 renderable.rhiRenderData.mainPass.srb = srb;
584 else
585 renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx] = srb;
586
587 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
588 if (dcd.pipeline
589 && !srbChanged
590 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash
591 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
592 && dcd.ps == *ps)
593 {
594 if (cubeFace == QSSGRenderTextureCubeFaceNone)
595 renderable.rhiRenderData.mainPass.pipeline = dcd.pipeline;
596 else
597 renderable.rhiRenderData.reflectionPass.pipeline = dcd.pipeline;
598 } else {
599 if (cubeFace == QSSGRenderTextureCubeFaceNone) {
600 renderable.rhiRenderData.mainPass.pipeline = rhiCtxD->pipeline(pipelineKey,
601 renderPassDescriptor,
602 srb);
603 dcd.pipeline = renderable.rhiRenderData.mainPass.pipeline;
604 } else {
605 renderable.rhiRenderData.reflectionPass.pipeline = rhiCtxD->pipeline(pipelineKey,
606 renderPassDescriptor,
607 srb);
608 dcd.pipeline = renderable.rhiRenderData.reflectionPass.pipeline;
609 }
610 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
611 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
612 dcd.ps = *ps;
613 }
614}
615
616void QSSGParticleRenderer::prepareParticlesForModel(QSSGRhiShaderPipeline &shaderPipeline,
617 QSSGRhiContext *rhiCtx,
618 QSSGRhiShaderResourceBindingList &bindings,
619 const QSSGRenderModel *model)
620{
621 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
622 QSSGRhiParticleData &particleData = rhiCtxD->particleData(model);
623 const QSSGParticleBuffer &particleBuffer = *model->particleBuffer;
624 int particleCount = particleBuffer.particleCount();
625 bool update = particleBuffer.serial() != particleData.serial;
626 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
627 if (particleData.texture == nullptr || particleData.particleCount != particleCount) {
628 QSize size(particleBuffer.size());
629 if (!particleData.texture) {
630 particleData.texture = rhiCtx->rhi()->newTexture(needsConversion ? QRhiTexture::RGBA16F : QRhiTexture::RGBA32F, size);
631 particleData.texture->create();
632 } else {
633 particleData.texture->setPixelSize(size);
634 particleData.texture->create();
635 }
636 particleData.particleCount = particleCount;
637 update = true;
638 }
639
640 if (update) {
641 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
642 QRhiTextureSubresourceUploadDescription upload;
643 upload.setData(convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion));
644 QRhiTextureUploadDescription uploadDesc(QRhiTextureUploadEntry(0, 0, upload));
645 rub->uploadTexture(particleData.texture, uploadDesc);
646 rhiCtx->commandBuffer()->resourceUpdate(rub);
647 }
648 particleData.serial = particleBuffer.serial();
649 int samplerBinding = shaderPipeline.bindingForTexture("qt_particleTexture");
650 if (samplerBinding >= 0) {
651 QRhiTexture *texture = particleData.texture;
652 if (samplerBinding >= 0 && texture) {
653 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
654 QRhiSampler::Nearest,
655 QRhiSampler::None,
656 QRhiSampler::ClampToEdge,
657 QRhiSampler::ClampToEdge,
658 QRhiSampler::Repeat
659 });
660 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
661 }
662 }
663}
664
665static QByteArray particlesLogPrefix() { return QByteArrayLiteral("particle material pipeline-- "); }
666
668{
676 void addUniform(const QByteArray &name, const QByteArray &type)
677 {
678 vs->addUniform(name, type);
679 fs->addUniform(name, type);
680 }
681 void addUniformArray(const QByteArray &name, const QByteArray &type, quint32 size)
682 {
683 vs->addUniformArray(name, type, size);
684 fs->addUniformArray(name, type, size);
685 }
686 void addDefinition(const QByteArray &name, const QByteArray &value)
687 {
688 vs->addDefinition(name, value);
689 fs->addDefinition(name, value);
690 }
691 void addInterpolant(const QByteArray &name, const QByteArray &type)
692 {
693 vs->addOutgoing(name, type);
694 fs->addIncoming(name, type);
695 }
696 void addFlatInterpolant(const QByteArray &name, const QByteArray &type)
697 {
698 vs->addFlatOutgoing(name, type);
699 fs->addFlatIncoming(name, type);
700 }
701 void addPrefix(const QByteArray &prefix)
702 {
703 vs->addPrefix(prefix);
704 fs->addPrefix(prefix);
705 }
706};
707
709{
711 int indent = 0;
712 AutoFormatGenerator(QSSGStageGeneratorBase &g)
713 : gen(g)
714 {
715
716 }
717 AutoFormatGenerator &operator<<(const QByteArray &data)
718 {
719 for (int i = 0; i < indent; i++)
720 gen << " ";
721 gen << data << "\n";
722 return *this;
723 }
725 {
726 indent++;
727 }
729 {
730 indent--;
731 Q_ASSERT(indent >= 0);
732 }
733};
734
735static const char *s_lightPrefix = {
736 "struct ParticleLightData\n"
737 "{\n"
738 " vec4 qt_pointLightPosition[4];\n"
739 " vec4 qt_pointLightConstantAtt;\n"
740 " vec4 qt_pointLightLinearAtt;\n"
741 " vec4 qt_pointLightQuadAtt;\n"
742 " vec4 qt_pointLightColor[4];\n"
743 " vec4 qt_spotLightPosition[4];\n"
744 " vec4 qt_spotLightConstantAtt;\n"
745 " vec4 qt_spotLightLinearAtt;\n"
746 " vec4 qt_spotLightQuadAtt;\n"
747 " vec4 qt_spotLightColor[4];\n"
748 " vec4 qt_spotLightDirection[4];\n"
749 " vec4 qt_spotLightConeAngle;\n"
750 " vec4 qt_spotLightInnerConeAngle;\n"
751 "};\n"
752};
753
754QSSGShaderFeatures QSSGParticleRenderer::particleShaderFeatures(const QSSGShaderFeatures& features)
755{
756#define COPY_FEATURE(f) ret.set(f, features.isSet(f));
757 QSSGShaderFeatures ret;
758 COPY_FEATURE(QSSGShaderFeatures::Feature::LinearTonemapping);
759 COPY_FEATURE(QSSGShaderFeatures::Feature::AcesTonemapping);
760 COPY_FEATURE(QSSGShaderFeatures::Feature::HejlDawsonTonemapping);
761 COPY_FEATURE(QSSGShaderFeatures::Feature::FilmicTonemapping);
762 COPY_FEATURE(QSSGShaderFeatures::Feature::DisableMultiView);
763#undef COPY_FEATURE
764 return ret;
765}
766
767QSSGRhiShaderPipelinePtr QSSGParticleRenderer::generateRhiShaderPipeline(QSSGRenderer &renderer,
768 QSSGParticlesRenderable &inRenderable,
769 const QSSGShaderFeatures &inFeatureSet,
770 QByteArray &shaderString,
771 const QSSGShaderParticleMaterialKeyProperties &shaderKeyProperties)
772{
773 const auto &m_contextInterface = renderer.m_contextInterface;
774 const auto &shaderCache = m_contextInterface->shaderCache();
775 const auto &shaderProgramGenerator = m_contextInterface->shaderProgramGenerator();
776 const auto &shaderLibraryManager = m_contextInterface->shaderLibraryManager();
777
778 shaderString = particlesLogPrefix();
779 QSSGShaderParticleMaterialKey theKey(inRenderable.shaderDescription);
780
781 theKey.toString(shaderString, shaderKeyProperties);
782
783 if (s_shaderCacheEnabled) {
784 if (const auto &maybePipeline = shaderCache->tryGetRhiShaderPipeline(shaderString, inFeatureSet))
785 return maybePipeline;
786
787 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(shaderString, QQsbCollection::toFeatureSet(inFeatureSet));
788 // Check if there's a pre-built (offline generated) shader for available.
789 if (renderer.m_currentLayer) {
790 QQsbCollection::EntryMap &pregenEntries = renderer.m_currentLayer->m_particleShaderEntries;
791 if (pregenEntries.isEmpty()) {
792 renderer.m_currentLayer->m_particleShaderEntries = shaderLibraryManager->getParticleShaderEntries();
793 pregenEntries = renderer.m_currentLayer->m_particleShaderEntries;
794 }
795 if (!pregenEntries.isEmpty()) {
796 const auto foundIt = pregenEntries.constFind(QQsbCollection::Entry(qsbcKey));
797 if (foundIt != pregenEntries.cend())
798 return shaderCache->newPipelineFromPregenerated(shaderString, inFeatureSet, *foundIt, inRenderable.particles);
799 }
800 }
801
802 // Try the persistent (disk-based) cache then.
803 if (const auto &maybePipeline = shaderCache->tryNewPipelineFromPersistentCache(qsbcKey, shaderString, inFeatureSet))
804 return maybePipeline;
805 }
806
807 // generate shader code
808 shaderProgramGenerator->beginProgram();
809 auto &vertex = *shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Vertex);
810 auto &fragment = *shaderProgramGenerator->getStage(QSSGShaderGeneratorStage::Fragment);
811 ShaderGeneratorCommon common(*shaderProgramGenerator);
812 const bool isSpriteLinear = shaderKeyProperties.m_isSpriteLinear.getValue(theKey);
813 const bool isColorTableLinear = shaderKeyProperties.m_isColorTableLinear.getValue(theKey);
814 const bool lighting = shaderKeyProperties.m_hasLighting.getValue(theKey);
815 const bool isMapped = shaderKeyProperties.m_isMapped.getValue(theKey);
816 const bool isLineParticle = shaderKeyProperties.m_isLineParticle.getValue(theKey);
817 const bool isAnimated = shaderKeyProperties.m_isAnimated.getValue(theKey);
818 const int viewCount = inFeatureSet.isSet(QSSGShaderFeatures::Feature::DisableMultiView)
819 ? 1 : shaderKeyProperties.m_viewCount.getValue(theKey);
820 const int oit = shaderKeyProperties.m_orderIndependentTransparency.getValue(theKey);
821 const bool oitMSAA = shaderKeyProperties.m_oitMSAA.getValue(theKey);
822
823 if (isAnimated)
824 common.addDefinition("QSSG_PARTICLES_ENABLE_ANIMATED", "1");
825 if (isLineParticle)
826 common.addDefinition("QSSG_PARTICLES_ENABLE_LINE_PARTICLE", "1");
827 if (oit)
828 common.addDefinition("QSSG_OIT_METHOD", QStringLiteral("%1").arg(oit).toUtf8());
829 if (oitMSAA)
830 common.addDefinition("QSSG_MULTISAMPLE", "1");
831
832 common.addUniform("qt_modelMatrix", "mat4");
833 if (viewCount >= 2) {
834 common.addUniformArray("qt_viewMatrix", "mat4", viewCount);
835 common.addUniformArray("qt_projectionMatrix", "mat4", viewCount);
836 } else {
837 common.addUniform("qt_viewMatrix", "mat4");
838 common.addUniform("qt_projectionMatrix", "mat4");
839 }
840 if (lighting) {
841 common.addPrefix(s_lightPrefix);
842 common.addUniform("lightData", "ParticleLightData");
843 }
844 common.addUniform("qt_spriteConfig", "vec4");
845 common.addUniform("qt_light_ambient_total", "vec3");
846 common.addUniform("qt_oneOverParticleImageSize", "vec2");
847 common.addUniform("qt_countPerSlice", "uint");
848 if (isLineParticle)
849 common.addUniform("qt_lineSegmentCount", "uint");
850 common.addUniform("qt_billboard", "float");
851 common.addUniform("qt_opacity", "float");
852 if (isLineParticle) {
853 common.addUniform("qt_alphaFade", "float");
854 common.addUniform("qt_sizeModifier", "float");
855 common.addUniform("qt_texcoordScale", "float");
856 }
857 if (lighting) {
858 common.addUniform("qt_pointLights", "bool");
859 common.addUniform("qt_spotLights", "bool");
860 }
861 if (oit == (int)QSSGRenderLayer::OITMethod::WeightedBlended) {
862 common.addUniform("qt_cameraProperties", "vec2");
863 } else if (oit == (int)QSSGRenderLayer::OITMethod::LinkedList) {
864 common.addUniform("qt_viewSize", "ivec2");
865 common.addUniform("qt_ABufImageWidth", "uint");
866 common.addUniform("qt_listNodeCount", "uint");
867#ifdef QSSG_OIT_USE_BUFFERS
868 common.addUniform("qt_samples", "uint");
869#endif
870 }
871
872 if (lighting)
873 vertex.addInclude("particleLighting.glsllib");
874
875 vertex.addUniform("qt_particleTexture", "sampler2D");
876
877 vertex.addInclude("particleLoading.glsllib");
878
879 common.addInterpolant("color", "vec4");
880 common.addInterpolant("spriteData", "vec2");
881 common.addInterpolant("texcoord", "vec2");
882 common.addFlatInterpolant("instanceIndex", "uint");
883 if (oit == (int)QSSGRenderLayer::OITMethod::LinkedList && viewCount >= 2)
884 common.addFlatInterpolant("v_viewIndex", "uint");
885
886 AutoFormatGenerator vg(vertex);
887 if (!isLineParticle)
888 vg << "const vec2 corners[4] = {{0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {1.0, 1.0}};";
889
890 // vertex shader main
891 vg << "out gl_PerVertex {"
892 << " vec4 gl_Position;"
893 << "};";
894
895 vg << "void main() {";
896 vg.incIndent();
897 if (isLineParticle) {
898 vg << "uint segmentIndex = gl_VertexIndex / 2;"
899 << "uint particleIndex = segmentIndex + gl_InstanceIndex * qt_lineSegmentCount;";
900 } else {
901 vg << "uint particleIndex = gl_InstanceIndex;"
902 << "uint cornerIndex = gl_VertexIndex;"
903 << "vec2 corner = corners[cornerIndex];";
904 }
905 vg << "instanceIndex = particleIndex;"
906 << "Particle p = qt_loadParticle(particleIndex);";
907
908 if (isLineParticle) {
909 vg << "float side = float(mod(gl_VertexIndex, 2)) - 0.5;"
910 << "float size = p.size * qt_calcSizeFactor(segmentIndex);"
911 << "vec3 o = p.binormal * side * size;"
912 << "vec4 worldPos = qt_modelMatrix * vec4(p.position + (1.0 - qt_billboard) * o, 1.0);";
913 if (viewCount >= 2) {
914 vg << "vec4 viewPos = qt_viewMatrix[gl_ViewIndex] * worldPos;"
915 << "vec3 viewBN = (transpose(inverse(qt_viewMatrix[gl_ViewIndex] * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
916 } else {
917 vg << "vec4 viewPos = qt_viewMatrix * worldPos;"
918 << "vec3 viewBN = (transpose(inverse(qt_viewMatrix * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
919 }
920 vg << "viewBN.z = 0;"
921 << "viewBN = normalize(viewBN) * side * size;"
922 << "viewPos = viewPos + vec4(viewBN, 0.0) * qt_billboard;"
923 << "texcoord.x = p.segmentLength * qt_texcoordScale;"
924 << "texcoord.y = float(mod(gl_VertexIndex, 2));"
925 << "color = p.color;"
926 << "color.a *= qt_opacity * qt_calcAlphaFade(segmentIndex);";
927 } else {
928 vg << "mat3 rotMat = qt_fromEulerRotation(p.rotation);"
929 << "vec4 worldPos = qt_modelMatrix * vec4(p.position, 1.0);"
930 << "vec4 viewPos = worldPos;"
931 << "vec3 offset = (p.size * vec3(corner - vec2(0.5), 0.0));"
932 << "viewPos.xyz += offset * rotMat * (1.0 - qt_billboard);";
933 if (viewCount >= 2)
934 vg << "viewPos = qt_viewMatrix[gl_ViewIndex] * viewPos;";
935 else
936 vg << "viewPos = qt_viewMatrix * viewPos;";
937 vg << "viewPos.xyz += rotMat * offset * qt_billboard;"
938 << "texcoord = corner;"
939 << "color = p.color;"
940 << "color.a *= qt_opacity;";
941 }
942 if (lighting)
943 vg << "color.rgb *= qt_calcLightColor(worldPos.xyz);";
944 if (viewCount >= 2) {
945 if (oit == int(QSSGRenderLayer::OITMethod::LinkedList))
946 vg << "v_viewIndex = gl_ViewIndex;";
947 vg << "gl_Position = qt_projectionMatrix[gl_ViewIndex] * viewPos;";
948 } else {
949 vg << "gl_Position = qt_projectionMatrix * viewPos;";
950 }
951 if (isMapped)
952 vg << "spriteData.x = qt_ageToSpriteFactor(p.age);";
953 if (isAnimated)
954 vg << "spriteData.y = p.animationFrame;";
955 vg.decIndent();
956 vg << "}";
957
958 // fragment shader main
959 fragment.addInclude("tonemapping.glsllib");
960 fragment.addInclude("particleSprite.glsllib");
961 fragment.addUniform("qt_sprite", "sampler2D");
962
963 AutoFormatGenerator fg(fragment);
964
965 if (oit == int(QSSGRenderLayer::OITMethod::WeightedBlended)) {
966 fragment.addInclude("oitweightedblended.glsllib");
967 fg << "layout(location = 1) out vec4 revealageOutput;";
968 } else if (oit == int(QSSGRenderLayer::OITMethod::LinkedList)) {
969#ifdef QSSG_OIT_USE_BUFFERS
970 fragment.addInclude("oitlinkedlist_buf.glsllib");
971 QSSGShaderResourceMergeContext::setAdditionalBufferAmount(3);
972#else
973 fragment.addInclude("oitlinkedlist.glsllib");
974#endif
975 }
976 if (isSpriteLinear)
977 fg << "#define spriteFunc";
978 else
979 fg << "#define spriteFunc qt_sRGBToLinear";
980 if (isMapped) {
981 fragment.addUniform("qt_colorTable", "sampler2D");
982 if (isColorTableLinear)
983 fg << "#define colorTableFunc";
984 else
985 fg << "#define colorTableFunc qt_sRGBToLinear";
986 }
987
988 fg << "vec4 qt_readSprite() {";
989 fg.incIndent();
990 if (isAnimated) {
991 fg << "vec2 coords[2];"
992 << "float factor = qt_spriteCoords(coords);"
993 << "return mix(spriteFunc(texture(qt_sprite, coords[0])), spriteFunc(texture(qt_sprite, coords[1])), factor);";
994 } else {
995 fg << "return spriteFunc(texture(qt_sprite, texcoord));";
996 }
997 fg.decIndent();
998 fg << "}";
999 fg << "vec4 qt_readColor() {";
1000 fg.incIndent();
1001 if (isMapped)
1002 fg << "return color * colorTableFunc(texture(qt_colorTable, vec2(spriteData.x, qt_rand(vec2(instanceIndex, 0)))));";
1003 else
1004 fg << "return color;";
1005 fg.decIndent();
1006 fg << "}";
1007 fg << "void main() {";
1008 fg.incIndent();
1009 fg << "vec4 ret = qt_readColor() * qt_readSprite();";
1010 if (oit) {
1011 if (oit == int(QSSGRenderLayer::OITMethod::WeightedBlended)) {
1012 fg << "float z = abs(gl_FragCoord.z);"
1013 << "float distWeight = qt_transparencyWeight(z, ret.a, qt_cameraProperties.y);"
1014 << "fragOutput = distWeight * qt_tonemap(ret);"
1015 << "revealageOutput = vec4(ret.a);";
1016 } else if (oit == int(QSSGRenderLayer::OITMethod::LinkedList)) {
1017#ifdef QSSG_OIT_USE_BUFFERS
1018 if (viewCount >= 2)
1019 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex, qt_samples);";
1020 else
1021 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0, qt_samples);";
1022#else
1023 if (viewCount >= 2)
1024 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex);";
1025 else
1026 fg << "fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0);";
1027#endif
1028 }
1029 } else {
1030 fg << "fragOutput = qt_tonemap(ret);";
1031 }
1032 fg.decIndent();
1033 fg << "}";
1034
1035
1036 return shaderProgramGenerator->compileGeneratedRhiShader(shaderString,
1037 inFeatureSet,
1038 *shaderLibraryManager,
1039 *shaderCache,
1040 QSSGRhiShaderPipeline::UsedWithoutIa,
1041 {},
1042 shaderKeyProperties.m_viewCount.getValue(inRenderable.shaderDescription),
1043 false);
1044}
1045
1046QSSGRhiShaderPipelinePtr QSSGParticleRenderer::getShaderPipelineParticles(QSSGRenderer &renderer,
1047 QSSGParticlesRenderable &inRenderable,
1048 const QSSGShaderFeatures &inFeatureSet)
1049{
1050 const auto features = particleShaderFeatures(inFeatureSet);
1051 auto *m_currentLayer = renderer.m_currentLayer;
1052 QSSG_ASSERT(m_currentLayer != nullptr, return {});
1053
1054 auto &shaderMap = m_currentLayer->particleShaderMap;
1055
1056 QElapsedTimer timer;
1057 timer.start();
1058
1059 QSSGRhiShaderPipelinePtr shaderPipeline;
1060
1061 // This just references inFeatureSet and inRenderable.shaderDescription -
1062 // cheap to construct and is good enough for the find()
1063 QSSGParticleShaderMapKey skey = QSSGParticleShaderMapKey(QByteArray(),
1064 features,
1065 inRenderable.shaderDescription);
1066 auto it = shaderMap.find(skey);
1067 if (it == shaderMap.end()) {
1068 Q_TRACE_SCOPE(QSSG_generateShader);
1069 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DGenerateShader);
1070 auto &shaderString = renderer.m_currentLayer->generatedShaderString;
1071 shaderPipeline = QSSGParticleRenderer::generateRhiShaderPipeline(renderer, inRenderable, features, shaderString, m_currentLayer->particleMaterialShaderKeyProperties);
1072 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DGenerateShader, 0, inRenderable.particles.profilingId);
1073 // make skey useable as a key for the QHash (makes a copy of the materialKey, instead of just referencing)
1074 skey.detach();
1075 // insert it no matter what, no point in trying over and over again
1076 shaderMap.insert(skey, shaderPipeline);
1077 } else {
1078 shaderPipeline = it.value();
1079 }
1080
1081 if (shaderPipeline != nullptr) {
1082 if (m_currentLayer && !m_currentLayer->renderedCameras.isEmpty())
1083 m_currentLayer->ensureCachedCameraDatas();
1084 }
1085
1086 const auto &rhiContext = renderer.m_contextInterface->rhiContext();
1087 QSSGRhiContextStats::get(*rhiContext).registerMaterialShaderGenerationTime(timer.elapsed());
1088
1089 return shaderPipeline;
1090}
1091
1092void QSSGParticleRenderer::rhiRenderRenderable(QSSGRhiContext *rhiCtx,
1093 QSSGParticlesRenderable &renderable,
1094 bool *needsSetViewport,
1095 QSSGRenderTextureCubeFace cubeFace,
1096 const QSSGRhiGraphicsPipelineState &state)
1097{
1098 QRhiGraphicsPipeline *ps = renderable.rhiRenderData.mainPass.pipeline;
1099 QRhiShaderResourceBindings *srb = renderable.rhiRenderData.mainPass.srb;
1100
1101 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1102 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
1103 ps = renderable.rhiRenderData.reflectionPass.pipeline;
1104 srb = renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx];
1105 }
1106
1107 if (!ps || !srb)
1108 return;
1109
1110 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
1111
1112 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1113 // QRhi optimizes out unnecessary binding of the same pipline
1114 cb->setGraphicsPipeline(ps);
1115 cb->setVertexInput(0, 0, nullptr);
1116 cb->setShaderResources(srb);
1117
1118 if (needsSetViewport && *needsSetViewport) {
1119 cb->setViewport(state.viewport);
1120 *needsSetViewport = false;
1121 }
1122 if (renderable.particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line) {
1123 // draw triangle strip with 2 * segmentCount vertices N times
1124 int S = renderable.particles.m_particleBuffer.segments();
1125 int N = renderable.particles.m_particleBuffer.particleCount() / S;
1126 cb->draw(2 * S, N);
1127 QSSGRHICTX_STAT(rhiCtx, draw(2 * S, N));
1128 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (2 * S | quint64(N) << 32), renderable.particles.profilingId);
1129 } else {
1130 // draw triangle strip with 2 triangles N times
1131 cb->draw(4, renderable.particles.m_particleBuffer.particleCount());
1132 QSSGRHICTX_STAT(rhiCtx, draw(4, renderable.particles.m_particleBuffer.particleCount()));
1133 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (4 | quint64(renderable.particles.m_particleBuffer.particleCount()) << 32), renderable.particles.profilingId);
1134 }
1135}
1136
1137QT_END_NAMESPACE
\keyword 16-bit Floating Point Support\inmodule QtCore \inheaderfile QFloat16
Definition qfloat16.h:57
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)