977void QSSGLayerRenderData::prepareImageForRender(QSSGRenderImage &inImage,
978 QSSGRenderableImage::Type inMapType,
979 QSSGRenderableImage *&ioFirstImage,
980 QSSGRenderableImage *&ioNextImage,
981 QSSGRenderableObjectFlags &ioFlags,
982 QSSGShaderDefaultMaterialKey &inShaderKey,
983 quint32 inImageIndex,
984 QSSGRenderDefaultMaterial *inMaterial)
986 QSSGRenderContextInterface &contextInterface = *renderer->contextInterface();
987 const auto &bufferManager = contextInterface.bufferManager();
989 if (inImage.clearDirty())
990 ioFlags |= QSSGRenderableObjectFlag::Dirty;
1001 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(&inImage);
1003 if (texture.m_texture) {
1004 if (texture.m_flags.hasTransparency()
1005 && (inMapType == QSSGRenderableImage::Type::Diffuse
1006 || inMapType == QSSGRenderableImage::Type::Opacity
1007 || inMapType == QSSGRenderableImage::Type::Translucency))
1009 ioFlags |= QSSGRenderableObjectFlag::HasTransparency;
1012 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, inMapType, inImage, texture);
1013 QSSGShaderKeyImageMap &theKeyProp = defaultMaterialShaderKeyProperties.m_imageMaps[inImageIndex];
1015 theKeyProp.setEnabled(inShaderKey,
true);
1016 switch (inImage.m_mappingMode) {
1017 case QSSGRenderImage::MappingModes::Normal:
1019 case QSSGRenderImage::MappingModes::Environment:
1020 theKeyProp.setEnvMap(inShaderKey,
true);
1022 case QSSGRenderImage::MappingModes::LightProbe:
1023 theKeyProp.setLightProbe(inShaderKey,
true);
1033 switch (texture.m_texture->format()) {
1034 case QRhiTexture::Format::RED_OR_ALPHA8:
1035 hasA = !renderer->contextInterface()->rhiContext()->rhi()->isFeatureSupported(QRhi::RedOrAlpha8IsRed);
1037 case QRhiTexture::Format::R8:
1047 if (inImage.isImageTransformIdentity())
1048 theKeyProp.setIdentityTransform(inShaderKey,
true);
1050 if (inImage.m_indexUV == 1)
1051 theKeyProp.setUsesUV1(inShaderKey,
true);
1053 if (texture.m_flags.isLinear())
1054 theKeyProp.setLinear(inShaderKey,
true);
1056 if (texture.m_flags.isPreMultipliedAlpha())
1057 theKeyProp.setPreMultipliedAlpha(inShaderKey,
true);
1059 if (ioFirstImage ==
nullptr)
1060 ioFirstImage = theImage;
1062 ioNextImage->m_nextImage = theImage;
1064 ioNextImage = theImage;
1066 if (inMaterial && inImageIndex >= QSSGShaderDefaultMaterialKeyProperties::SingleChannelImagesFirst) {
1067 QSSGRenderDefaultMaterial::TextureChannelMapping value = QSSGRenderDefaultMaterial::R;
1069 const quint32 scIndex = inImageIndex - QSSGShaderDefaultMaterialKeyProperties::SingleChannelImagesFirst;
1070 QSSGShaderKeyTextureChannel &channelKey = defaultMaterialShaderKeyProperties.m_textureChannels[scIndex];
1071 switch (inImageIndex) {
1072 case QSSGShaderDefaultMaterialKeyProperties::OpacityMap:
1073 value = inMaterial->opacityChannel;
1075 case QSSGShaderDefaultMaterialKeyProperties::RoughnessMap:
1076 value = inMaterial->roughnessChannel;
1078 case QSSGShaderDefaultMaterialKeyProperties::MetalnessMap:
1079 value = inMaterial->metalnessChannel;
1081 case QSSGShaderDefaultMaterialKeyProperties::OcclusionMap:
1082 value = inMaterial->occlusionChannel;
1084 case QSSGShaderDefaultMaterialKeyProperties::TranslucencyMap:
1085 value = inMaterial->translucencyChannel;
1087 case QSSGShaderDefaultMaterialKeyProperties::HeightMap:
1088 value = inMaterial->heightChannel;
1090 case QSSGShaderDefaultMaterialKeyProperties::ClearcoatMap:
1091 value = inMaterial->clearcoatChannel;
1093 case QSSGShaderDefaultMaterialKeyProperties::ClearcoatRoughnessMap:
1094 value = inMaterial->clearcoatRoughnessChannel;
1096 case QSSGShaderDefaultMaterialKeyProperties::SheenRoughnessMap:
1097 value = inMaterial->sheenRoughnessChannel;
1099 case QSSGShaderDefaultMaterialKeyProperties::IridescenceMap:
1100 value = inMaterial->iridescenceChannel;
1102 case QSSGShaderDefaultMaterialKeyProperties::IridescenceThicknessMap:
1103 value = inMaterial->iridescenceThicknessChannel;
1105 case QSSGShaderDefaultMaterialKeyProperties::TransmissionMap:
1106 value = inMaterial->transmissionChannel;
1108 case QSSGShaderDefaultMaterialKeyProperties::ThicknessMap:
1109 value = inMaterial->thicknessChannel;
1111 case QSSGShaderDefaultMaterialKeyProperties::BaseColorMap:
1112 value = inMaterial->baseColorChannel;
1114 case QSSGShaderDefaultMaterialKeyProperties::SpecularAmountMap:
1115 value = inMaterial->specularAmountChannel;
1117 case QSSGShaderDefaultMaterialKeyProperties::EmissiveMap:
1118 value = inMaterial->emissiveChannel;
1123 bool useDefault =
false;
1125 case QSSGRenderDefaultMaterial::TextureChannelMapping::G:
1128 case QSSGRenderDefaultMaterial::TextureChannelMapping::B:
1131 case QSSGRenderDefaultMaterial::TextureChannelMapping::A:
1138 value = QSSGRenderDefaultMaterial::R;
1139 channelKey.setTextureChannel(QSSGShaderKeyTextureChannel::TexturChannelBits(value), inShaderKey);
1169QSSGDefaultMaterialPreparationResult QSSGLayerRenderData::prepareDefaultMaterialForRender(
1170 QSSGRenderDefaultMaterial &inMaterial,
1171 QSSGRenderableObjectFlags &inExistingFlags,
1172 float inOpacity,
bool hasAnyLights,
1173 bool anyLightHasShadows,
1174 QSSGLayerRenderPreparationResultFlags &ioFlags)
1176 QSSGRenderDefaultMaterial *theMaterial = &inMaterial;
1177 QSSGDefaultMaterialPreparationResult retval(QSSGShaderDefaultMaterialKey(qHash(features)));
1178 retval.renderableFlags = inExistingFlags;
1179 QSSGRenderableObjectFlags &renderableFlags(retval.renderableFlags);
1180 QSSGShaderDefaultMaterialKey &theGeneratedKey(retval.materialKey);
1181 retval.opacity = inOpacity;
1182 float &subsetOpacity(retval.opacity);
1184 if (theMaterial->isDirty())
1185 renderableFlags |= QSSGRenderableObjectFlag::Dirty;
1187 subsetOpacity *= theMaterial->opacity;
1189 QSSGRenderableImage *firstImage =
nullptr;
1191 const bool lighting = theMaterial->lighting != QSSGRenderDefaultMaterial::MaterialLighting::NoLighting;
1192 defaultMaterialShaderKeyProperties.m_hasLighting.setValue(theGeneratedKey, lighting);
1194 defaultMaterialShaderKeyProperties.m_hasPunctualLights.setValue(theGeneratedKey, hasAnyLights);
1195 defaultMaterialShaderKeyProperties.m_hasShadows.setValue(theGeneratedKey, anyLightHasShadows);
1196 const bool validSky = layer.skyMaterial !=
nullptr && layer.skyMaterial->enableIBL;
1197 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey, layer.lightProbe !=
nullptr || validSky);
1200 defaultMaterialShaderKeyProperties.m_specularAAEnabled.setValue(theGeneratedKey, layer.specularAAEnabled);
1203 defaultMaterialShaderKeyProperties.m_isDoubleSided.setValue(theGeneratedKey, theMaterial->cullMode == QSSGCullFaceMode::Disabled);
1206 defaultMaterialShaderKeyProperties.m_overridesPosition.setValue(theGeneratedKey,
false);
1209 defaultMaterialShaderKeyProperties.m_usesProjectionMatrix.setValue(theGeneratedKey,
false);
1210 defaultMaterialShaderKeyProperties.m_usesInverseProjectionMatrix.setValue(theGeneratedKey,
false);
1212 defaultMaterialShaderKeyProperties.m_usesVarColor.setValue(theGeneratedKey,
false);
1215 defaultMaterialShaderKeyProperties.m_alphaMode.setValue(theGeneratedKey, theMaterial->alphaMode);
1218 setVertexInputPresence(renderableFlags, theGeneratedKey);
1221 defaultMaterialShaderKeyProperties.m_usesPointsTopology.setValue(theGeneratedKey, renderableFlags.isPointsTopology());
1224 defaultMaterialShaderKeyProperties.m_lightmapEnabled.setValue(theGeneratedKey, renderableFlags.rendersWithLightmap());
1225 defaultMaterialShaderKeyProperties.m_metallicRoughnessEnabled.setValue(theGeneratedKey, theMaterial->type == QSSGRenderDefaultMaterial::Type::PrincipledMaterial);
1226 defaultMaterialShaderKeyProperties.m_specularGlossyEnabled.setValue(theGeneratedKey, theMaterial->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial);
1230 defaultMaterialShaderKeyProperties.m_debugMode.setValue(theGeneratedKey,
int(layer.debugMode));
1233 defaultMaterialShaderKeyProperties.m_fogEnabled.setValue(theGeneratedKey, layer.fog.enabled);
1236 defaultMaterialShaderKeyProperties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
1237 defaultMaterialShaderKeyProperties.m_usesViewIndex.setValue(theGeneratedKey, layer.viewCount >= 2);
1239 if (!defaultMaterialShaderKeyProperties.m_hasIbl.getValue(theGeneratedKey) && theMaterial->iblProbe) {
1240 features.set(QSSGShaderFeatures::Feature::LightProbe,
true);
1241 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey,
true);
1246 if (subsetOpacity >= QSSGRendererPrivate::minimumRenderOpacity) {
1262 if (theMaterial->blendMode != QSSGRenderDefaultMaterial::MaterialBlendMode::SourceOver
1263 || theMaterial->opacityMap
1264 || theMaterial->alphaMode == QSSGRenderDefaultMaterial::Blend)
1266 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1269 const bool specularEnabled = theMaterial->isSpecularEnabled();
1270 const bool metalnessEnabled = theMaterial->isMetalnessEnabled();
1271 defaultMaterialShaderKeyProperties.m_specularEnabled.setValue(theGeneratedKey, specularEnabled || metalnessEnabled);
1272 defaultMaterialShaderKeyProperties.m_specularModel.setSpecularModel(theGeneratedKey, theMaterial->specularModel);
1273 defaultMaterialShaderKeyProperties.m_diffuseModel.setDiffuseModel(theGeneratedKey, theMaterial->diffuseModel);
1274 defaultMaterialShaderKeyProperties.m_fresnelScaleBiasEnabled.setValue(theGeneratedKey, theMaterial->isFresnelScaleBiasEnabled());
1275 defaultMaterialShaderKeyProperties.m_clearcoatFresnelScaleBiasEnabled.setValue(theGeneratedKey, theMaterial->isClearcoatFresnelScaleBiasEnabled());
1276 defaultMaterialShaderKeyProperties.m_fresnelEnabled.setValue(theGeneratedKey, theMaterial->isFresnelEnabled());
1277 defaultMaterialShaderKeyProperties.m_baseColorSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isBaseColorSingleChannelEnabled());
1278 defaultMaterialShaderKeyProperties.m_specularSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isSpecularAmountSingleChannelEnabled());
1279 defaultMaterialShaderKeyProperties.m_emissiveSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isEmissiveSingleChannelEnabled());
1280 defaultMaterialShaderKeyProperties.m_invertOpacityMapValue.setValue(theGeneratedKey, theMaterial->isInvertOpacityMapValue());
1281 defaultMaterialShaderKeyProperties.m_vertexColorsEnabled.setValue(theGeneratedKey, theMaterial->isVertexColorsEnabled());
1282 defaultMaterialShaderKeyProperties.m_vertexColorsMaskEnabled.setValue(theGeneratedKey, theMaterial->isVertexColorsMaskEnabled());
1283 defaultMaterialShaderKeyProperties.m_vertexColorRedMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorRedMask.toInt()));
1284 defaultMaterialShaderKeyProperties.m_vertexColorGreenMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorGreenMask.toInt()));
1285 defaultMaterialShaderKeyProperties.m_vertexColorBlueMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorBlueMask.toInt()));
1286 defaultMaterialShaderKeyProperties.m_vertexColorAlphaMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorAlphaMask.toInt()));
1287 defaultMaterialShaderKeyProperties.m_clearcoatEnabled.setValue(theGeneratedKey, theMaterial->isClearcoatEnabled());
1288 defaultMaterialShaderKeyProperties.m_sheenEnabled.setValue(theGeneratedKey, theMaterial->isSheenEnabled());
1289 defaultMaterialShaderKeyProperties.m_anisotropyEnabled.setValue(theGeneratedKey, theMaterial->isAnisotropyEnabled());
1290 defaultMaterialShaderKeyProperties.m_iridescenceEnabled.setValue(theGeneratedKey, theMaterial->isIridescenceEnabled());
1291 defaultMaterialShaderKeyProperties.m_dispersionEnabled.setValue(theGeneratedKey, theMaterial->isDispersionEnabled());
1292 defaultMaterialShaderKeyProperties.m_transmissionEnabled.setValue(theGeneratedKey, theMaterial->isTransmissionEnabled());
1297 QSSGRenderableImage *nextImage =
nullptr;
1298#define CHECK_IMAGE_AND_PREPARE(img, imgtype, shadercomponent)
1300 prepareImageForRender(*(img), imgtype, firstImage, nextImage, renderableFlags,
1301 theGeneratedKey, shadercomponent, &inMaterial)
1303 if (theMaterial->type == QSSGRenderGraphObject::Type::PrincipledMaterial ||
1304 theMaterial->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial) {
1306 QSSGRenderableImage::Type::BaseColor,
1307 QSSGShaderDefaultMaterialKeyProperties::BaseColorMap);
1309 QSSGRenderableImage::Type::Occlusion,
1310 QSSGShaderDefaultMaterialKeyProperties::OcclusionMap);
1312 QSSGRenderableImage::Type::Height,
1313 QSSGShaderDefaultMaterialKeyProperties::HeightMap);
1315 QSSGRenderableImage::Type::Clearcoat,
1316 QSSGShaderDefaultMaterialKeyProperties::ClearcoatMap);
1318 QSSGRenderableImage::Type::ClearcoatRoughness,
1319 QSSGShaderDefaultMaterialKeyProperties::ClearcoatRoughnessMap);
1321 QSSGRenderableImage::Type::ClearcoatNormal,
1322 QSSGShaderDefaultMaterialKeyProperties::ClearcoatNormalMap);
1324 QSSGRenderableImage::Type::SheenColor,
1325 QSSGShaderDefaultMaterialKeyProperties::SheenColorMap);
1327 QSSGRenderableImage::Type::SheenRoughness,
1328 QSSGShaderDefaultMaterialKeyProperties::SheenRoughnessMap);
1330 QSSGRenderableImage::Type::Anisotropy,
1331 QSSGShaderDefaultMaterialKeyProperties::AnisotropyMap);
1333 QSSGRenderableImage::Type::Iridescence,
1334 QSSGShaderDefaultMaterialKeyProperties::IridescenceMap);
1336 QSSGRenderableImage::Type::IridescenceThickness,
1337 QSSGShaderDefaultMaterialKeyProperties::IridescenceThicknessMap);
1339 QSSGRenderableImage::Type::Transmission,
1340 QSSGShaderDefaultMaterialKeyProperties::TransmissionMap);
1342 QSSGRenderableImage::Type::Thickness,
1343 QSSGShaderDefaultMaterialKeyProperties::ThicknessMap);
1344 if (theMaterial->type == QSSGRenderGraphObject::Type::PrincipledMaterial) {
1346 QSSGRenderableImage::Type::Metalness,
1347 QSSGShaderDefaultMaterialKeyProperties::MetalnessMap);
1351 QSSGRenderableImage::Type::Diffuse,
1352 QSSGShaderDefaultMaterialKeyProperties::DiffuseMap);
1354 CHECK_IMAGE_AND_PREPARE(theMaterial->emissiveMap, QSSGRenderableImage::Type::Emissive, QSSGShaderDefaultMaterialKeyProperties::EmissiveMap);
1356 QSSGRenderableImage::Type::Specular,
1357 QSSGShaderDefaultMaterialKeyProperties::SpecularMap);
1359 QSSGRenderableImage::Type::Roughness,
1360 QSSGShaderDefaultMaterialKeyProperties::RoughnessMap);
1361 CHECK_IMAGE_AND_PREPARE(theMaterial->opacityMap, QSSGRenderableImage::Type::Opacity, QSSGShaderDefaultMaterialKeyProperties::OpacityMap);
1362 CHECK_IMAGE_AND_PREPARE(theMaterial->bumpMap, QSSGRenderableImage::Type::Bump, QSSGShaderDefaultMaterialKeyProperties::BumpMap);
1364 QSSGRenderableImage::Type::SpecularAmountMap,
1365 QSSGShaderDefaultMaterialKeyProperties::SpecularAmountMap);
1366 CHECK_IMAGE_AND_PREPARE(theMaterial->normalMap, QSSGRenderableImage::Type::Normal, QSSGShaderDefaultMaterialKeyProperties::NormalMap);
1368 QSSGRenderableImage::Type::Translucency,
1369 QSSGShaderDefaultMaterialKeyProperties::TranslucencyMap);
1371#undef CHECK_IMAGE_AND_PREPARE
1373 if (subsetOpacity < QSSGRendererPrivate::minimumRenderOpacity) {
1374 subsetOpacity = 0.0f;
1378 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1379 renderableFlags |= QSSGRenderableObjectFlag::CompletelyTransparent;
1382 if (subsetOpacity > 1.f - QSSGRendererPrivate::minimumRenderOpacity)
1383 subsetOpacity = 1.f;
1385 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1387 if (inMaterial.isTransmissionEnabled()) {
1388 ioFlags.setRequiresScreenTexture(
true);
1389 ioFlags.setRequiresMipmapsForScreenTexture(
true);
1390 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1393 if (renderableFlags.hasTransparency()) {
1394 if (orderIndependentTransparencyEnabled)
1395 defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.setValue(theGeneratedKey,
int(layer.oitMethod));
1396 if (layer.oitMethodDirty)
1397 renderableFlags |= QSSGRenderableObjectFlag::Dirty;
1400 retval.firstImage = firstImage;
1401 if (retval.renderableFlags.isDirty())
1402 retval.dirty =
true;
1404 renderer->addMaterialDirtyClear(&inMaterial);
1408QSSGDefaultMaterialPreparationResult QSSGLayerRenderData::prepareCustomMaterialForRender(
1409 QSSGRenderCustomMaterial &inMaterial, QSSGRenderableObjectFlags &inExistingFlags,
1410 float inOpacity,
bool alreadyDirty,
bool hasAnyLights,
bool anyLightHasShadows,
1411 QSSGLayerRenderPreparationResultFlags &ioFlags)
1413 QSSGDefaultMaterialPreparationResult retval(QSSGShaderDefaultMaterialKey(qHash(features)));
1414 retval.renderableFlags = inExistingFlags;
1415 QSSGRenderableObjectFlags &renderableFlags(retval.renderableFlags);
1416 QSSGShaderDefaultMaterialKey &theGeneratedKey(retval.materialKey);
1417 retval.opacity = inOpacity;
1418 float &subsetOpacity(retval.opacity);
1420 if (subsetOpacity < QSSGRendererPrivate::minimumRenderOpacity) {
1421 subsetOpacity = 0.0f;
1425 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1426 renderableFlags |= QSSGRenderableObjectFlag::CompletelyTransparent;
1429 if (subsetOpacity > 1.f - QSSGRendererPrivate::minimumRenderOpacity)
1430 subsetOpacity = 1.f;
1432 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1434 defaultMaterialShaderKeyProperties.m_hasLighting.setValue(theGeneratedKey,
true);
1435 defaultMaterialShaderKeyProperties.m_hasPunctualLights.setValue(theGeneratedKey, hasAnyLights);
1436 defaultMaterialShaderKeyProperties.m_hasShadows.setValue(theGeneratedKey, anyLightHasShadows);
1437 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey, layer.lightProbe !=
nullptr || layer.skyMaterial !=
nullptr);
1438 defaultMaterialShaderKeyProperties.m_specularEnabled.setValue(theGeneratedKey,
true);
1440 defaultMaterialShaderKeyProperties.m_specularAAEnabled.setValue(theGeneratedKey, layer.specularAAEnabled);
1443 defaultMaterialShaderKeyProperties.m_isDoubleSided.setValue(theGeneratedKey, inMaterial.m_cullMode == QSSGCullFaceMode::Disabled);
1446 defaultMaterialShaderKeyProperties.m_metallicRoughnessEnabled.setValue(theGeneratedKey,
true);
1449 const bool overridesPosition = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::OverridesPosition);
1450 defaultMaterialShaderKeyProperties.m_overridesPosition.setValue(theGeneratedKey, overridesPosition);
1453 const bool usesProjectionMatrix = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ProjectionMatrix);
1454 defaultMaterialShaderKeyProperties.m_usesProjectionMatrix.setValue(theGeneratedKey, usesProjectionMatrix);
1455 const bool usesInvProjectionMatrix = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::InverseProjectionMatrix);
1456 defaultMaterialShaderKeyProperties.m_usesInverseProjectionMatrix.setValue(theGeneratedKey, usesInvProjectionMatrix);
1459 setVertexInputPresence(renderableFlags, theGeneratedKey);
1462 defaultMaterialShaderKeyProperties.m_usesPointsTopology.setValue(theGeneratedKey, renderableFlags.isPointsTopology());
1465 defaultMaterialShaderKeyProperties.m_lightmapEnabled.setValue(theGeneratedKey, renderableFlags.rendersWithLightmap());
1468 defaultMaterialShaderKeyProperties.m_debugMode.setValue(theGeneratedKey,
int(layer.debugMode));
1471 defaultMaterialShaderKeyProperties.m_fogEnabled.setValue(theGeneratedKey, layer.fog.enabled);
1474 defaultMaterialShaderKeyProperties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
1475 defaultMaterialShaderKeyProperties.m_usesViewIndex.setValue(theGeneratedKey,
1476 inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ViewIndex));
1481 const bool usesVarColor = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::VarColor);
1482 defaultMaterialShaderKeyProperties.m_usesVarColor.setValue(theGeneratedKey, usesVarColor);
1484 const bool usesClearcoat = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Clearcoat);
1485 defaultMaterialShaderKeyProperties.m_clearcoatEnabled.setValue(theGeneratedKey, usesClearcoat);
1487 const bool usesSheen = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Sheen);
1488 defaultMaterialShaderKeyProperties.m_sheenEnabled.setValue(theGeneratedKey, usesSheen);
1490 const bool usesAnisotropy = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Anisotropy);
1491 defaultMaterialShaderKeyProperties.m_anisotropyEnabled.setValue(theGeneratedKey, usesAnisotropy);
1493 const bool usesIridescence = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Iridescence);
1494 defaultMaterialShaderKeyProperties.m_iridescenceEnabled.setValue(theGeneratedKey, usesIridescence);
1496 const bool usesDispersion = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Dispersion);
1497 defaultMaterialShaderKeyProperties.m_dispersionEnabled.setValue(theGeneratedKey, usesDispersion);
1499 const bool usesClearcoatFresnelScaleBias = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ClearcoatFresnelScaleBias);
1500 defaultMaterialShaderKeyProperties.m_clearcoatFresnelScaleBiasEnabled.setValue(theGeneratedKey, usesClearcoatFresnelScaleBias);
1502 const bool usesFresnelScaleBias = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::FresnelScaleBias);
1503 defaultMaterialShaderKeyProperties.m_fresnelScaleBiasEnabled.setValue(theGeneratedKey, usesFresnelScaleBias);
1505 const bool usesTransmission = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Transmission);
1506 defaultMaterialShaderKeyProperties.m_transmissionEnabled.setValue(theGeneratedKey, usesTransmission);
1508 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Blending))
1509 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1511 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenTexture)) {
1512 ioFlags.setRequiresScreenTexture(
true);
1513 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1516 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenMipTexture)) {
1517 ioFlags.setRequiresScreenTexture(
true);
1518 ioFlags.setRequiresMipmapsForScreenTexture(
true);
1519 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1522 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::DepthTexture))
1523 ioFlags.setRequiresDepthTexture(
true);
1525 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::NormalTexture)) {
1526 ioFlags.setRequiresNormalTexture(
true);
1527 renderableFlags |= QSSGRenderableObjectFlag::RequiresNormalTexture;
1530 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::AoTexture)) {
1531 ioFlags.setRequiresDepthTexture(
true);
1532 ioFlags.setRequiresSsaoPass(
true);
1534 if (orderIndependentTransparencyEnabled && renderableFlags.hasTransparency())
1535 defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.setValue(theGeneratedKey,
int(layer.oitMethod));
1537 retval.firstImage =
nullptr;
1539 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::MotionVectorTexture))
1540 ioFlags.setRequiresMotionVectorPass(
true);
1542 if (retval.dirty || alreadyDirty)
1543 renderer->addMaterialDirtyClear(&inMaterial);
1601bool QSSGLayerRenderData::prepareModelsForRender(QSSGRenderContextInterface &contextInterface,
1602 const RenderableNodeEntries &renderableModels,
1603 QSSGLayerRenderPreparationResultFlags &ioFlags,
1604 const QSSGRenderCameraList &allCameras,
1605 const QSSGRenderCameraDataList &allCameraData,
1606 TModelContextPtrList &modelContexts,
1607 QSSGRenderableObjectList &opaqueObjects,
1608 QSSGRenderableObjectList &transparentObjects,
1609 QSSGRenderableObjectList &screenTextureObjects,
1612 const auto &rhiCtx = contextInterface.rhiContext();
1613 const auto &bufferManager = contextInterface.bufferManager();
1615 const auto &debugDrawSystem = contextInterface.debugDrawSystem();
1616 const bool maybeDebugDraw = debugDrawSystem && debugDrawSystem->isEnabled();
1618 bool wasDirty =
false;
1620 for (
const QSSGRenderableNodeEntry &renderable : renderableModels) {
1621 if ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::Disabled) != 0)
1624 const QSSGRenderModel &model = *
static_cast<QSSGRenderModel *>(renderable.node);
1625 const auto &lights = renderable.lights;
1626 QSSGRenderMesh *theMesh = modelData->getMesh(model);
1630 const bool altGlobalTransform = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::GlobalTransform) != 0);
1631 const auto &globalTransform = altGlobalTransform ? renderable.extOverrides.globalTransform : getGlobalTransform(model);
1632 QMatrix3x3 normalMatrix { Qt::Uninitialized };
1633 QSSGLayerRenderData::ModelViewProjections mvps;
1634 if (altGlobalTransform) {
1635 QSSGRenderNode::calculateNormalMatrix(globalTransform, normalMatrix);
1636 size_t mvpCount = 0;
1637 for (
const auto &cameraData : allCameraData) {
1638 QSSGRenderNode::calculateMVPAndNormalMatrix(globalTransform, cameraData.viewProjection, mvps[mvpCount++], normalMatrix);
1641 if (model.usesBoneTexture()) {
1645 size_t mvpCount = 0;
1646 for (
const QSSGRenderCameraData &cameraData : allCameraData) {
1647 mvps[mvpCount++] = cameraData.viewProjection;
1648 normalMatrix = QMatrix3x3();
1651 normalMatrix = getNormalMatrix(model);
1652 mvps = getModelMvps(model);
1655 const bool altModelOpacity = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::GlobalOpacity) != 0);
1656 const float modelGlobalOpacity = altModelOpacity ? renderable.extOverrides.globalOpacity : getGlobalOpacity(model);
1657 QSSGModelContext &theModelContext = *RENDER_FRAME_NEW<QSSGModelContext>(contextInterface, model, globalTransform, normalMatrix, mvps);
1658 modelContexts.push_back(&theModelContext);
1661 const auto &meshSubsets = theMesh->subsets;
1662 const auto meshSubsetCount = meshSubsets.size();
1663 theModelContext.subsets = RENDER_FRAME_NEW_BUFFER<QSSGSubsetRenderable>(contextInterface, meshSubsetCount);
1667 auto boneTexture = bufferManager->loadSkinmap(model.skin);
1668 setBonemapTexture(theModelContext, boneTexture.m_texture);
1669 }
else if (model.skeleton) {
1670 auto boneTexture = bufferManager->loadSkinmap(&(model.skeleton->boneTexData));
1671 setBonemapTexture(theModelContext, boneTexture.m_texture);
1675 QSSGRenderableObjectFlags renderableFlagsForModel;
1677 if (meshSubsetCount > 0) {
1678 const QSSGRenderSubset &theSubset = meshSubsets.at(0);
1680 renderableFlagsForModel.setMotionVectorParticipant(model.motionVectorEnabled);
1682 renderableFlagsForModel.setCastsShadows(model.castsShadows);
1683 renderableFlagsForModel.setReceivesShadows(model.receivesShadows);
1684 renderableFlagsForModel.setReceivesReflections(model.receivesReflections);
1685 renderableFlagsForModel.setCastsReflections(model.castsReflections);
1687 renderableFlagsForModel.setUsedInBakedLighting(model.usedInBakedLighting);
1688 if (model.hasLightmap()) {
1689 QSSGRenderImageTexture lmImageTexture = bufferManager->loadLightmap(model);
1690 if (lmImageTexture.m_texture) {
1691 renderableFlagsForModel.setRendersWithLightmap(
true);
1692 setLightmapTexture(theModelContext, lmImageTexture.m_texture);
1701 bool hasJoint =
false;
1702 bool hasWeight =
false;
1703 bool hasMorphTarget = theSubset.rhi.targetsTexture !=
nullptr;
1704 for (
const QSSGRhiInputAssemblerState::InputSemantic &sem : std::as_const(theSubset.rhi.ia.inputs)) {
1705 if (sem == QSSGRhiInputAssemblerState::PositionSemantic) {
1706 renderableFlagsForModel.setHasAttributePosition(
true);
1707 }
else if (sem == QSSGRhiInputAssemblerState::NormalSemantic) {
1708 renderableFlagsForModel.setHasAttributeNormal(
true);
1709 }
else if (sem == QSSGRhiInputAssemblerState::TexCoord0Semantic) {
1710 renderableFlagsForModel.setHasAttributeTexCoord0(
true);
1711 }
else if (sem == QSSGRhiInputAssemblerState::TexCoord1Semantic) {
1712 renderableFlagsForModel.setHasAttributeTexCoord1(
true);
1713 }
else if (sem == QSSGRhiInputAssemblerState::TexCoordLightmapSemantic) {
1714 renderableFlagsForModel.setHasAttributeTexCoordLightmap(
true);
1715 }
else if (sem == QSSGRhiInputAssemblerState::TangentSemantic) {
1716 renderableFlagsForModel.setHasAttributeTangent(
true);
1717 }
else if (sem == QSSGRhiInputAssemblerState::BinormalSemantic) {
1718 renderableFlagsForModel.setHasAttributeBinormal(
true);
1719 }
else if (sem == QSSGRhiInputAssemblerState::ColorSemantic) {
1720 renderableFlagsForModel.setHasAttributeColor(
true);
1723 }
else if (sem == QSSGRhiInputAssemblerState::JointSemantic) {
1725 }
else if (sem == QSSGRhiInputAssemblerState::WeightSemantic) {
1729 renderableFlagsForModel.setHasAttributeJointAndWeight(hasJoint && hasWeight);
1730 renderableFlagsForModel.setHasAttributeMorphTarget(hasMorphTarget);
1733 QSSGRenderableObjectList bakedLightingObjects;
1734 bool usesBlendParticles = particlesEnabled && theModelContext.model.particleBuffer !=
nullptr
1735 && model.particleBuffer->particleCount();
1736 const bool anyLightHasShadows = std::find_if(lights.begin(),
1738 [](
const QSSGShaderLight &light) {
return light.shadows; })
1740 const bool hasAnyLights = !lights.isEmpty();
1741 QSSGRenderLight::SoftShadowQuality maxSoftShadowQuality = QSSGRenderLight::SoftShadowQuality::Hard;
1742 if (anyLightHasShadows) {
1744 for (
const QSSGShaderLight &light : lights) {
1745 if (light.shadows && light.light->m_softShadowQuality > maxSoftShadowQuality)
1746 maxSoftShadowQuality = light.light->m_softShadowQuality;
1752 auto &renderableSubsets = theModelContext.subsets;
1753 const bool hasMaterialOverrides = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::Materials) != 0);
1754 const auto &materials = hasMaterialOverrides ? renderable.extOverrides.materials : modelData->getMaterials(model);
1755 const auto materialCount = materials.size();
1756 QSSGRenderGraphObject *lastMaterial = !materials.isEmpty() ? materials.last() :
nullptr;
1757 int idx = 0, subsetIdx = 0;
1758 for (; idx < meshSubsetCount; ++idx) {
1760 QSSGRenderGraphObject *theMaterialObject = (idx >= materialCount) ? lastMaterial : materials[idx];
1761 if (!theMaterialObject)
1764 const QSSGRenderSubset &theSubset = meshSubsets.at(idx);
1765 QSSGRenderableObjectFlags renderableFlags = renderableFlagsForModel;
1766 float subsetOpacity = modelGlobalOpacity;
1768 renderableFlags.setPointsTopology(theSubset.rhi.ia.topology == QRhiGraphicsPipeline::Points);
1769 QSSGRenderableObject *theRenderableObject = &renderableSubsets[subsetIdx++];
1771 const bool usesInstancing = theModelContext.model.instancing()
1772 && rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing);
1773 if (usesInstancing && theModelContext.model.instanceTable->hasTransparency())
1774 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1775 if (theModelContext.model.hasTransparency)
1776 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1779 quint32 subsetLevelOfDetail = 0;
1780 if (!theSubset.lods.isEmpty() && lodThreshold > 0.0f) {
1782 float lodDistanceMultiplier = camerasView[0]->getLevelOfDetailMultiplier();
1783 float distanceThreshold = 0.0f;
1784 const auto scale = QSSGUtils::mat44::getScale(globalTransform);
1785 float modelScale = qMax(scale.x(), qMax(scale.y(), scale.z()));
1786 QSSGBounds3 transformedBounds = theSubset.bounds;
1787 if (camerasView[0]->type != QSSGRenderGraphObject::Type::OrthographicCamera) {
1788 transformedBounds.transform(globalTransform);
1789 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod))
1790 debugDrawSystem->drawBounds(transformedBounds, QColor(Qt::red));
1791 const QMatrix4x4 cameraGlobalTranform = getGlobalTransform(*camerasView[0]);
1792 const QVector3D cameraNormal = QSSGRenderNode::getScalingCorrectDirection(cameraGlobalTranform);
1793 const QVector3D cameraPosition = QSSGRenderNode::getGlobalPos(cameraGlobalTranform);
1794 const QSSGPlane cameraPlane = QSSGPlane(cameraPosition, cameraNormal);
1795 const QVector3D lodSupportMin = transformedBounds.getSupport(-cameraNormal);
1796 const QVector3D lodSupportMax = transformedBounds.getSupport(cameraNormal);
1797 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod))
1798 debugDrawSystem->drawPoint(lodSupportMin, QColor(
"orange"));
1800 const float distanceMin = cameraPlane.distance(lodSupportMin);
1801 const float distanceMax = cameraPlane.distance(lodSupportMax);
1803 if (distanceMin * distanceMax < 0.0)
1804 distanceThreshold = 0.0;
1805 else if (distanceMin >= 0.0)
1806 distanceThreshold = distanceMin;
1807 else if (distanceMax <= 0.0)
1808 distanceThreshold = -distanceMax;
1812 distanceThreshold = 1.0;
1815 int currentLod = -1;
1816 if (model.levelOfDetailBias > 0.0f) {
1820 int lodsCount = theSubset.lods.size();
1821 if (model.instanceTable && lodsCount) {
1822 currentLod = qRound((lodsCount - 1) * qBound(0.f, model.instancingLodFactor, 1.f));
1824 const float threshold = distanceThreshold * lodDistanceMultiplier;
1825 const float modelBias = 1 / model.levelOfDetailBias;
1826 for (qsizetype i = 0; i < lodsCount; ++i) {
1827 float subsetDistance = theSubset.lods[i].distance * modelScale * modelBias;
1828 float screenSize = subsetDistance / threshold;
1829 if (screenSize > lodThreshold)
1836 if (currentLod == -1)
1837 subsetLevelOfDetail = 0;
1839 subsetLevelOfDetail = currentLod + 1;
1840 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod))
1841 debugDrawSystem->drawBounds(transformedBounds, QSSGDebugDrawSystem::levelOfDetailColor(subsetLevelOfDetail));
1844 QVector3D theModelCenter(theSubset.bounds.center());
1845 theModelCenter = QSSGUtils::mat44::transform(globalTransform, theModelCenter);
1846 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLodNormal)) {
1847 const QMatrix4x4 allCamera0GlobalTransform = getGlobalTransform(*allCameras[0]);
1848 debugDrawSystem->debugNormals(*bufferManager, theModelContext, theSubset, subsetLevelOfDetail, (theModelCenter - QSSGRenderNode::getGlobalPos(allCamera0GlobalTransform)).length() * 0.01);
1851 auto checkF32TypeIndex = [&rhiCtx](QRhiVertexInputAttribute::Format f) {
1852 if ((f == QRhiVertexInputAttribute::Format::Float4)
1853 || (f == QRhiVertexInputAttribute::Format::Float3)
1854 || (f == QRhiVertexInputAttribute::Format::Float2)
1855 || (f == QRhiVertexInputAttribute::Format::Float)) {
1858 if (!rhiCtx->rhi()->isFeatureSupported(QRhi::IntAttributes))
1859 qWarning() <<
"WARN: Model has non-integer type indices for skinning but current RHI backend doesn't support it!";
1863 if (theMaterialObject->type == QSSGRenderGraphObject::Type::DefaultMaterial ||
1864 theMaterialObject->type == QSSGRenderGraphObject::Type::PrincipledMaterial ||
1865 theMaterialObject->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial) {
1866 QSSGRenderDefaultMaterial &theMaterial(
static_cast<QSSGRenderDefaultMaterial &>(*theMaterialObject));
1867 QSSGDefaultMaterialPreparationResult theMaterialPrepResult(prepareDefaultMaterialForRender(theMaterial, renderableFlags, subsetOpacity, hasAnyLights, anyLightHasShadows, ioFlags));
1868 QSSGShaderDefaultMaterialKey &theGeneratedKey(theMaterialPrepResult.materialKey);
1869 subsetOpacity = theMaterialPrepResult.opacity;
1870 QSSGRenderableImage *firstImage(theMaterialPrepResult.firstImage);
1871 wasDirty |= theMaterialPrepResult.dirty;
1872 renderableFlags = theMaterialPrepResult.renderableFlags;
1873 if (renderableFlags.hasTransparency())
1874 ioFlags.setHasCustomBlendMode(theMaterial.blendMode != QSSGRenderDefaultMaterial::MaterialBlendMode::SourceOver);
1877 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey, usesBlendParticles);
1879 if (defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.getValue(theGeneratedKey) ==
int(QSSGRenderLayer::OITMethod::LinkedList))
1880 defaultMaterialShaderKeyProperties.m_oitMSAA.setValue(theGeneratedKey, rhiCtx->mainPassSampleCount() > 1);
1883 const auto boneCount = model.skin ? model.skin->boneCount :
1884 model.skeleton ? model.skeleton->boneCount : 0;
1885 defaultMaterialShaderKeyProperties.m_boneCount.setValue(theGeneratedKey, boneCount);
1886 if (
auto idJoint = theSubset.rhi.ia.inputs.indexOf(QSSGRhiInputAssemblerState::JointSemantic); idJoint != -1) {
1887 const auto attr = theSubset.rhi.ia.inputLayout.attributeAt(idJoint);
1888 defaultMaterialShaderKeyProperties.m_usesFloatJointIndices.setValue(theGeneratedKey, checkF32TypeIndex(attr->format()));
1892 defaultMaterialShaderKeyProperties.m_shadowSoftness.setShadowSoftness(theGeneratedKey, maxSoftShadowQuality);
1895 defaultMaterialShaderKeyProperties.m_usesInstancing.setValue(theGeneratedKey, usesInstancing);
1897 defaultMaterialShaderKeyProperties.m_targetCount.setValue(theGeneratedKey,
1898 theSubset.rhi.ia.targetCount);
1899 defaultMaterialShaderKeyProperties.m_targetPositionOffset.setValue(theGeneratedKey,
1900 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::PositionSemantic]);
1901 defaultMaterialShaderKeyProperties.m_targetNormalOffset.setValue(theGeneratedKey,
1902 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::NormalSemantic]);
1903 defaultMaterialShaderKeyProperties.m_targetTangentOffset.setValue(theGeneratedKey,
1904 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TangentSemantic]);
1905 defaultMaterialShaderKeyProperties.m_targetBinormalOffset.setValue(theGeneratedKey,
1906 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::BinormalSemantic]);
1907 defaultMaterialShaderKeyProperties.m_targetTexCoord0Offset.setValue(theGeneratedKey,
1908 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord0Semantic]);
1909 defaultMaterialShaderKeyProperties.m_targetTexCoord1Offset.setValue(theGeneratedKey,
1910 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord1Semantic]);
1911 defaultMaterialShaderKeyProperties.m_targetColorOffset.setValue(theGeneratedKey,
1912 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::ColorSemantic]);
1914 new (theRenderableObject) QSSGSubsetRenderable(QSSGSubsetRenderable::Type::DefaultMaterialMeshSubset,
1921 subsetLevelOfDetail,
1926 anyLightHasShadows);
1927 wasDirty = wasDirty || renderableFlags.isDirty();
1928 }
else if (theMaterialObject->type == QSSGRenderGraphObject::Type::CustomMaterial) {
1929 QSSGRenderCustomMaterial &theMaterial(
static_cast<QSSGRenderCustomMaterial &>(*theMaterialObject));
1931 const auto &theMaterialSystem(contextInterface.customMaterialSystem());
1932 wasDirty |= theMaterialSystem->prepareForRender(theModelContext.model, theSubset, theMaterial);
1934 if (theMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Blending))
1935 ioFlags.setHasCustomBlendMode(!hasCustomBlendMode(theMaterial));
1937 QSSGDefaultMaterialPreparationResult theMaterialPrepResult(
1938 prepareCustomMaterialForRender(theMaterial, renderableFlags, subsetOpacity, wasDirty,
1939 hasAnyLights, anyLightHasShadows, ioFlags));
1940 QSSGShaderDefaultMaterialKey &theGeneratedKey(theMaterialPrepResult.materialKey);
1941 subsetOpacity = theMaterialPrepResult.opacity;
1942 QSSGRenderableImage *firstImage(theMaterialPrepResult.firstImage);
1943 renderableFlags = theMaterialPrepResult.renderableFlags;
1945 if (model.particleBuffer && model.particleBuffer->particleCount())
1946 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey,
true);
1948 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey,
false);
1950 if (defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.getValue(theGeneratedKey) ==
int(QSSGRenderLayer::OITMethod::LinkedList))
1951 defaultMaterialShaderKeyProperties.m_oitMSAA.setValue(theGeneratedKey, rhiCtx->mainPassSampleCount() > 1);
1954 defaultMaterialShaderKeyProperties.m_shadowSoftness.setShadowSoftness(theGeneratedKey, maxSoftShadowQuality);
1957 const auto boneCount = model.skin ? model.skin->boneCount :
1958 model.skeleton ? model.skeleton->boneCount : 0;
1959 defaultMaterialShaderKeyProperties.m_boneCount.setValue(theGeneratedKey, boneCount);
1960 if (
auto idJoint = theSubset.rhi.ia.inputs.indexOf(QSSGRhiInputAssemblerState::JointSemantic); idJoint != -1) {
1961 const auto attr = theSubset.rhi.ia.inputLayout.attributeAt(idJoint);
1962 defaultMaterialShaderKeyProperties.m_usesFloatJointIndices.setValue(theGeneratedKey, checkF32TypeIndex(attr->format()));
1966 bool usesInstancing = theModelContext.model.instancing()
1967 && rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing);
1968 defaultMaterialShaderKeyProperties.m_usesInstancing.setValue(theGeneratedKey, usesInstancing);
1970 defaultMaterialShaderKeyProperties.m_targetCount.setValue(theGeneratedKey,
1971 theSubset.rhi.ia.targetCount);
1972 defaultMaterialShaderKeyProperties.m_targetPositionOffset.setValue(theGeneratedKey,
1973 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::PositionSemantic]);
1974 defaultMaterialShaderKeyProperties.m_targetNormalOffset.setValue(theGeneratedKey,
1975 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::NormalSemantic]);
1976 defaultMaterialShaderKeyProperties.m_targetTangentOffset.setValue(theGeneratedKey,
1977 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TangentSemantic]);
1978 defaultMaterialShaderKeyProperties.m_targetBinormalOffset.setValue(theGeneratedKey,
1979 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::BinormalSemantic]);
1980 defaultMaterialShaderKeyProperties.m_targetTexCoord0Offset.setValue(theGeneratedKey,
1981 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord0Semantic]);
1982 defaultMaterialShaderKeyProperties.m_targetTexCoord1Offset.setValue(theGeneratedKey,
1983 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord1Semantic]);
1984 defaultMaterialShaderKeyProperties.m_targetColorOffset.setValue(theGeneratedKey,
1985 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::ColorSemantic]);
1987 if (theMaterial.m_iblProbe)
1988 theMaterial.m_iblProbe->clearDirty();
1990 new (theRenderableObject) QSSGSubsetRenderable(QSSGSubsetRenderable::Type::CustomMaterialMeshSubset,
1997 subsetLevelOfDetail,
2002 anyLightHasShadows);
2004 if (theRenderableObject)
2005 theRenderableObject->camdistSq = getCameraDistanceSq(*theRenderableObject, allCameraData[0]);
2009 if (Q_UNLIKELY(idx != subsetIdx))
2010 renderableSubsets.mSize = subsetIdx;
2012 for (
auto &ro : renderableSubsets) {
2013 const auto depthMode = ro.depthWriteMode;
2014 hasDepthWriteObjects |= (depthMode == QSSGDepthDrawMode::Always || depthMode == QSSGDepthDrawMode::OpaqueOnly);
2015 enum ObjectType : quint8 { ScreenTexture, Transparent, Opaque };
2016 static constexpr DepthPrepassObject ppState[][2] = { {DepthPrepassObject::None, DepthPrepassObject::ScreenTexture},
2017 {DepthPrepassObject::None, DepthPrepassObject::Transparent},
2018 {DepthPrepassObject::None, DepthPrepassObject::Opaque} };
2020 if (ro.renderableFlags.requiresScreenTexture()) {
2021 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::ScreenTexture][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2022 screenTextureObjects.push_back({&ro, ro.camdistSq, model.tag});
2023 }
else if (ro.renderableFlags.hasTransparency()) {
2024 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::Transparent][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2025 transparentObjects.push_back({&ro, ro.camdistSq, model.tag});
2027 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::Opaque][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2028 opaqueObjects.push_back({&ro, ro.camdistSq, model.tag});
2031 if (ro.renderableFlags.usedInBakedLighting())
2032 bakedLightingObjects.push_back({&ro, ro.camdistSq, model.tag});
2035 if (!bakedLightingObjects.isEmpty())
2036 bakedLightingModels.push_back(QSSGBakedLightingModel(&model, bakedLightingObjects));
2042bool QSSGLayerRenderData::prepareParticlesForRender(
const RenderableNodeEntries &renderableParticles,
const QSSGRenderCameraData &cameraData, QSSGLayerRenderPreparationResultFlags &ioFlags)
2044 QSSG_ASSERT(particlesEnabled,
return false);
2046 QSSGRenderContextInterface &contextInterface = *renderer->contextInterface();
2051 auto &opaqueObjects = opaqueObjectStore[0];
2052 auto &transparentObjects = transparentObjectStore[0];
2053 auto &screenTextureObjects = screenTextureObjectStore[0];
2055 for (
auto &renderable : renderableParticles) {
2056 QSSGShaderParticleMaterialKeyProperties &properties = particleMaterialShaderKeyProperties;
2058 QSSGRenderParticles &particles = *
static_cast<QSSGRenderParticles *>(renderable.node);
2059 QSSGShaderParticleMaterialKey &theGeneratedKey(particles.materialKey);
2060 const auto &lights = renderable.lights;
2062 QSSGRenderableObjectFlags renderableFlags;
2063 renderableFlags.setCastsShadows(
false);
2064 renderableFlags.setReceivesShadows(
false);
2065 renderableFlags.setHasAttributePosition(
true);
2066 renderableFlags.setHasAttributeNormal(
true);
2067 renderableFlags.setHasAttributeTexCoord0(
true);
2068 renderableFlags.setHasAttributeColor(
true);
2069 renderableFlags.setHasTransparency(particles.m_hasTransparency);
2070 renderableFlags.setCastsReflections(particles.m_castsReflections);
2071 if (particles.m_hasTransparency && particles.m_blendMode != QSSGRenderParticles::BlendMode::SourceOver)
2072 ioFlags.setHasCustomBlendMode(
true);
2074 properties.m_isLineParticle.setValue(theGeneratedKey, particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line);
2075 const bool animated = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimated
2076 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Animated
2077 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::AnimatedVLight
2078 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimatedVLight;
2079 const bool mapped = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMapped
2080 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Mapped
2081 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::MappedVLight
2082 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMappedVLight;
2083 const bool lit = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineVLight
2084 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::AnimatedVLight
2085 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::MappedVLight
2086 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMappedVLight
2087 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimatedVLight
2088 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::SimpleVLight;
2089 properties.m_isAnimated.setValue(theGeneratedKey, animated);
2090 properties.m_isMapped.setValue(theGeneratedKey, mapped);
2091 properties.m_hasLighting.setValue(theGeneratedKey, lit);
2092 properties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
2093 if (renderableFlags.hasTransparency() && orderIndependentTransparencyEnabled) {
2094 properties.m_orderIndependentTransparency.setValue(theGeneratedKey,
int(layer.oitMethod));
2095 if (layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
2096 properties.m_oitMSAA.setValue(theGeneratedKey, contextInterface.rhiContext()->mainPassSampleCount() > 1);
2098 properties.m_orderIndependentTransparency.setValue(theGeneratedKey,
int(0));
2101 float opacity = getGlobalOpacity(particles);
2102 const QMatrix4x4 globalTransform = getGlobalTransform(particles);
2103 QVector3D center(particles.m_particleBuffer.bounds().center());
2104 center = QSSGUtils::mat44::transform(globalTransform, center);
2106 QSSGRenderableImage *firstImage =
nullptr;
2107 if (particles.m_sprite) {
2108 const auto &bufferManager = contextInterface.bufferManager();
2110 if (particles.m_sprite->clearDirty())
2113 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(particles.m_sprite);
2114 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, QSSGRenderableImage::Type::Diffuse, *particles.m_sprite, texture);
2115 firstImage = theImage;
2116 properties.m_isSpriteLinear.setValue(theGeneratedKey, texture.m_flags.isLinear());
2119 QSSGRenderableImage *colorTable =
nullptr;
2120 if (particles.m_colorTable) {
2121 const auto &bufferManager = contextInterface.bufferManager();
2123 if (particles.m_colorTable->clearDirty())
2126 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(particles.m_colorTable);
2128 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, QSSGRenderableImage::Type::Diffuse, *particles.m_colorTable, texture);
2129 colorTable = theImage;
2130 properties.m_isColorTableLinear.setValue(theGeneratedKey, texture.m_flags.isLinear());
2133 if (opacity > 0.0f && particles.m_particleBuffer.particleCount()) {
2134 auto *theRenderableObject = RENDER_FRAME_NEW<QSSGParticlesRenderable>(contextInterface,
2145 if (theRenderableObject) {
2146 if (theRenderableObject->renderableFlags.requiresScreenTexture())
2147 screenTextureObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2148 else if (theRenderableObject->renderableFlags.hasTransparency())
2149 transparentObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2151 opaqueObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2438void QSSGLayerRenderData::prepareForRender()
2440 QSSG_ASSERT_X(layerPrepResult.isNull(),
"Prep-result was not reset for render!", layerPrepResult = {});
2442 QRect theViewport(renderer->viewport());
2446 frameData.m_ctx = renderer->contextInterface();
2451 ps.viewport = {
float(theViewport.x()),
float(theViewport.y()),
float(theViewport.width()),
float(theViewport.height()), 0.0f, 1.0f };
2452 if (layer.scissorRect.isValid()) {
2453 ps.flags |= QSSGRhiGraphicsPipelineState::Flag::UsesScissor;
2454 ps.scissor = { layer.scissorRect.x(),
2455 theViewport.height() - (layer.scissorRect.y() + layer.scissorRect.height()),
2456 layer.scissorRect.width(),
2457 layer.scissorRect.height() };
2460 ps.depthFunc = QRhiGraphicsPipeline::LessOrEqual;
2461 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::BlendEnabled,
false);
2464 ps.polygonMode = layer.wireframeMode ? QRhiGraphicsPipeline::Line : QRhiGraphicsPipeline::Fill;
2466 bool wasDirty =
false;
2467 bool wasDataDirty =
false;
2468 wasDirty = layer.isDirty();
2470 const bool shouldDisableInternalPasses = (layer.renderOverrides & size_t(QSSGRenderLayer::RenderOverrides::DisableInternalPasses)) != 0;
2471 wasDirty |= (shouldDisableInternalPasses != disableMainPasses);
2472 disableMainPasses = shouldDisableInternalPasses;
2475 layerPrepResult = { theViewport, layer };
2478 const bool SSAOEnabled = layer.ssaoEnabled();
2479 layerPrepResult.flags.setRequiresSsaoPass(SSAOEnabled);
2480 features.set(QSSGShaderFeatures::Feature::Ssao, SSAOEnabled);
2483 bool requiresDepthTexture = SSAOEnabled;
2484 bool requiresNormalTexture =
false;
2485 bool requiresMotionVectorTexture =
false;
2486 for (QSSGRenderEffect *theEffect = layer.firstEffect; theEffect; theEffect = theEffect->m_nextEffect) {
2487 if (theEffect->isDirty()) {
2489 theEffect->clearDirty();
2491 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesDepthTexture))
2492 requiresDepthTexture =
true;
2493 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesNormalTexture))
2494 requiresNormalTexture =
true;
2495 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesMotionVectorTexture))
2496 requiresMotionVectorTexture =
true;
2499 const auto &rhiCtx = renderer->contextInterface()->rhiContext();
2500 orderIndependentTransparencyEnabled = (layer.oitMethod != QSSGRenderLayer::OITMethod::None);
2501 if (layer.oitMethod == QSSGRenderLayer::OITMethod::WeightedBlended) {
2502 orderIndependentTransparencyEnabled = rhiCtx->rhi()->isFeatureSupported(QRhi::PerRenderTargetBlending);
2503 if (rhiCtx->mainPassSampleCount() > 1)
2504 orderIndependentTransparencyEnabled &= rhiCtx->rhi()->isFeatureSupported(QRhi::TexelFetch) && rhiCtx->rhi()->isFeatureSupported(QRhi::SampleVariables);
2505 if (!orderIndependentTransparencyEnabled && !oitWarningUnsupportedShown) {
2506 qCWarning(lcQuick3DRender) <<
"WeightedBlended OIT is requested, but it is not supported.";
2507 oitWarningUnsupportedShown =
true;
2509 }
else if (layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList) {
2510 orderIndependentTransparencyEnabled = rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32UI, QRhiTexture::UsedWithLoadStore);
2511 if (rhiCtx->mainPassSampleCount() > 1)
2512 orderIndependentTransparencyEnabled &= rhiCtx->rhi()->isFeatureSupported(QRhi::SampleVariables);
2513 if (!orderIndependentTransparencyEnabled && !oitWarningUnsupportedShown) {
2514 qCWarning(lcQuick3DRender) <<
"LinkedList OIT is requested, but it is not supported.";
2515 oitWarningUnsupportedShown =
true;
2518 if (layer.oitMethodDirty) {
2519 oitRenderContext.reset();
2520 for (
auto &renderResult : renderResults)
2521 renderResult.reset();
2524 layerPrepResult.flags.setRequiresDepthTexture(requiresDepthTexture);
2526 layerPrepResult.flags.setRequiresNormalTexture(requiresNormalTexture);
2528 layerPrepResult.flags.setRequiresMotionVectorPass(requiresMotionVectorTexture);
2532 if (!layer.firstEffect)
2533 QSSGLayerRenderData::setTonemapFeatures(features, layer.tonemapMode);
2540 if (rhiCtx->rhi()->resourceLimit(QRhi::MaxUniformBufferRange) < REDUCED_MAX_LIGHT_COUNT_THRESHOLD_BYTES) {
2541 features.set(QSSGShaderFeatures::Feature::ReduceMaxNumLights,
true);
2542 static bool notified =
false;
2545 qCDebug(lcQuick3DRender,
"Qt Quick 3D maximum number of lights has been reduced from %d to %d due to the graphics driver's limitations",
2546 QSSG_MAX_NUM_LIGHTS, QSSG_REDUCED_MAX_NUM_LIGHTS);
2551 const auto &lightProbeSettings = layer.lightProbeSettings;
2552 if (layer.lightProbe) {
2553 if (layer.lightProbe->m_format == QSSGRenderTextureFormat::Unknown) {
2556 if (renderer->contextInterface()->rhiContext()->rhi()->isTextureFormatSupported(QRhiTexture::RGBA16F))
2557 layer.lightProbe->m_format = QSSGRenderTextureFormat::RGBA16F;
2559 layer.lightProbe->m_format = QSSGRenderTextureFormat::RGBE8;
2562 if (layer.lightProbe->clearDirty())
2563 wasDataDirty =
true;
2565 features.set(QSSGShaderFeatures::Feature::LightProbe,
true);
2566 features.set(QSSGShaderFeatures::Feature::IblOrientation, !lightProbeSettings.probeOrientation.isIdentity());
2567 if (layer.lightProbe->m_format.format == QSSGRenderTextureFormat::Format::RGBE8)
2568 features.set(QSSGShaderFeatures::Feature::RGBELightProbe,
true);
2570 }
else if (layer.skyMaterial) {
2571 if (layer.skyMaterial->enableIBL) {
2572 features.set(QSSGShaderFeatures::Feature::LightProbe,
true);
2573 features.set(QSSGShaderFeatures::Feature::IblOrientation, !lightProbeSettings.probeOrientation.isIdentity());
2575 layerPrepResult.flags.setRequiresSkyMaterialPass(
true);
2578 const bool forceIblExposureValues = (features.isSet(QSSGShaderFeatures::Feature::LightProbe)
2579 && layer.tonemapMode == QSSGRenderLayer::TonemapMode::Custom);
2580 features.set(QSSGShaderFeatures::Feature::ForceIblExposure, forceIblExposureValues);
2582 frameData.m_ctx->bufferManager()->setLightmapSource(layer.lightmapSource);
2586 version = nodeData->version();
2591 auto &globalTransforms = nodeData->globalTransforms;
2592 auto &globalOpacities = nodeData->globalOpacities;
2593 auto &instanceTransforms = nodeData->instanceTransforms;
2596 QSSGRenderDataHelpers::GlobalStateResultT globalStateResult = QSSGRenderDataHelpers::GlobalStateResult::None;
2598 const bool layerTreeWasDirty = layer.isDirty(QSSGRenderLayer::DirtyFlag::TreeDirty);
2599 layer.clearDirty(QSSGRenderLayer::DirtyFlag::TreeDirty);
2600 if (layerTreeWasDirty) {
2601 wasDataDirty =
true;
2602 layerNodes = nodeData->getLayerNodeView(layer);
2604 using GlobalStateResult = QSSGRenderDataHelpers::GlobalStateResult;
2606 constexpr QSSGRenderDataHelpers::GlobalStateResultT FilterAffectingChanges = GlobalStateResult::ActiveChanged
2607 | GlobalStateResult::TagChanged;
2608 bool sharedStateChanged =
false;
2609 for (
auto &node : layerNodes) {
2610 const auto result = QSSGRenderDataHelpers::updateGlobalNodeState(node, version);
2611 globalStateResult |= result;
2615 const bool affectsFilter = ((result & FilterAffectingChanges) != 0);
2616 const bool isShared = node->getGlobalState(QSSGRenderNode::GlobalState::Imported);
2617 sharedStateChanged |= (affectsFilter && isShared);
2620 if (sharedStateChanged)
2621 nodeData->bumpStateGeneration();
2623 bool transformAndOpacityDirty =
false;
2624 for (
auto &node : layerNodes)
2625 transformAndOpacityDirty |= QSSGRenderDataHelpers::calcGlobalNodeData<QSSGRenderDataHelpers::Strategy::Update>(node, version, globalTransforms, globalOpacities);
2628 if (transformAndOpacityDirty) {
2629 for (
const auto &node : layerNodes)
2630 wasDataDirty |= QSSGRenderDataHelpers::calcInstanceTransforms(node, version, globalTransforms, instanceTransforms);
2633 wasDataDirty |= transformAndOpacityDirty;
2640 const bool viewportVisibilityDirty = layer.isDirty(QSSGRenderLayer::DirtyFlag::VisibilityDirty);
2641 layer.clearDirty(QSSGRenderLayer::DirtyFlag::VisibilityDirty);
2642 if (viewportVisibilityDirty)
2643 wasDataDirty =
true;
2648 const bool hasExplicitCamera = (layer.explicitCameras.size() != 0);
2649 bool cameraLayerMaskDirty =
false;
2650 quint32 layerMask = QSSGRenderCamera::LayerMaskAll;
2651 if (hasExplicitCamera) {
2652 QSSGRenderCamera *explicitCamera = layer.explicitCameras[0];
2655 layerMask = explicitCamera->tag.value() | QSSGRenderCamera::ReservedLayerMask;
2656 cameraLayerMaskDirty = explicitCamera->isDirty(QSSGRenderCamera::DirtyFlag::LayerMaskDirty);
2657 explicitCamera->clearDirty(QSSGRenderCamera::DirtyFlag::LayerMaskDirty);
2661 const bool sharedStateDirty = (stateGeneration != nodeData->stateGeneration());
2662 stateGeneration = nodeData->stateGeneration();
2664 const bool restatNodes = (layerTreeWasDirty
2665 || (globalStateResult & (QSSGRenderDataHelpers::GlobalStateResult::ActiveChanged | QSSGRenderDataHelpers::GlobalStateResult::TagChanged))
2666 || cameraLayerMaskDirty
2667 || sharedStateDirty);
2670 updateFilteredLayerNodes(layerMask);
2676 QSSGRenderCamera::Configuration cameraConfig { renderer->dpr(), layer.isSsaaEnabled() ? layer.ssaaMultiplier : 1.0f };
2677 renderedCameras.clear();
2678 if (!layer.explicitCameras.isEmpty()) {
2679 for (QSSGRenderCamera *cam : std::as_const(layer.explicitCameras)) {
2681 if (cam->getGlobalState(QSSGRenderCamera::GlobalState::Active)) {
2682 const bool computeFrustumSucceeded = cam->calculateProjection(theViewport, cameraConfig);
2683 if (Q_LIKELY(computeFrustumSucceeded))
2684 renderedCameras.append(cam);
2686 qCCritical(INTERNAL_ERROR,
"Failed to calculate camera frustum");
2690 }
else if (QSSG_GUARD_X(layer.viewCount == 1,
"Multiview rendering requires explicit cameras to be set!.")) {
2695 for (
auto iter = camerasView.begin(); renderedCameras.isEmpty() && iter != camerasView.end(); iter++) {
2696 QSSGRenderCamera *theCamera = *iter;
2697 if (theCamera->getGlobalState(QSSGRenderCamera::GlobalState::Active)) {
2698 const bool computeFrustumSucceeded = theCamera->calculateProjection(theViewport, cameraConfig);
2699 if (Q_LIKELY(computeFrustumSucceeded))
2700 renderedCameras.append(theCamera);
2702 qCCritical(INTERNAL_ERROR,
"Failed to calculate camera frustum");
2710 if (renderedCameras.size() > 0 && (renderedCameras[0]->layerMask & QSSGRenderCamera::LayerMaskUserAll) != QSSGRenderCamera::LayerMaskUserAll) {
2711 if (!nonExplicitCameraWithLayerMaskWarningShown) {
2712 nonExplicitCameraWithLayerMaskWarningShown =
true;
2713 qWarning() <<
"Scenes with non-explicit cameras with a layer detected!"
2714 " Set the camera explicitly to avoid unnecessary evaluation of scene nodes!";
2718 layerMask = renderedCameras[0]->layerMask;
2719 updateFilteredLayerNodes(layerMask);
2723 float meshLodThreshold = 1.0f;
2724 if (!renderedCameras.isEmpty())
2725 meshLodThreshold = renderedCameras[0]->levelOfDetailPixelThreshold / theViewport.width();
2727 layer.renderedCamerasMutex.lock();
2728 layer.renderedCameras = renderedCameras;
2729 layer.renderedCamerasMutex.unlock();
2732 const QSSGRenderCameraDataList &renderCameraData = getCachedCameraDatas();
2733 modelData->updateModelData(modelsView, renderer, renderCameraData);
2736 item2DData->updateItem2DData(item2DsView, renderer, renderCameraData);
2739 prepareResourceLoaders();
2742 updateDirtySkeletons(*
this, modelsView);
2745 int directionalLightsCount = 0;
2746 int positionalLightsCount = 0;
2747 const int maxLightCount = effectiveMaxLightCount(features);
2748 const int maxDirectionalLights = effectiveMaxDirectionalLightCount(features);
2749 QSSGShaderLightList renderableLights;
2750 int shadowMapCount = 0;
2751 bool hasScopedLights =
false;
2757 auto it = std::make_reverse_iterator(lightsView.end());
2758 const auto end = it + qMin(maxLightCount, lightsView.size());
2759 for (; it != end; ++it) {
2760 QSSGRenderLight *renderLight = (*it);
2761 QMatrix4x4 renderLightTransform = getGlobalTransform(*renderLight);
2762 if (renderLight->type == QSSGRenderGraphObject::Type::DirectionalLight)
2763 directionalLightsCount++;
2765 positionalLightsCount++;
2767 if (positionalLightsCount > maxLightCount)
2769 if (directionalLightsCount > maxDirectionalLights)
2773 hasScopedLights |= (renderLight->m_scope !=
nullptr);
2774 const bool castShadows = renderLight->m_castShadow && !renderLight->m_fullyBaked;
2775 shadowMapCount +=
int(castShadows);
2776 const auto &direction = renderLight->getScalingCorrectDirection(renderLightTransform);
2777 renderableLights.push_back(QSSGShaderLight{ renderLight, castShadows, direction });
2781 const bool showLightCountWarning = !tooManyLightsWarningShown && (positionalLightsCount > maxLightCount);
2782 if (showLightCountWarning) {
2783 qWarning(
"Too many lights in scene, maximum is %d", maxLightCount);
2784 tooManyLightsWarningShown =
true;
2787 const bool showDirectionalLightCountWarning = !tooManyDirectionalLightsWarningShown && (directionalLightsCount > maxDirectionalLights);
2788 if (showDirectionalLightCountWarning) {
2789 qWarning(
"Too many directional lights in scene, maximum is %d", maxDirectionalLights);
2790 tooManyDirectionalLightsWarningShown =
true;
2793 if (shadowMapCount > 0) {
2794 requestShadowMapManager();
2795 layerPrepResult.flags.setRequiresShadowMapPass(
true);
2800 features.set(QSSGShaderFeatures::Feature::Ssm,
true);
2801 shadowMapManager->addShadowMaps(renderableLights);
2802 }
else if (shadowMapManager) {
2804 shadowMapManager->releaseCachedResources();
2810 QSSG_ASSERT(globalLights.isEmpty(), globalLights.clear());
2811 if (hasScopedLights) {
2812 for (
const auto &shaderLight : std::as_const(renderableLights)) {
2813 if (!shaderLight.light->m_scope)
2814 globalLights.push_back(shaderLight);
2817 const auto prepareLightsWithScopedLights = [&renderableLights,
this](QVector<QSSGRenderableNodeEntry> &renderableNodes) {
2818 for (qint32 idx = 0, end = renderableNodes.size(); idx < end; ++idx) {
2819 QSSGRenderableNodeEntry &theNodeEntry(renderableNodes[idx]);
2820 QSSGShaderLightList filteredLights;
2821 for (
const auto &light : std::as_const(renderableLights)) {
2822 if (light.light->m_scope && !scopeLight(theNodeEntry.node, light.light->m_scope))
2824 filteredLights.push_back(light);
2827 if (filteredLights.isEmpty()) {
2828 theNodeEntry.lights = QSSGDataView(globalLights);
2833 auto customLightList = RENDER_FRAME_NEW_BUFFER<QSSGShaderLight>(*renderer->contextInterface(), filteredLights.size());
2834 std::copy(filteredLights.cbegin(), filteredLights.cend(), customLightList.begin());
2835 theNodeEntry.lights = customLightList;
2840 prepareLightsWithScopedLights(renderableModels);
2841 prepareLightsWithScopedLights(renderableParticles);
2843 globalLights = renderableLights;
2845 const auto prepareLights = [
this](QVector<QSSGRenderableNodeEntry> &renderableNodes) {
2846 for (qint32 idx = 0, end = renderableNodes.size(); idx < end; ++idx) {
2847 QSSGRenderableNodeEntry &theNodeEntry(renderableNodes[idx]);
2848 theNodeEntry.lights = QSSGDataView(globalLights);
2852 prepareLights(renderableModels);
2853 prepareLights(renderableParticles);
2859 Q_STATIC_ASSERT(USERPASSES == size_t(QSSGRenderLayer::RenderExtensionStage::Count));
2860 for (size_t i = 0; i != size_t(QSSGRenderLayer::RenderExtensionStage::Count); ++i) {
2861 const auto &renderExtensions = layer.renderExtensions[i];
2862 auto &userPass = userPasses[i];
2863 for (
auto rit = renderExtensions.crbegin(), rend = renderExtensions.crend(); rit != rend; ++rit) {
2864 if ((*rit)->prepareData(frameData)) {
2866 userPass.extensions.push_back(*rit);
2874 const auto &userRenderPassManager = requestUserRenderPassManager();
2875 userRenderPassManager->updateUserPassOrder(layerTreeWasDirty);
2876 userRenderPasses.userPasses = userRenderPassManager->scheduledUserPasses();
2879 auto &opaqueObjects = opaqueObjectStore[0];
2880 auto &transparentObjects = transparentObjectStore[0];
2881 auto &screenTextureObjects = screenTextureObjectStore[0];
2883 if (!renderedCameras.isEmpty()) {
2884 wasDirty |= prepareModelsForRender(*renderer->contextInterface(), renderableModels, layerPrepResult.flags, renderedCameras, getCachedCameraDatas(), modelContexts, opaqueObjects, transparentObjects, screenTextureObjects, meshLodThreshold);
2885 if (particlesEnabled) {
2886 const auto &cameraDatas = getCachedCameraDatas();
2887 wasDirty |= prepareParticlesForRender(renderableParticles, cameraDatas[0], layerPrepResult.flags);
2890 wasDirty |= (item2DsView.size() != 0);
2892 if (orderIndependentTransparencyEnabled) {
2894 if (transparentObjects.size() > 0 && !layerPrepResult.flags.hasCustomBlendMode()) {
2895 if (layer.oitMethod == QSSGRenderLayer::OITMethod::WeightedBlended) {
2896 if (rhiCtx->mainPassSampleCount() > 1)
2897 layerPrepResult.flags.setRequiresDepthTextureMS(
true);
2899 layerPrepResult.flags.setRequiresDepthTexture(
true);
2902 orderIndependentTransparencyEnabled =
false;
2903 if (!oitWarningInvalidBlendModeShown) {
2904 qCWarning(lcQuick3DRender) <<
"Order Independent Transparency requested, but disabled due to invalid blend modes.";
2905 qCWarning(lcQuick3DRender) <<
"Use SourceOver blend mode for Order Independent Transparency.";
2906 oitWarningInvalidBlendModeShown =
true;
2910 layer.oitMethodDirty =
false;
2912 prepareReflectionProbesForRender();
2914 wasDirty = wasDirty || wasDataDirty;
2915 layerPrepResult.flags.setWasDirty(wasDirty);
2916 layerPrepResult.flags.setLayerDataDirty(wasDataDirty);
2919 const bool animating = wasDirty;
2921 layer.progAAPassIndex = 0;
2923 const bool progressiveAA = layer.isProgressiveAAEnabled() && !animating;
2924 layer.progressiveAAIsActive = progressiveAA;
2925 const bool temporalAA = layer.isTemporalAAEnabled() && !progressiveAA;
2927 layer.temporalAAIsActive = temporalAA;
2929 QVector2D vertexOffsetsAA;
2931 if (progressiveAA && layer.progAAPassIndex > 0 && layer.progAAPassIndex < quint32(layer.antialiasingQuality)) {
2932 int idx = layer.progAAPassIndex - 1;
2933 vertexOffsetsAA = s_ProgressiveAAVertexOffsets[idx] / QVector2D{
float(theViewport.width()/2.0),
float(theViewport.height()/2.0) };
2937 if (layer.temporalAAMode == QSSGRenderLayer::TAAMode::MotionVector && layer.tempAAPassIndex > 0) {
2938 if (layer.tempAAPassIndex >= quint32(MAX_AA_LEVELS) + 1)
2939 layer.tempAAPassIndex = 1;
2940 int idx = layer.tempAAPassIndex - 1;
2941 vertexOffsetsAA = s_ProgressiveAAVertexOffsets[idx] / QVector2D{
float(theViewport.width()/2.0),
float(theViewport.height()/2.0) };
2942 layer.currentAndLastJitter = QVector4D(vertexOffsetsAA, layer.currentAndLastJitter.x(), layer.currentAndLastJitter.y());
2943 layerPrepResult.flags.setRequiresMotionVectorPass(
true);
2944 layerPrepResult.flags.setRequiresDepthTexture(
true);
2946 const int t = 1 - 2 * (layer.tempAAPassIndex % 2);
2947 const float f = t * layer.temporalAAStrength;
2948 vertexOffsetsAA = { f /
float(theViewport.width()/2.0), f /
float(theViewport.height()/2.0) };
2952 if (!renderedCameras.isEmpty()) {
2953 if (temporalAA || progressiveAA ) {
2954 QMatrix4x4 offsetProjection = renderedCameras[0]->projection;
2955 QMatrix4x4 invProjection = renderedCameras[0]->projection.inverted();
2956 if (renderedCameras[0]->type == QSSGRenderCamera::Type::OrthographicCamera) {
2957 offsetProjection(0, 3) -= vertexOffsetsAA.x();
2958 offsetProjection(1, 3) -= vertexOffsetsAA.y();
2959 }
else if (renderedCameras[0]->type == QSSGRenderCamera::Type::PerspectiveCamera) {
2960 offsetProjection(0, 2) += vertexOffsetsAA.x();
2961 offsetProjection(1, 2) += vertexOffsetsAA.y();
2963 for (
auto &modelContext : std::as_const(modelContexts)) {
2964 for (
int mvpIdx = 0; mvpIdx < renderedCameras.count(); ++mvpIdx)
2965 modelContext->modelViewProjections[mvpIdx] = offsetProjection * invProjection * modelContext->modelViewProjections[mvpIdx];
2970 const bool hasItem2Ds = (item2DsView.size() > 0);
2971 const bool layerEnableDepthTest = layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest);
2972 const bool layerEnabledDepthPrePass = layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthPrePass);
2973 const bool depthTestEnableDefault = layerEnableDepthTest && (!opaqueObjects.isEmpty() || depthPrepassObjectsState || hasDepthWriteObjects);
2974 const bool zPrePassForced = (depthPrepassObjectsState != 0);
2975 zPrePassActive = zPrePassForced || (layerEnabledDepthPrePass && layerEnableDepthTest && (hasDepthWriteObjects || hasItem2Ds));
2976 const bool depthWriteEnableDefault = depthTestEnableDefault && (!layerEnabledDepthPrePass || !zPrePassActive);
2978 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthTestEnabled, depthTestEnableDefault);
2979 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled, depthWriteEnableDefault);
2983 layerPrepResult.setState(QSSGLayerRenderPreparationResult::State::Done);
2986 QSSG_ASSERT(activePasses.isEmpty(), activePasses.clear());
2990 if (layerPrepResult.flags.requiresDepthTexture())
2991 activePasses.push_back(&depthMapPass);
2992 if (layerPrepResult.flags.requiresDepthTextureMS())
2993 activePasses.push_back(&depthMapPassMS);
2995 if (layerPrepResult.flags.requiresNormalTexture())
2996 activePasses.push_back(&normalPass);
2999 if (layerPrepResult.flags.requiresSsaoPass())
3000 activePasses.push_back(&ssaoMapPass);
3003 if (layerPrepResult.flags.requiresShadowMapPass())
3004 activePasses.push_back(&shadowMapPass);
3006 if (zPrePassActive && !disableMainPasses)
3007 activePasses.push_back(&zPrePassPass);
3010 if (layerPrepResult.flags.requiresScreenTexture())
3011 activePasses.push_back(&screenMapPass);
3014 if (layerPrepResult.flags.requiresSkyMaterialPass())
3015 activePasses.push_back(&skyMaterialPass);
3018 if (reflectionProbesView.size() != 0)
3019 activePasses.push_back(&reflectionMapPass);
3021 auto &textureExtensionPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::TextureProviders)];
3022 if (textureExtensionPass.hasData())
3023 activePasses.push_back(&textureExtensionPass);
3025 auto &underlayPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::Underlay)];
3026 if (underlayPass.hasData())
3027 activePasses.push_back(&underlayPass);
3030 if (userRenderPasses.hasData())
3031 activePasses.push_back(&userRenderPasses);
3033 const bool hasOpaqueObjects = (opaqueObjects.size() > 0);
3035 if (hasOpaqueObjects && !disableMainPasses)
3036 activePasses.push_back(&opaquePass);
3039 if (layerPrepResult.flags.requiresMotionVectorPass())
3040 activePasses.push_back(&motionVectorMapPass);
3044 if (renderer->contextInterface()->rhiContext()->rhi()->isFeatureSupported(QRhi::TexelFetch)) {
3045 if (layer.background == QSSGRenderLayer::Background::SkyBoxCubeMap && layer.skyBoxCubeMap && !disableMainPasses)
3046 activePasses.push_back(&skyboxCubeMapPass);
3047 else if (layer.background == QSSGRenderLayer::Background::SkyBox && layer.lightProbe && !disableMainPasses)
3048 activePasses.push_back(&skyboxPass);
3049 else if (layer.background == QSSGRenderLayer::Background::SkyMaterial && layer.skyMaterial && !disableMainPasses) {
3050 if (layer.skyMaterial->skyboxMode != QSSGRenderSkyMaterial::SkyboxMode::Cubemap)
3051 activePasses.push_back(&skyMaterialBackgroundPass);
3053 activePasses.push_back(&skyboxPass);
3057 if (hasItem2Ds && !disableMainPasses)
3058 activePasses.push_back(&item2DPass);
3060 if (layerPrepResult.flags.requiresScreenTexture())
3061 activePasses.push_back(&reflectionPass);
3064 if ((transparentObjects.size() > 0 || (!layerEnableDepthTest && hasOpaqueObjects)) && !disableMainPasses) {
3065 if (orderIndependentTransparencyEnabled) {
3066 activePasses.push_back(&oitRenderPass);
3067 activePasses.push_back(&oitCompositePass);
3068 oitRenderPass.setMethod(layer.oitMethod);
3069 oitCompositePass.setMethod(layer.oitMethod);
3071 activePasses.push_back(&transparentPass);
3075 auto &overlayPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::Overlay)];
3076 if (overlayPass.hasData())
3077 activePasses.push_back(&overlayPass);
3079 if (layer.gridEnabled)
3080 activePasses.push_back(&infiniteGridPass);
3082 if (
const auto &dbgDrawSystem = renderer->contextInterface()->debugDrawSystem(); dbgDrawSystem && dbgDrawSystem->isEnabled() && !disableMainPasses)
3083 activePasses.push_back(&debugDrawPass);