52void QSSGParticleRenderer::updateUniformsForParticles(
const QSSGLayerRenderData &inData,
53 QSSGRhiShaderPipeline &shaders,
54 QSSGRhiContext *rhiCtx,
56 QSSGParticlesRenderable &renderable,
57 const QSSGRenderCameraList &cameras)
59 const QMatrix4x4 clipSpaceCorrMatrix = rhiCtx->rhi()->clipSpaceCorrMatrix();
61 QSSGRhiShaderPipeline::CommonUniformIndices &cui = shaders.commonUniformIndices;
63 const int viewCount = cameras.count();
66 QMatrix4x4 camGlobalTransforms[2] { QMatrix4x4{Qt::Uninitialized}, QMatrix4x4{Qt::Uninitialized} };
68 camGlobalTransforms[0] = inData.getGlobalTransform(*cameras[0]);
70 for (size_t viewIndex = 0; viewIndex != std::size(camGlobalTransforms); ++viewIndex)
71 camGlobalTransforms[viewIndex] = inData.getGlobalTransform(*cameras[viewIndex]);
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);
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();
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);
90 const QMatrix4x4 &modelMatrix = renderable.globalTransform;
91 shaders.setUniform(ubufData,
"qt_modelMatrix", modelMatrix.constData(), 16 *
sizeof(
float), &cui.modelMatrixIdx);
93 const QVector2D camProperties(cameras[0]->clipPlanes);
94 shaders.setUniform(ubufData,
"qt_cameraProperties", &camProperties, 2 *
sizeof(
float), &cui.cameraPropertiesIdx);
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));
104 shaders.setUniform(ubufData,
"qt_opacity", &renderable.opacity, 1 *
sizeof(
float));
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;
110 QVector4D spriteConfig(imageCount, ooImageCount, 0.0f, blendImages);
111 shaders.setUniform(ubufData,
"qt_spriteConfig", &spriteConfig, 4 *
sizeof(
float));
113 const float billboard = renderable.particles.m_billboard ? 1.0f : 0.0f;
114 shaders.setUniform(ubufData,
"qt_billboard", &billboard, 1 *
sizeof(
float));
117 QVector3D theLightAmbientTotal;
118 bool hasLights = !renderable.particles.m_lights.isEmpty();
122 ParticleLightData lightData;
123 auto &lights = renderable.lights;
124 for (quint32 lightIdx = 0, lightEnd = lights.size();
126 QSSGRenderLight *theLight(lights[lightIdx].light);
128 if (!renderable.particles.m_lights.contains(theLight))
131 const QMatrix4x4 lightGlobalTransform = inData.getGlobalTransform(*theLight);
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);
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;
151 float innerConeAngle = std::min(theLight->m_innerConeAngle, coneAngle - 0.01f);
152 lightData.spotLightConeAngle[spotLight] = qDegreesToRadians(coneAngle);
153 lightData.spotLightInnerConeAngle[spotLight] = qDegreesToRadians(innerConeAngle);
156 theLightAmbientTotal += theLight->m_ambientColor;
159 int lightOffset = shaders.offsetOfUniform(
"lightData");
160 if (lightOffset >= 0)
161 memcpy(ubufData + lightOffset, &lightData,
sizeof(ParticleLightData));
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));
170 int segmentCount = particleBuffer.segments();
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());
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));
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) {
192 int listNodeCount = inData.layer.oitNodeCount;
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);
199 int abufWidth = RenderHelpers::rhiCalculateABufferSize(inData.layer.oitNodeCount);
200 int listNodeCount = abufWidth * abufWidth;
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);
254 const QSSGParticleBuffer &buffer,
const QSSGRenderParticles &particles,
255 const QVector3D &cameraDirection,
bool animatedParticles)
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;
265 particleCount /= segments;
266 sortData.resize(particleCount);
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);
278 const auto slices = buffer.sliceCount();
279 const auto ss = buffer.sliceStride();
280 const auto pps = buffer.particlesPerSlice();
283 const char *source = buffer.pointer();
284 const char *begin = source;
287 for (i = 0; i < particleCount; i++) {
289 const QSSGLineParticle *lineBegin = srcParticlePointer(i, 0, segments, ss, pps, source);
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));
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)};
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)};
324 result.resize(buffer.bufferSize());
325 std::sort(sortData.begin(), sortData.end(), [](
const QSSGRhiSortData &a,
const QSSGRhiSortData &b){
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();
334 char *dest = dst.data();
335 const char *source = buffer.pointer();
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);
345 if (seg == segments) {
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);
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);
379 copyParticles(result, sortData, buffer);
393void QSSGParticleRenderer::rhiPrepareRenderable(QSSGRhiShaderPipeline &shaderPipeline,
395 QSSGRhiContext *rhiCtx,
396 QSSGRhiGraphicsPipelineState *ps,
397 QSSGParticlesRenderable &renderable,
398 const QSSGLayerRenderData &inData,
399 QRhiRenderPassDescriptor *renderPassDescriptor,
402 QSSGRenderCamera *alteredCamera,
403 QSSGRenderTextureCubeFace cubeFace,
404 QSSGReflectionMapEntry *entry,
407 const void *node = &renderable.particles;
408 const bool needsConversion = !rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32F);
410 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
411 QSSGRhiDrawCallData &dcd = QSSGRhiContextPrivate::get(rhiCtx)->drawCallData({ passKey, node,
nullptr, entry,
413 shaderPipeline.ensureUniformBuffer(&dcd.ubuf);
415 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
416 if (!alteredCamera) {
417 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, inData.renderedCameras);
419 QSSGRenderCameraList cameras({ alteredCamera });
420 updateUniformsForParticles(inData, shaderPipeline, rhiCtx, ubufData, renderable, cameras);
422 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
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();
433 particleData.texture->setPixelSize(size);
434 particleData.texture->create();
436 particleData.particleCount = particleCount;
439 bool sortingChanged = particleData.sorting != renderable.particles.m_depthSorting;
440 if (sortingChanged && !renderable.particles.m_depthSorting) {
441 particleData.sortData.clear();
442 particleData.sortedData.clear();
444 particleData.sorting = renderable.particles.m_depthSorting;
446 QByteArray uploadData;
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);
453 const QMatrix4x4 globalTransform = inData.getGlobalTransform(*alteredCamera);
454 sortParticles(inData, particleData.sortedData, particleData.sortData, particleBuffer, renderable.particles, QSSGRenderNode::getScalingCorrectDirection(globalTransform), animatedParticles);
456 uploadData = convertParticleData(particleData.convertData, particleData.sortedData, needsConversion);
458 uploadData = convertParticleData(particleData.convertData, particleBuffer.data(), needsConversion);
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);
468 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
469 ia.topology = QRhiGraphicsPipeline::TriangleStrip;
470 ia.inputLayout = QRhiVertexInputLayout();
473 ps->samples = samples;
474 ps->viewCount = viewCount;
475 ps->cullMode = QRhiGraphicsPipeline::None;
477 if (inData.orderIndependentTransparencyEnabled ==
false) {
478 if (renderable.renderableFlags.hasTransparency())
479 fillTargetBlend(ps->targetBlend[0], renderable.particles.m_blendMode);
481 ps->targetBlend[0] = QRhiGraphicsPipeline::TargetBlend();
484 QSSGRhiShaderResourceBindingList bindings;
485 bindings.addUniformBuffer(0, VISIBILITY_ALL, dcd.ubuf, 0, shaderPipeline.ub0Size());
489 QSSGRenderableImage *renderableImage = renderable.firstImage;
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)
503 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
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,
511 QRhiSampler::ClampToEdge,
512 QRhiSampler::ClampToEdge,
515 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
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,
526 QRhiSampler::ClampToEdge,
527 QRhiSampler::ClampToEdge,
530 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
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;
541 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest,
542 QRhiSampler::Nearest,
544 QRhiSampler::ClampToEdge,
545 QRhiSampler::ClampToEdge,
548 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
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,
559 QRhiSampler::ClampToEdge,
560 QRhiSampler::ClampToEdge,
563 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
567 if (oit && inData.layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
568 RenderHelpers::addAccumulatorImageBindings(&shaderPipeline, bindings);
570 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
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;
582 if (cubeFace == QSSGRenderTextureCubeFaceNone)
583 renderable.rhiRenderData.mainPass.srb = srb;
585 renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx] = srb;
587 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
590 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash
591 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
594 if (cubeFace == QSSGRenderTextureCubeFaceNone)
595 renderable.rhiRenderData.mainPass.pipeline = dcd.pipeline;
597 renderable.rhiRenderData.reflectionPass.pipeline = dcd.pipeline;
599 if (cubeFace == QSSGRenderTextureCubeFaceNone) {
600 renderable.rhiRenderData.mainPass.pipeline = rhiCtxD->pipeline(pipelineKey,
601 renderPassDescriptor,
603 dcd.pipeline = renderable.rhiRenderData.mainPass.pipeline;
605 renderable.rhiRenderData.reflectionPass.pipeline = rhiCtxD->pipeline(pipelineKey,
606 renderPassDescriptor,
608 dcd.pipeline = renderable.rhiRenderData.reflectionPass.pipeline;
610 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
611 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
616void QSSGParticleRenderer::prepareParticlesForModel(QSSGRhiShaderPipeline &shaderPipeline,
617 QSSGRhiContext *rhiCtx,
618 QSSGRhiShaderResourceBindingList &bindings,
619 const QSSGRenderModel *model)
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();
633 particleData.texture->setPixelSize(size);
634 particleData.texture->create();
636 particleData.particleCount = particleCount;
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);
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,
656 QRhiSampler::ClampToEdge,
657 QRhiSampler::ClampToEdge,
660 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::VertexStage, texture, sampler);
767QSSGRhiShaderPipelinePtr QSSGParticleRenderer::generateRhiShaderPipeline(QSSGRenderer &renderer,
768 QSSGParticlesRenderable &inRenderable,
769 const QSSGShaderFeatures &inFeatureSet,
770 QByteArray &shaderString,
771 const QSSGShaderParticleMaterialKeyProperties &shaderKeyProperties)
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();
778 shaderString = particlesLogPrefix();
779 QSSGShaderParticleMaterialKey theKey(inRenderable.shaderDescription);
781 theKey.toString(shaderString, shaderKeyProperties);
783 if (s_shaderCacheEnabled) {
784 if (
const auto &maybePipeline = shaderCache->tryGetRhiShaderPipeline(shaderString, inFeatureSet))
785 return maybePipeline;
787 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(shaderString, QQsbCollection::toFeatureSet(inFeatureSet));
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;
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);
803 if (
const auto &maybePipeline = shaderCache->tryNewPipelineFromPersistentCache(qsbcKey, shaderString, inFeatureSet))
804 return maybePipeline;
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);
824 common.addDefinition(
"QSSG_PARTICLES_ENABLE_ANIMATED",
"1");
826 common.addDefinition(
"QSSG_PARTICLES_ENABLE_LINE_PARTICLE",
"1");
828 common.addDefinition(
"QSSG_OIT_METHOD", QStringLiteral(
"%1").arg(oit).toUtf8());
830 common.addDefinition(
"QSSG_MULTISAMPLE",
"1");
832 common.addUniform(
"qt_modelMatrix",
"mat4");
833 if (viewCount >= 2) {
834 common.addUniformArray(
"qt_viewMatrix",
"mat4", viewCount);
835 common.addUniformArray(
"qt_projectionMatrix",
"mat4", viewCount);
837 common.addUniform(
"qt_viewMatrix",
"mat4");
838 common.addUniform(
"qt_projectionMatrix",
"mat4");
841 common.addPrefix(s_lightPrefix);
842 common.addUniform(
"lightData",
"ParticleLightData");
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");
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");
858 common.addUniform(
"qt_pointLights",
"bool");
859 common.addUniform(
"qt_spotLights",
"bool");
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");
873 vertex.addInclude(
"particleLighting.glsllib");
875 vertex.addUniform(
"qt_particleTexture",
"sampler2D");
877 vertex.addInclude(
"particleLoading.glsllib");
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");
886 AutoFormatGenerator vg(vertex);
888 vg <<
"const vec2 corners[4] = {{0.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {1.0, 1.0}};";
891 vg <<
"out gl_PerVertex {"
892 <<
" vec4 gl_Position;"
895 vg <<
"void main() {";
897 if (isLineParticle) {
898 vg <<
"uint segmentIndex = gl_VertexIndex / 2;"
899 <<
"uint particleIndex = segmentIndex + gl_InstanceIndex * qt_lineSegmentCount;";
901 vg <<
"uint particleIndex = gl_InstanceIndex;"
902 <<
"uint cornerIndex = gl_VertexIndex;"
903 <<
"vec2 corner = corners[cornerIndex];";
905 vg <<
"instanceIndex = particleIndex;"
906 <<
"Particle p = qt_loadParticle(particleIndex);";
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;";
917 vg <<
"vec4 viewPos = qt_viewMatrix * worldPos;"
918 <<
"vec3 viewBN = (transpose(inverse(qt_viewMatrix * qt_modelMatrix)) * vec4(p.binormal, 0.0)).xyz;";
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);";
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);";
934 vg <<
"viewPos = qt_viewMatrix[gl_ViewIndex] * viewPos;";
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;";
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;";
949 vg <<
"gl_Position = qt_projectionMatrix * viewPos;";
952 vg <<
"spriteData.x = qt_ageToSpriteFactor(p.age);";
954 vg <<
"spriteData.y = p.animationFrame;";
959 fragment.addInclude(
"tonemapping.glsllib");
960 fragment.addInclude(
"particleSprite.glsllib");
961 fragment.addUniform(
"qt_sprite",
"sampler2D");
963 AutoFormatGenerator fg(fragment);
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);
973 fragment.addInclude(
"oitlinkedlist.glsllib");
977 fg <<
"#define spriteFunc";
979 fg <<
"#define spriteFunc qt_sRGBToLinear";
981 fragment.addUniform(
"qt_colorTable",
"sampler2D");
982 if (isColorTableLinear)
983 fg <<
"#define colorTableFunc";
985 fg <<
"#define colorTableFunc qt_sRGBToLinear";
988 fg <<
"vec4 qt_readSprite() {";
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);";
995 fg <<
"return spriteFunc(texture(qt_sprite, texcoord));";
999 fg <<
"vec4 qt_readColor() {";
1002 fg <<
"return color * colorTableFunc(texture(qt_colorTable, vec2(spriteData.x, qt_rand(vec2(instanceIndex, 0)))));";
1004 fg <<
"return color;";
1007 fg <<
"void main() {";
1009 fg <<
"vec4 ret = qt_readColor() * qt_readSprite();";
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
1019 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex, qt_samples);";
1021 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0, qt_samples);";
1024 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, v_viewIndex);";
1026 fg <<
"fragOutput = qt_oitLinkedList(ret, qt_listNodeCount, qt_ABufImageWidth, qt_viewSize, 0);";
1030 fg <<
"fragOutput = qt_tonemap(ret);";
1036 return shaderProgramGenerator->compileGeneratedRhiShader(shaderString,
1038 *shaderLibraryManager,
1040 QSSGRhiShaderPipeline::UsedWithoutIa,
1042 shaderKeyProperties.m_viewCount.getValue(inRenderable.shaderDescription),
1092void QSSGParticleRenderer::rhiRenderRenderable(QSSGRhiContext *rhiCtx,
1093 QSSGParticlesRenderable &renderable,
1094 bool *needsSetViewport,
1095 QSSGRenderTextureCubeFace cubeFace,
1096 const QSSGRhiGraphicsPipelineState &state)
1098 QRhiGraphicsPipeline *ps = renderable.rhiRenderData.mainPass.pipeline;
1099 QRhiShaderResourceBindings *srb = renderable.rhiRenderData.mainPass.srb;
1101 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1102 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
1103 ps = renderable.rhiRenderData.reflectionPass.pipeline;
1104 srb = renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx];
1110 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
1112 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1114 cb->setGraphicsPipeline(ps);
1115 cb->setVertexInput(0, 0,
nullptr);
1116 cb->setShaderResources(srb);
1118 if (needsSetViewport && *needsSetViewport) {
1119 cb->setViewport(state.viewport);
1120 *needsSetViewport =
false;
1122 if (renderable.particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line) {
1124 int S = renderable.particles.m_particleBuffer.segments();
1125 int N = renderable.particles.m_particleBuffer.particleCount() / S;
1128 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DRenderCall, (2 * S | quint64(N) << 32), renderable.particles.profilingId);
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);