MeshFeatureProcessor.cpp 161 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Mesh/MeshFeatureProcessor.h>
  9. #include <Mesh/StreamBufferViewsBuilder.h>
  10. #include <Atom/Feature/CoreLights/PhotometricValue.h>
  11. #include <Atom/Feature/Material/ConvertEmissiveUnitFunctor.h>
  12. #include <Atom/Feature/Mesh/MeshCommon.h>
  13. #include <Atom/Feature/Mesh/ModelReloaderSystemInterface.h>
  14. #include <Atom/Feature/RenderCommon.h>
  15. #include <Atom/Feature/Utils/GpuBufferHandler.h>
  16. #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h>
  17. #include <Atom/RHI/RHISystemInterface.h>
  18. #include <Atom/RHI/RHIUtils.h>
  19. #include <Atom/RPI.Public/AssetQuality.h>
  20. #include <Atom/RPI.Public/Culling.h>
  21. #include <Atom/RPI.Public/Model/ModelLodUtils.h>
  22. #include <Atom/RPI.Public/Model/ModelTagSystemComponent.h>
  23. #include <Atom/RPI.Public/RPIUtils.h>
  24. #include <Atom/RPI.Public/Scene.h>
  25. #include <Atom/Utils/StableDynamicArray.h>
  26. #include <ReflectionProbe/ReflectionProbeFeatureProcessor.h>
  27. #include <Atom/RPI.Reflect/Model/ModelAssetCreator.h>
  28. #include <AzFramework/Asset/AssetSystemBus.h>
  29. #include <AtomCore/Instance/InstanceDatabase.h>
  30. #include <AzCore/Asset/AssetCommon.h>
  31. #include <AzCore/Console/IConsole.h>
  32. #include <AzCore/Jobs/Algorithms.h>
  33. #include <AzCore/Jobs/JobCompletion.h>
  34. #include <AzCore/Jobs/JobFunction.h>
  35. #include <AzCore/Math/ShapeIntersection.h>
  36. #include <AzCore/Name/NameDictionary.h>
  37. #include <AzCore/RTTI/RTTI.h>
  38. #include <AzCore/RTTI/TypeInfo.h>
  39. #include <AzCore/Serialization/SerializeContext.h>
  40. #include <algorithm>
  41. namespace AZ
  42. {
  43. namespace Render
  44. {
  45. static AZ::Name s_o_meshUseForwardPassIBLSpecular_Name =
  46. AZ::Name::FromStringLiteral("o_meshUseForwardPassIBLSpecular", AZ::Interface<AZ::NameDictionary>::Get());
  47. static AZ::Name s_Manual_Name = AZ::Name::FromStringLiteral("Manual", AZ::Interface<AZ::NameDictionary>::Get());
  48. static AZ::Name s_Multiply_Name = AZ::Name::FromStringLiteral("Multiply", AZ::Interface<AZ::NameDictionary>::Get());
  49. static AZ::Name s_BaseColorTint_Name = AZ::Name::FromStringLiteral("BaseColorTint", AZ::Interface<AZ::NameDictionary>::Get());
  50. static AZ::Name s_BaseColor_Name = AZ::Name::FromStringLiteral("BaseColor", AZ::Interface<AZ::NameDictionary>::Get());
  51. static AZ::Name s_baseColor_color_Name = AZ::Name::FromStringLiteral("baseColor.color", AZ::Interface<AZ::NameDictionary>::Get());
  52. static AZ::Name s_baseColor_factor_Name = AZ::Name::FromStringLiteral("baseColor.factor", AZ::Interface<AZ::NameDictionary>::Get());
  53. static AZ::Name s_baseColor_useTexture_Name =
  54. AZ::Name::FromStringLiteral("baseColor.useTexture", AZ::Interface<AZ::NameDictionary>::Get());
  55. static AZ::Name s_metallic_factor_Name = AZ::Name::FromStringLiteral("metallic.factor", AZ::Interface<AZ::NameDictionary>::Get());
  56. static AZ::Name s_roughness_factor_Name = AZ::Name::FromStringLiteral("roughness.factor", AZ::Interface<AZ::NameDictionary>::Get());
  57. static AZ::Name s_emissive_enable_Name = AZ::Name::FromStringLiteral("emissive.enable", AZ::Interface<AZ::NameDictionary>::Get());
  58. static AZ::Name s_emissive_color_Name = AZ::Name::FromStringLiteral("emissive.color", AZ::Interface<AZ::NameDictionary>::Get());
  59. static AZ::Name s_emissive_intensity_Name =
  60. AZ::Name::FromStringLiteral("emissive.intensity", AZ::Interface<AZ::NameDictionary>::Get());
  61. static AZ::Name s_emissive_unit_Name = AZ::Name::FromStringLiteral("emissive.unit", AZ::Interface<AZ::NameDictionary>::Get());
  62. static AZ::Name s_baseColor_textureMap_Name =
  63. AZ::Name::FromStringLiteral("baseColor.textureMap", AZ::Interface<AZ::NameDictionary>::Get());
  64. static AZ::Name s_normal_textureMap_Name =
  65. AZ::Name::FromStringLiteral("normal.textureMap", AZ::Interface<AZ::NameDictionary>::Get());
  66. static AZ::Name s_metallic_textureMap_Name =
  67. AZ::Name::FromStringLiteral("metallic.textureMap", AZ::Interface<AZ::NameDictionary>::Get());
  68. static AZ::Name s_roughness_textureMap_Name =
  69. AZ::Name::FromStringLiteral("roughness.textureMap", AZ::Interface<AZ::NameDictionary>::Get());
  70. static AZ::Name s_irradiance_irradianceColorSource_Name =
  71. AZ::Name::FromStringLiteral("irradiance.irradianceColorSource", AZ::Interface<AZ::NameDictionary>::Get());
  72. static AZ::Name s_emissive_textureMap_Name =
  73. AZ::Name::FromStringLiteral("emissive.textureMap", AZ::Interface<AZ::NameDictionary>::Get());
  74. static AZ::Name s_irradiance_manualColor_Name =
  75. AZ::Name::FromStringLiteral("irradiance.manualColor", AZ::Interface<AZ::NameDictionary>::Get());
  76. static AZ::Name s_irradiance_color_Name = AZ::Name::FromStringLiteral("irradiance.color", AZ::Interface<AZ::NameDictionary>::Get());
  77. static AZ::Name s_baseColor_textureBlendMode_Name =
  78. AZ::Name::FromStringLiteral("baseColor.textureBlendMode", AZ::Interface<AZ::NameDictionary>::Get());
  79. static AZ::Name s_irradiance_factor_Name =
  80. AZ::Name::FromStringLiteral("irradiance.factor", AZ::Interface<AZ::NameDictionary>::Get());
  81. static AZ::Name s_opacity_mode_Name = AZ::Name::FromStringLiteral("opacity.mode", AZ::Interface<AZ::NameDictionary>::Get());
  82. static AZ::Name s_opacity_factor_Name = AZ::Name::FromStringLiteral("opacity.factor", AZ::Interface<AZ::NameDictionary>::Get());
  83. static AZ::Name s_m_rootConstantInstanceDataOffset_Name =
  84. AZ::Name::FromStringLiteral("m_rootConstantInstanceDataOffset", AZ::Interface<AZ::NameDictionary>::Get());
  85. static AZ::Name s_o_meshInstancingIsEnabled_Name =
  86. AZ::Name::FromStringLiteral("o_meshInstancingIsEnabled", AZ::Interface<AZ::NameDictionary>::Get());
  87. static AZ::Name s_transparent_Name = AZ::Name::FromStringLiteral("transparent", AZ::Interface<AZ::NameDictionary>::Get());
  88. static AZ::Name s_block_silhouette_Name = AZ::Name::FromStringLiteral("silhouette.blockSilhouette", AZ::Interface<AZ::NameDictionary>::Get());
  89. static ModelDataInstance& ToModelDataInstance(const MeshFeatureProcessorInterface::MeshHandle& meshHandle)
  90. {
  91. return *azrtti_cast<ModelDataInstance*>(&*meshHandle);
  92. }
  93. static void CacheRootConstantInterval(MeshInstanceGroupData& meshInstanceGroupData)
  94. {
  95. meshInstanceGroupData.m_drawRootConstantOffset = 0;
  96. RHI::ConstPtr<RHI::ConstantsLayout> rootConstantsLayout = meshInstanceGroupData.m_drawPacket.GetRootConstantsLayout();
  97. if (rootConstantsLayout)
  98. {
  99. // Get the root constant layout
  100. RHI::ShaderInputConstantIndex shaderInputIndex =
  101. rootConstantsLayout->FindShaderInputIndex(s_m_rootConstantInstanceDataOffset_Name);
  102. if (shaderInputIndex.IsValid())
  103. {
  104. RHI::Interval interval = rootConstantsLayout->GetInterval(shaderInputIndex);
  105. meshInstanceGroupData.m_drawRootConstantOffset = interval.m_min;
  106. }
  107. }
  108. }
  109. void MeshFeatureProcessor::Reflect(ReflectContext* context)
  110. {
  111. if (auto* serializeContext = azrtti_cast<SerializeContext*>(context))
  112. {
  113. serializeContext->Class<MeshFeatureProcessor, FeatureProcessor>()->Version(1);
  114. }
  115. }
  116. void MeshFeatureProcessor::Activate()
  117. {
  118. m_transformService = GetParentScene()->GetFeatureProcessor<TransformServiceFeatureProcessor>();
  119. AZ_Assert(m_transformService, "MeshFeatureProcessor requires a TransformServiceFeatureProcessor on its parent scene.");
  120. m_rayTracingFeatureProcessor = GetParentScene()->GetFeatureProcessor<RayTracingFeatureProcessor>();
  121. m_reflectionProbeFeatureProcessor = GetParentScene()->GetFeatureProcessor<ReflectionProbeFeatureProcessor>();
  122. m_handleGlobalShaderOptionUpdate = RPI::ShaderSystemInterface::GlobalShaderOptionUpdatedEvent::Handler
  123. {
  124. [this](const AZ::Name&, RPI::ShaderOptionValue) { m_forceRebuildDrawPackets = true; }
  125. };
  126. RPI::ShaderSystemInterface::Get()->Connect(m_handleGlobalShaderOptionUpdate);
  127. EnableSceneNotification();
  128. // Must read cvar from AZ::Console due to static variable in multiple libraries, see ghi-5537
  129. bool enablePerMeshShaderOptionFlagsCvar = false;
  130. if (auto* console = AZ::Interface<AZ::IConsole>::Get(); console != nullptr)
  131. {
  132. console->GetCvarValue("r_enablePerMeshShaderOptionFlags", enablePerMeshShaderOptionFlagsCvar);
  133. // push the cvars value so anything in this dll can access it directly.
  134. console->PerformCommand(AZStd::string::format("r_enablePerMeshShaderOptionFlags %s", enablePerMeshShaderOptionFlagsCvar ? "true" : "false").c_str());
  135. }
  136. m_meshMovedFlag = GetParentScene()->GetViewTagBitRegistry().AcquireTag(MeshCommon::MeshMovedName);
  137. m_meshMotionDrawListTag = AZ::RHI::RHISystemInterface::Get()->GetDrawListTagRegistry()->AcquireTag(MeshCommon::MotionDrawListTagName);
  138. m_transparentDrawListTag = AZ::RHI::RHISystemInterface::Get()->GetDrawListTagRegistry()->AcquireTag(s_transparent_Name);
  139. if (auto* console = AZ::Interface<AZ::IConsole>::Get(); console != nullptr)
  140. {
  141. console->GetCvarValue("r_meshInstancingEnabled", m_enableMeshInstancing);
  142. // push the cvars value so anything in this dll can access it directly.
  143. console->PerformCommand(
  144. AZStd::string::format("r_meshInstancingEnabled %s", m_enableMeshInstancing ? "true" : "false")
  145. .c_str());
  146. console->GetCvarValue("r_meshInstancingEnabledForTransparentObjects", m_enableMeshInstancingForTransparentObjects);
  147. // push the cvars value so anything in this dll can access it directly.
  148. console->PerformCommand(
  149. AZStd::string::format(
  150. "r_meshInstancingEnabledForTransparentObjects %s", m_enableMeshInstancingForTransparentObjects ? "true" : "false")
  151. .c_str());
  152. size_t meshInstancingBucketSortScatterBatchSize;
  153. console->GetCvarValue("r_meshInstancingBucketSortScatterBatchSize", meshInstancingBucketSortScatterBatchSize);
  154. // push the cvars value so anything in this dll can access it directly.
  155. console->PerformCommand(
  156. AZStd::string::format(
  157. "r_meshInstancingBucketSortScatterBatchSize %zu", meshInstancingBucketSortScatterBatchSize)
  158. .c_str());
  159. }
  160. }
  161. void MeshFeatureProcessor::Deactivate()
  162. {
  163. m_flagRegistry.reset();
  164. m_handleGlobalShaderOptionUpdate.Disconnect();
  165. DisableSceneNotification();
  166. AZ_Warning("MeshFeatureProcessor", m_modelData.size() == 0,
  167. "Deactivating the MeshFeatureProcessor, but there are still outstanding mesh handles.\n"
  168. );
  169. m_transformService = nullptr;
  170. m_rayTracingFeatureProcessor = nullptr;
  171. m_reflectionProbeFeatureProcessor = nullptr;
  172. m_forceRebuildDrawPackets = false;
  173. GetParentScene()->GetViewTagBitRegistry().ReleaseTag(m_meshMovedFlag);
  174. RHI::RHISystemInterface::Get()->GetDrawListTagRegistry()->ReleaseTag(m_meshMotionDrawListTag);
  175. RHI::RHISystemInterface::Get()->GetDrawListTagRegistry()->ReleaseTag(m_transparentDrawListTag);
  176. }
  177. TransformServiceFeatureProcessorInterface::ObjectId MeshFeatureProcessor::GetObjectId(const MeshHandle& meshHandle) const
  178. {
  179. if (meshHandle.IsValid())
  180. {
  181. return ToModelDataInstance(meshHandle).m_objectId;
  182. }
  183. return TransformServiceFeatureProcessorInterface::ObjectId::Null;
  184. }
  185. void MeshFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet)
  186. {
  187. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: Simulate");
  188. AZ::Job* parentJob = packet.m_parentJob;
  189. AZStd::concurrency_check_scope scopeCheck(m_meshDataChecker);
  190. // If the instancing cvar has changed, we need to re-initalize the ModelDataInstances
  191. CheckForInstancingCVarChange();
  192. AZStd::vector<Job*> initJobQueue = CreateInitJobQueue();
  193. AZStd::vector<Job*> updateCullingJobQueue = CreateUpdateCullingJobQueue();
  194. if (!r_meshInstancingEnabled)
  195. {
  196. // There's no need for all the init jobs to finish before any of the update culling jobs are run.
  197. // Any update culling job can run once it's corresponding init job is done. So instead of separating the jobs
  198. // entirely, use individual job dependencies to synchronize them. This performs better than having a big sync between them
  199. ExecuteCombinedJobQueue(initJobQueue, updateCullingJobQueue, parentJob);
  200. }
  201. else
  202. {
  203. ExecuteSimulateJobQueue(initJobQueue, parentJob);
  204. // Per-InstanceGroup work must be done after the Init jobs are complete, because the init jobs will determine which instance
  205. // group each mesh belongs to and populate those instance groups
  206. // Note: the Per-InstanceGroup jobs need to be created after init jobs because it's possible new instance groups are created in init jobs
  207. AZStd::vector<Job*> perInstanceGroupJobQueue = CreatePerInstanceGroupJobQueue();
  208. ExecuteSimulateJobQueue(perInstanceGroupJobQueue, parentJob);
  209. // Updating the culling scene must happen after the per-instance group work is done
  210. // because the per-instance group work will update the draw packets.
  211. ExecuteSimulateJobQueue(updateCullingJobQueue, parentJob);
  212. }
  213. m_forceRebuildDrawPackets = false;
  214. }
  215. void MeshFeatureProcessor::CheckForInstancingCVarChange()
  216. {
  217. if (m_enableMeshInstancing != r_meshInstancingEnabled || m_enableMeshInstancingForTransparentObjects != r_meshInstancingEnabledForTransparentObjects)
  218. {
  219. // DeInit and re-init every object
  220. for (auto& modelDataInstance : m_modelData)
  221. {
  222. modelDataInstance.ReInit(this);
  223. }
  224. m_enableMeshInstancing = r_meshInstancingEnabled;
  225. m_enableMeshInstancingForTransparentObjects = r_meshInstancingEnabledForTransparentObjects;
  226. }
  227. }
  228. AZStd::vector<Job*> MeshFeatureProcessor::CreatePerInstanceGroupJobQueue()
  229. {
  230. const auto instanceManagerRanges = m_meshInstanceManager.GetParallelRanges();
  231. AZStd::vector<Job*> perInstanceGroupJobQueue;
  232. perInstanceGroupJobQueue.reserve(instanceManagerRanges.size());
  233. RPI::Scene* scene = GetParentScene();
  234. for (const auto& iteratorRange : instanceManagerRanges)
  235. {
  236. const auto perInstanceGroupJobLambda = [this, scene, iteratorRange]() -> void
  237. {
  238. AZ_PROFILE_SCOPE(AzRender, "MeshFeatureProcessor: Simulate: PerInstanceGroupUpdate");
  239. for (auto instanceGroupDataIter = iteratorRange.m_begin; instanceGroupDataIter != iteratorRange.m_end;
  240. ++instanceGroupDataIter)
  241. {
  242. if (instanceGroupDataIter->UpdateDrawPacket(*scene, m_forceRebuildDrawPackets))
  243. {
  244. // We're going to need an interval for the root constant data that we update every frame for each draw item, so
  245. // cache that here
  246. CacheRootConstantInterval(*instanceGroupDataIter);
  247. }
  248. }
  249. };
  250. Job* executePerInstanceGroupJob =
  251. aznew JobFunction<decltype(perInstanceGroupJobLambda)>(perInstanceGroupJobLambda, true, nullptr); // Auto-deletes
  252. perInstanceGroupJobQueue.push_back(executePerInstanceGroupJob);
  253. }
  254. return perInstanceGroupJobQueue;
  255. }
  256. AZStd::vector<Job*> MeshFeatureProcessor::CreateInitJobQueue()
  257. {
  258. const auto iteratorRanges = m_modelData.GetParallelRanges();
  259. AZStd::vector<Job*> initJobQueue;
  260. initJobQueue.reserve(iteratorRanges.size());
  261. bool removePerMeshShaderOptionFlags = !r_enablePerMeshShaderOptionFlags && m_enablePerMeshShaderOptionFlags;
  262. for (const auto& iteratorRange : iteratorRanges)
  263. {
  264. const auto initJobLambda = [this, iteratorRange, removePerMeshShaderOptionFlags]() -> void
  265. {
  266. AZ_PROFILE_SCOPE(AzRender, "MeshFeatureProcessor: Simulate: Init");
  267. for (auto modelDataIter = iteratorRange.m_begin; modelDataIter != iteratorRange.m_end; ++modelDataIter)
  268. {
  269. if (!modelDataIter->m_model)
  270. {
  271. continue; // model not loaded yet
  272. }
  273. if (!modelDataIter->m_flags.m_visible)
  274. {
  275. continue;
  276. }
  277. if (modelDataIter->m_flags.m_needsInit)
  278. {
  279. modelDataIter->Init(this);
  280. }
  281. if (modelDataIter->m_flags.m_objectSrgNeedsUpdate)
  282. {
  283. modelDataIter->UpdateObjectSrg(this);
  284. }
  285. if (modelDataIter->m_flags.m_needsSetRayTracingData)
  286. {
  287. modelDataIter->SetRayTracingData(this);
  288. }
  289. // If instancing is enabled, the draw packets will be updated by the per-instance group jobs,
  290. // so they don't need to be updated here
  291. if (!r_meshInstancingEnabled)
  292. {
  293. // Unset per mesh shader options
  294. if (removePerMeshShaderOptionFlags)
  295. {
  296. for (RPI::MeshDrawPacketList& drawPacketList : modelDataIter->m_meshDrawPacketListsByLod)
  297. {
  298. for (RPI::MeshDrawPacket& drawPacket : drawPacketList)
  299. {
  300. m_flagRegistry->VisitTags(
  301. [&](AZ::Name shaderOption, [[maybe_unused]] FlagRegistry::TagType tag)
  302. {
  303. drawPacket.UnsetShaderOption(shaderOption);
  304. });
  305. }
  306. }
  307. modelDataIter->m_cullable.m_shaderOptionFlags = 0;
  308. modelDataIter->m_cullable.m_prevShaderOptionFlags = 0;
  309. }
  310. // [GFX TODO] [ATOM-1357] Currently all of the draw packets have to be checked for material ID changes because
  311. // material properties can impact which actual shader is used, which impacts the SRG in the draw packet.
  312. // This is scheduled to be optimized so the work is only done on draw packets that need it instead of having
  313. // to check every one.
  314. modelDataIter->UpdateDrawPackets(m_forceRebuildDrawPackets);
  315. }
  316. }
  317. };
  318. Job* executeInitJob = aznew JobFunction<decltype(initJobLambda)>(initJobLambda, true, nullptr); // Auto-deletes
  319. initJobQueue.push_back(executeInitJob);
  320. }
  321. return initJobQueue;
  322. }
  323. AZStd::vector<Job*> MeshFeatureProcessor::CreateUpdateCullingJobQueue()
  324. {
  325. const auto iteratorRanges = m_modelData.GetParallelRanges();
  326. AZStd::vector<Job*> updateCullingJobQueue;
  327. updateCullingJobQueue.reserve(iteratorRanges.size());
  328. for (const auto& iteratorRange : iteratorRanges)
  329. {
  330. const auto updateCullingJobLambda = [this, iteratorRange]() -> void
  331. {
  332. AZ_PROFILE_SCOPE(AzRender, "MeshFeatureProcessor: Simulate: UpdateCulling");
  333. for (auto meshDataIter = iteratorRange.m_begin; meshDataIter != iteratorRange.m_end; ++meshDataIter)
  334. {
  335. if (!meshDataIter->m_model)
  336. {
  337. continue; // model not loaded yet
  338. }
  339. if (meshDataIter->m_flags.m_cullableNeedsRebuild)
  340. {
  341. meshDataIter->BuildCullable();
  342. }
  343. if (meshDataIter->m_flags.m_cullBoundsNeedsUpdate)
  344. {
  345. meshDataIter->UpdateCullBounds(this);
  346. }
  347. }
  348. };
  349. Job* executeUpdateGroupJob =
  350. aznew JobFunction<decltype(updateCullingJobLambda)>(updateCullingJobLambda, true, nullptr); // Auto-deletes
  351. updateCullingJobQueue.push_back(executeUpdateGroupJob);
  352. }
  353. return updateCullingJobQueue;
  354. }
  355. void MeshFeatureProcessor::ExecuteCombinedJobQueue(AZStd::span<Job*> initQueue, AZStd::span<Job*> updateCullingQueue, Job* parentJob)
  356. {
  357. AZ::JobCompletion jobCompletion;
  358. for (size_t i = 0; i < initQueue.size(); ++i)
  359. {
  360. // Update Culling work should happen after Init is done
  361. initQueue[i]->SetDependent(updateCullingQueue[i]);
  362. // FeatureProcessor::Simulate is optionally run with a parent job.
  363. if (parentJob)
  364. {
  365. // When a parent job is used, we set dependencies on it and use WaitForChildren to wait for them to finish executing
  366. parentJob->StartAsChild(updateCullingQueue[i]);
  367. initQueue[i]->Start();
  368. }
  369. else
  370. {
  371. // When a parent job is not used, we use a job completion to synchronize
  372. updateCullingQueue[i]->SetDependent(&jobCompletion);
  373. initQueue[i]->Start();
  374. updateCullingQueue[i]->Start();
  375. }
  376. }
  377. if (parentJob)
  378. {
  379. parentJob->WaitForChildren();
  380. }
  381. else
  382. {
  383. jobCompletion.StartAndWaitForCompletion();
  384. }
  385. }
  386. void MeshFeatureProcessor::ExecuteSimulateJobQueue(AZStd::span<Job*> jobQueue, Job* parentJob)
  387. {
  388. AZ::JobCompletion jobCompletion;
  389. for (Job* childJob : jobQueue)
  390. {
  391. // FeatureProcessor::Simulate is optionally run with a parent job.
  392. if (parentJob)
  393. {
  394. // When a parent job is used, we set dependencies on it and use WaitForChildren to wait for them to finish executing
  395. parentJob->StartAsChild(childJob);
  396. }
  397. else
  398. {
  399. // When a parent job is not used, we use a job completion to synchronize
  400. childJob->SetDependent(&jobCompletion);
  401. childJob->Start();
  402. }
  403. }
  404. if (parentJob)
  405. {
  406. parentJob->WaitForChildren();
  407. }
  408. else
  409. {
  410. jobCompletion.StartAndWaitForCompletion();
  411. }
  412. }
  413. void MeshFeatureProcessor::OnEndCulling(const MeshFeatureProcessor::RenderPacket& packet)
  414. {
  415. if (r_meshInstancingEnabled)
  416. {
  417. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: OnEndCulling");
  418. // If necessary, allocate memory up front for the work that needs to be done this frame
  419. ResizePerViewInstanceVectors(packet.m_views.size());
  420. {
  421. // Iterate over all of the visible objects for each view, and perform the first stage of the bucket sort
  422. // where each visible object is sorted into its bucket
  423. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: Add Visible Objects to Buckets");
  424. AZ::TaskGraphEvent addVisibleObjectsToBucketsTGEvent{ "AddVisibleObjectsToBuckets Wait" };
  425. AZ::TaskGraph addVisibleObjectsToBucketsTG{ "AddVisibleObjectsToBuckets" };
  426. for (size_t viewIndex = 0; viewIndex < packet.m_views.size(); ++viewIndex)
  427. {
  428. AddVisibleObjectsToBuckets(addVisibleObjectsToBucketsTG, viewIndex, packet.m_views[viewIndex]);
  429. }
  430. addVisibleObjectsToBucketsTG.Submit(&addVisibleObjectsToBucketsTGEvent);
  431. addVisibleObjectsToBucketsTGEvent.Wait();
  432. }
  433. {
  434. // Now that the buckets have been filled, create a task for each bucket to sort each individual bucket in parallel
  435. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: Sort Buckets");
  436. AZ::TaskGraphEvent sortInstanceBufferBucketsTGEvent{ "SortInstanceBufferBuckets Wait" };
  437. AZ::TaskGraph sortInstanceBufferBucketsTG{ "SortInstanceBufferBuckets" };
  438. for (size_t viewIndex = 0; viewIndex < packet.m_views.size(); ++viewIndex)
  439. {
  440. SortInstanceBufferBuckets(sortInstanceBufferBucketsTG, viewIndex);
  441. }
  442. // submit the tasks
  443. sortInstanceBufferBucketsTG.Submit(&sortInstanceBufferBucketsTGEvent);
  444. sortInstanceBufferBucketsTGEvent.Wait();
  445. }
  446. {
  447. // For each bucket, create a task to iterate over the instance buffer to calculate the offset and count
  448. // to use with each instanced draw call, and add the draw calls to the view.
  449. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: Build Instance Buffer and Draw Calls");
  450. AZ::TaskGraphEvent buildInstanceBufferTGEvent{ "BuildInstanceBuffer Wait" };
  451. AZ::TaskGraph buildInstanceBufferTG{ "BuildInstanceBuffer" };
  452. for (size_t viewIndex = 0; viewIndex < packet.m_views.size(); ++viewIndex)
  453. {
  454. BuildInstanceBufferAndDrawCalls(buildInstanceBufferTG, viewIndex, packet.m_views[viewIndex]);
  455. }
  456. // submit the tasks
  457. buildInstanceBufferTG.Submit(&buildInstanceBufferTGEvent);
  458. buildInstanceBufferTGEvent.Wait();
  459. }
  460. for (size_t viewIndex = 0; viewIndex < packet.m_views.size(); ++viewIndex)
  461. {
  462. // Now that the per-view instance buffers are up to date on the CPU, update them on the GPU
  463. UpdateGPUInstanceBufferForView(viewIndex, packet.m_views[viewIndex]);
  464. }
  465. }
  466. }
  467. void MeshFeatureProcessor::ResizePerViewInstanceVectors(size_t viewCount)
  468. {
  469. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: ResizePerInstanceVectors");
  470. // Initialize the instance data if it hasn't been created yet
  471. if (m_perViewInstanceData.size() <= viewCount)
  472. {
  473. m_perViewInstanceData.resize(
  474. viewCount, AZStd::vector<TransformServiceFeatureProcessorInterface::ObjectId>());
  475. }
  476. if (m_perViewInstanceGroupBuckets.size() <= viewCount)
  477. {
  478. m_perViewInstanceGroupBuckets.resize(viewCount, AZStd::vector<InstanceGroupBucket>());
  479. }
  480. // Initialize the buffer handler if it hasn't been created yet
  481. if (m_perViewInstanceDataBufferHandlers.size() <= viewCount)
  482. {
  483. GpuBufferHandler::Descriptor desc;
  484. desc.m_bufferName = "MeshInstanceDataBuffer";
  485. desc.m_bufferSrgName = "m_instanceData";
  486. desc.m_elementSize = sizeof(uint32_t);
  487. desc.m_srgLayout = RPI::RPISystemInterface::Get()->GetViewSrgLayout().get();
  488. m_perViewInstanceDataBufferHandlers.reserve(viewCount);
  489. while (m_perViewInstanceDataBufferHandlers.size() < viewCount)
  490. {
  491. // We construct and add these one at a time instead of a single call to resize
  492. // because copying a GpuBufferHandler will result in a new one that refers to the same buffer,
  493. // and we want a unique GpuBufferHandler referring to a unique buffer for each view.
  494. m_perViewInstanceDataBufferHandlers.push_back(GpuBufferHandler(desc));
  495. }
  496. }
  497. AZStd::vector<uint32_t> perBucketInstanceCounts;
  498. const auto instanceManagerRanges = m_meshInstanceManager.GetParallelRanges();
  499. if (instanceManagerRanges.size() > 0)
  500. {
  501. // Resize the per-bucket data vectors for every view
  502. for (AZStd::vector<InstanceGroupBucket>& perViewInstanceGroupBuckets : m_perViewInstanceGroupBuckets)
  503. {
  504. // Get the max page index (bucket count) by looking at the index of the very last page
  505. // This is slightly conservative, as the StableDynamicArray in the MeshInstanceManager will always
  506. // increment the page count to get the index of a new page, but it will never decrement the page count
  507. // it or re-use the index of and existing page after it is freed, so that could result in some extra buckets
  508. // here that are ultimately unused. But the MeshInstanceManager is never releasing unused pages, so that won't
  509. // be an issue.
  510. uint32_t bucketCount = static_cast<uint32_t>(instanceManagerRanges.back().m_begin.GetPageIndex()) + 1;
  511. perViewInstanceGroupBuckets.resize(bucketCount);
  512. perBucketInstanceCounts.resize(bucketCount, 0);
  513. for (InstanceGroupBucket& instanceGroupBucket : perViewInstanceGroupBuckets)
  514. {
  515. instanceGroupBucket.m_currentElementIndex = 0;
  516. instanceGroupBucket.m_sortInstanceData.clear();
  517. }
  518. }
  519. }
  520. else
  521. {
  522. // If there are no buckets, clear them
  523. for (AZStd::vector<InstanceGroupBucket>& perViewInstanceGroupBuckets : m_perViewInstanceGroupBuckets)
  524. {
  525. perViewInstanceGroupBuckets.clear();
  526. }
  527. }
  528. for (const auto& iteratorRange : instanceManagerRanges)
  529. {
  530. uint32_t maxPossibleInstanceCountForGroup = 0;
  531. for (auto instanceGroupDataIter = iteratorRange.m_begin; instanceGroupDataIter != iteratorRange.m_end;
  532. ++instanceGroupDataIter)
  533. {
  534. // Resize the cloned draw packet vector so that there is a unique drawItem for each view
  535. instanceGroupDataIter->m_perViewDrawPackets.resize(viewCount);
  536. maxPossibleInstanceCountForGroup += instanceGroupDataIter->m_count;
  537. }
  538. perBucketInstanceCounts[iteratorRange.m_begin.GetPageIndex()] = maxPossibleInstanceCountForGroup;
  539. }
  540. // Resize the per-bucket data vectors for every view to allow for all possible objects to be visible
  541. for (size_t viewIndex = 0; viewIndex < viewCount; ++viewIndex)
  542. {
  543. AZStd::vector<InstanceGroupBucket>& currentViewInstanceGroupBuckets = m_perViewInstanceGroupBuckets[viewIndex];
  544. for (size_t bucketIndex = 0; bucketIndex < currentViewInstanceGroupBuckets.size(); ++bucketIndex)
  545. {
  546. // Reserve enough memory to handle the case where all of the objects are visible
  547. // We use resize_no_construct instead of reserve + push_back so that we can use an
  548. // atomic index to insert the data lock-free from multiple threads.
  549. uint32_t maxPossibleObjects = perBucketInstanceCounts[bucketIndex];
  550. currentViewInstanceGroupBuckets[bucketIndex].m_sortInstanceData.resize_no_construct(maxPossibleObjects);
  551. }
  552. }
  553. }
  554. void MeshFeatureProcessor::SetLightingChannelMask(const MeshHandle& meshHandle, uint32_t lightingChannelMask)
  555. {
  556. if (meshHandle.IsValid())
  557. {
  558. ToModelDataInstance(meshHandle).SetLightingChannelMask(lightingChannelMask);
  559. }
  560. }
  561. uint32_t MeshFeatureProcessor::GetLightingChannelMask(const MeshHandle& meshHandle) const
  562. {
  563. if (meshHandle.IsValid())
  564. {
  565. return meshHandle->GetLightingChannelMask();
  566. }
  567. else
  568. {
  569. AZ_Assert(false, "Invalid mesh handle");
  570. return 1;
  571. }
  572. }
  573. void MeshFeatureProcessor::AddVisibleObjectsToBuckets(
  574. TaskGraph& addVisibleObjectsToBucketsTG, size_t viewIndex, const RPI::ViewPtr& view)
  575. {
  576. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: AddVisibleObjectsToBuckets");
  577. size_t visibleObjectCount = view->GetVisibleObjectList().size();
  578. AZStd::vector<TransformServiceFeatureProcessorInterface::ObjectId>& perViewInstanceData = m_perViewInstanceData[viewIndex];
  579. if (visibleObjectCount > 0)
  580. {
  581. perViewInstanceData.clear();
  582. static const AZ::TaskDescriptor addVisibleObjectsToBucketsTaskDescriptor{
  583. "AZ::Render::MeshFeatureProcessor::OnEndCulling - AddVisibleObjectsToBuckets", "Graphics"
  584. };
  585. size_t batchSize = r_meshInstancingBucketSortScatterBatchSize;
  586. size_t batchCount = AZ::DivideAndRoundUp(visibleObjectCount, batchSize);
  587. for (size_t batchIndex = 0; batchIndex < batchCount; ++batchIndex)
  588. {
  589. size_t batchStart = batchIndex * batchSize;
  590. // If we're in the last batch, we just get the remaining objects
  591. size_t currentBatchCount = batchIndex == batchCount - 1 ? visibleObjectCount - batchStart : batchSize;
  592. addVisibleObjectsToBucketsTG.AddTask(
  593. addVisibleObjectsToBucketsTaskDescriptor,
  594. // Don't capture the shared_ptr because that causes incorrect ref counting when copying/moving the lambda
  595. [this, viewPtr = view.get(), viewIndex, batchStart, currentBatchCount]()
  596. {
  597. RPI::VisibleObjectListView visibilityList = viewPtr->GetVisibleObjectList();
  598. AZStd::vector<InstanceGroupBucket>& currentViewInstanceGroupBuckets = m_perViewInstanceGroupBuckets[viewIndex];
  599. for (size_t i = batchStart; i < batchStart + currentBatchCount; ++i)
  600. {
  601. const RPI::VisibleObjectProperties& visibleObject = visibilityList[i];
  602. const ModelDataInstance::PostCullingInstanceDataList* postCullingInstanceDataList =
  603. static_cast<const ModelDataInstance::PostCullingInstanceDataList*>(visibleObject.m_userData);
  604. for (const ModelDataInstance::PostCullingInstanceData& postCullingData : *postCullingInstanceDataList)
  605. {
  606. SortInstanceData instanceData;
  607. instanceData.m_instanceGroupHandle = postCullingData.m_instanceGroupHandle;
  608. instanceData.m_objectId = postCullingData.m_objectId;
  609. instanceData.m_depth = visibleObject.m_depth;
  610. // Sort transparent objects in reverse by making their depths negative.
  611. if (instanceData.m_instanceGroupHandle->m_isTransparent)
  612. {
  613. instanceData.m_depth *= -1.0f;
  614. }
  615. // Add the sort data to the bucket
  616. InstanceGroupBucket& instanceGroupBucket =
  617. currentViewInstanceGroupBuckets[postCullingData.m_instanceGroupPageIndex];
  618. // Use an atomic operation to determine where to insert this sort data
  619. uint32_t currentIndex = instanceGroupBucket.m_currentElementIndex++;
  620. instanceGroupBucket.m_sortInstanceData[currentIndex] = instanceData;
  621. }
  622. }
  623. });
  624. }
  625. }
  626. }
  627. void MeshFeatureProcessor::SortInstanceBufferBuckets(TaskGraph& sortInstanceBufferBucketsTG, size_t viewIndex)
  628. {
  629. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: SortInstanceBufferBuckets");
  630. AZStd::vector<InstanceGroupBucket>& currentViewInstanceGroupBuckets = m_perViewInstanceGroupBuckets[viewIndex];
  631. // Populate a task graph where each task is responsible for sorting a bucket.
  632. static const AZ::TaskDescriptor sortInstanceBufferBucketsTaskDescriptor{
  633. "AZ::Render::MeshFeatureProcessor::OnEndCulling - sort instance data buckets", "Graphics"
  634. };
  635. for (InstanceGroupBucket& instanceGroupBucket : currentViewInstanceGroupBuckets)
  636. {
  637. // We're creating one task per bucket here. That is ideal when the buckets are all close to the same size,
  638. // but it can lead to an imperfect distribution of work if one bucket has more objects than any of the others.
  639. // If this becomes a performance bottleneck, it could be alleviated by adding an heuristic to sort any overfull
  640. // buckets using a parallel std sort rather than using a single task, or by breaking it up into smaller buckets.
  641. sortInstanceBufferBucketsTG.AddTask(
  642. sortInstanceBufferBucketsTaskDescriptor,
  643. [&instanceGroupBucket]()
  644. {
  645. // Note: we've previously resized m_sortInstanceData to conservatively fit all possible visible meshes for the bucket,
  646. // which allowed us to use an atomic index for parallel lock free insertion.
  647. // As a result, m_sortInstanceData it has a greater size than the actual count.
  648. // We only care about the real visible objects, so cut off the last unused elements here
  649. instanceGroupBucket.m_sortInstanceData.resize(instanceGroupBucket.m_currentElementIndex);
  650. // Sort within the bucket
  651. std::sort(instanceGroupBucket.m_sortInstanceData.begin(), instanceGroupBucket.m_sortInstanceData.end());
  652. });
  653. }
  654. }
  655. static void AddInstancedDrawPacketToView(
  656. const RPI::ViewPtr& view,
  657. size_t viewIndex,
  658. ModelDataInstance::InstanceGroupHandle instanceGroupHandle,
  659. float accumulatedDepth,
  660. uint32_t instanceGroupBeginIndex,
  661. uint32_t instanceGroupEndNonInclusiveIndex)
  662. {
  663. MeshInstanceGroupData& instanceGroup = *instanceGroupHandle;
  664. // Each task is working on a page of instance groups, but
  665. // there is also one task per-view. So there may be multiple
  666. // threads accessing the intance group here, so we must use a lock to protect it.
  667. // We could potentially handle all views for a given bucket of instance groups
  668. // In a single task, which would negate the need to lock here
  669. if (instanceGroup.m_perViewDrawPackets.size() <= viewIndex)
  670. {
  671. AZStd::scoped_lock meshDataLock(instanceGroup.m_eventLock);
  672. instanceGroup.m_perViewDrawPackets.resize(viewIndex + 1);
  673. }
  674. // Cache a cloned drawpacket here
  675. if (!instanceGroup.m_perViewDrawPackets[viewIndex])
  676. {
  677. // Since there is only one task that will operate both on this view index and on the bucket with this instance group,
  678. // there is no need to lock here.
  679. RHI::DrawPacketBuilder drawPacketBuilder{RHI::MultiDevice::AllDevices};
  680. instanceGroup.m_perViewDrawPackets[viewIndex] = drawPacketBuilder.Clone(instanceGroup.m_drawPacket.GetRHIDrawPacket());
  681. }
  682. // Now that we have a valid cloned draw packet, update it with the latest offset + count
  683. RHI::Ptr<RHI::DrawPacket> clonedDrawPacket = instanceGroup.m_perViewDrawPackets[viewIndex];
  684. // Set the instance data offset
  685. AZStd::span<uint8_t> data{ reinterpret_cast<uint8_t*>(&instanceGroupBeginIndex), sizeof(uint32_t) };
  686. clonedDrawPacket->SetRootConstant(instanceGroup.m_drawRootConstantOffset, data);
  687. // instanceGroupEndNonInclusiveIndex is the first index after the current group ends.
  688. uint32_t instanceCount = instanceGroupEndNonInclusiveIndex - instanceGroupBeginIndex;
  689. // Set the cloned draw packet instance count
  690. clonedDrawPacket->SetInstanceCount(instanceCount);
  691. float averageDepth = accumulatedDepth / static_cast<float>(instanceCount);
  692. // Depth values from the camera are always positive.
  693. // However, we use negative values to sort by reverse depth for transparent objects
  694. // If the average depth is negative (this instance group is transparent), make it positive to get the real average depth for the group
  695. averageDepth = AZStd::abs(averageDepth);
  696. // Submit the draw packet
  697. view->AddDrawPacket(clonedDrawPacket.get(), averageDepth);
  698. }
  699. void MeshFeatureProcessor::BuildInstanceBufferAndDrawCalls(
  700. TaskGraph& buildInstanceBufferTG, size_t viewIndex, const RPI::ViewPtr& view)
  701. {
  702. AZStd::vector<TransformServiceFeatureProcessorInterface::ObjectId>& perViewInstanceData = m_perViewInstanceData[viewIndex];
  703. AZStd::vector<InstanceGroupBucket>& currentViewInstanceGroupBuckets = m_perViewInstanceGroupBuckets[viewIndex];
  704. uint32_t currentBatchStart = 0;
  705. for (InstanceGroupBucket& instanceGroupBucket : currentViewInstanceGroupBuckets)
  706. {
  707. if (instanceGroupBucket.m_currentElementIndex > 0)
  708. {
  709. static const AZ::TaskDescriptor buildInstanceBufferTaskDescriptor{
  710. "AZ::Render::MeshFeatureProcessor::OnEndCulling - process instance data", "Graphics"
  711. };
  712. // Process data up to but not including actualEndOffset
  713. buildInstanceBufferTG.AddTask(
  714. buildInstanceBufferTaskDescriptor,
  715. [currentBatchStart,
  716. viewIndex,
  717. &view,
  718. &perViewInstanceData, &instanceGroupBucket]()
  719. {
  720. ModelDataInstance::InstanceGroupHandle currentInstanceGroup =
  721. instanceGroupBucket.m_sortInstanceData.begin()->m_instanceGroupHandle;
  722. uint32_t instanceDataOffset = currentBatchStart;
  723. float accumulatedDepth = 0.0f;
  724. uint32_t instanceDataIndex = currentBatchStart;
  725. for (SortInstanceData& sortInstanceData : instanceGroupBucket.m_sortInstanceData)
  726. {
  727. // Anytime the instance group changes, submit a draw for the previous group
  728. if (sortInstanceData.m_instanceGroupHandle != currentInstanceGroup)
  729. {
  730. AddInstancedDrawPacketToView(
  731. view, viewIndex, currentInstanceGroup, accumulatedDepth, instanceDataOffset, instanceDataIndex);
  732. // Update the loop trackers
  733. accumulatedDepth = 0.0f;
  734. instanceDataOffset = instanceDataIndex;
  735. currentInstanceGroup = sortInstanceData.m_instanceGroupHandle;
  736. }
  737. perViewInstanceData[instanceDataIndex] = sortInstanceData.m_objectId;
  738. accumulatedDepth += sortInstanceData.m_depth;
  739. instanceDataIndex++;
  740. }
  741. // Submit the last instance group
  742. {
  743. AddInstancedDrawPacketToView(
  744. view, viewIndex, currentInstanceGroup, accumulatedDepth, instanceDataOffset, instanceDataIndex);
  745. }
  746. });
  747. // At this point, inserting into the bucket is already complete, so m_currentElementIndex represents the count of all visible meshes in this bucket.
  748. currentBatchStart += instanceGroupBucket.m_currentElementIndex;
  749. }
  750. }
  751. // currentBatchStart now represents the total count of visible instances in this view.
  752. // Re-size the instance data buffer so that we can fill it with the tasks created above
  753. perViewInstanceData.resize_no_construct(currentBatchStart);
  754. }
  755. void MeshFeatureProcessor::UpdateGPUInstanceBufferForView(size_t viewIndex, const RPI::ViewPtr& view)
  756. {
  757. AZ_PROFILE_SCOPE(RPI, "MeshFeatureProcessor: UpdateGPUInstanceBufferForView");
  758. // Use the correct srg for the view
  759. GpuBufferHandler& instanceDataBufferHandler = m_perViewInstanceDataBufferHandlers[viewIndex];
  760. instanceDataBufferHandler.UpdateSrg(view->GetShaderResourceGroup().get());
  761. // Now that we have all of our instance data, we need to create the buffer and bind it to the view srgs
  762. // Eventually, this could be a transient buffer
  763. // create output buffer descriptors
  764. AZStd::vector<TransformServiceFeatureProcessorInterface::ObjectId>& perViewInstanceData = m_perViewInstanceData[viewIndex];
  765. instanceDataBufferHandler.UpdateBuffer(perViewInstanceData.data(), static_cast<uint32_t>(perViewInstanceData.size()));
  766. }
  767. void MeshFeatureProcessor::OnBeginPrepareRender()
  768. {
  769. m_meshDataChecker.soft_lock();
  770. // The per-mesh shader option flags are set in feature processors' simulate function
  771. // So we want to process the flags here to update the draw packets if needed.
  772. // Update MeshDrawPacket's shader options if PerMeshShaderOption is enabled
  773. if (r_enablePerMeshShaderOptionFlags || m_enablePerMeshShaderOptionFlags)
  774. {
  775. // For mesh instance groups when r_meshInstancingEnabled is enabled
  776. AZStd::vector<ModelDataInstance::InstanceGroupHandle> instanceGroupsNeedUpdate;
  777. // Per mesh shader option flags was on, but now turned off, so reset all the shader options.
  778. for (auto& modelHandle : m_modelData)
  779. {
  780. if (modelHandle.m_cullable.m_prevShaderOptionFlags != modelHandle.m_cullable.m_shaderOptionFlags)
  781. {
  782. // skip if the model need to be initialized
  783. if (modelHandle.m_flags.m_needsInit)
  784. {
  785. continue;
  786. }
  787. if (!r_meshInstancingEnabled)
  788. {
  789. for (RPI::MeshDrawPacketList& drawPacketList : modelHandle.m_meshDrawPacketListsByLod)
  790. {
  791. for (RPI::MeshDrawPacket& drawPacket : drawPacketList)
  792. {
  793. m_flagRegistry->VisitTags(
  794. [&](AZ::Name shaderOption, FlagRegistry::TagType tag)
  795. {
  796. bool shaderOptionValue = (modelHandle.m_cullable.m_shaderOptionFlags & tag.GetIndex()) > 0;
  797. drawPacket.SetShaderOption(shaderOption, AZ::RPI::ShaderOptionValue(shaderOptionValue));
  798. });
  799. drawPacket.Update(*GetParentScene(), true);
  800. }
  801. }
  802. modelHandle.m_flags.m_cullableNeedsRebuild = true;
  803. // [GHI-13619]
  804. // Update the draw packets on the cullable, since we just set a shader item.
  805. // BuildCullable is a bit overkill here, this could be reduced to just updating the drawPacket specific info
  806. // It's also going to cause m_cullableNeedsUpdate to be set, which will execute next frame, which we don't need
  807. modelHandle.BuildCullable();
  808. }
  809. else
  810. {
  811. // mark the instance groups which need to update their shader options
  812. for (size_t lodIndex = 0; lodIndex < modelHandle.m_postCullingInstanceDataByLod.size(); ++lodIndex)
  813. {
  814. ModelDataInstance::PostCullingInstanceDataList& postCullingInstanceDataList =
  815. modelHandle.m_postCullingInstanceDataByLod[lodIndex];
  816. for (const ModelDataInstance::PostCullingInstanceData& postCullingData : postCullingInstanceDataList)
  817. {
  818. instanceGroupsNeedUpdate.push_back(postCullingData.m_instanceGroupHandle);
  819. }
  820. }
  821. }
  822. }
  823. }
  824. if (r_meshInstancingEnabled)
  825. {
  826. for (auto& instanceGroupDataIter : instanceGroupsNeedUpdate)
  827. {
  828. // default values for when r_enablePerMeshShaderOptionFlags was set from true to false
  829. bool shaderOptionFlagsChanged = true;
  830. uint32_t shaderOptionFlagMask = 0; // 0 means disable all shader options
  831. if (r_enablePerMeshShaderOptionFlags)
  832. {
  833. shaderOptionFlagsChanged = instanceGroupDataIter->UpdateShaderOptionFlags();
  834. shaderOptionFlagMask = instanceGroupDataIter->m_shaderOptionFlagMask;
  835. }
  836. if (shaderOptionFlagsChanged)
  837. {
  838. // Set shader options here
  839. m_flagRegistry->VisitTags(
  840. [&](AZ::Name shaderOption, FlagRegistry::TagType tag)
  841. {
  842. if ((shaderOptionFlagMask & tag.GetIndex()) > 0)
  843. {
  844. bool shaderOptionValue = (instanceGroupDataIter->m_shaderOptionFlags & tag.GetIndex()) > 0;
  845. instanceGroupDataIter->m_drawPacket.SetShaderOption(
  846. shaderOption, AZ::RPI::ShaderOptionValue(shaderOptionValue));
  847. }
  848. else
  849. {
  850. instanceGroupDataIter->m_drawPacket.UnsetShaderOption(shaderOption);
  851. }
  852. });
  853. instanceGroupDataIter->UpdateDrawPacket(*GetParentScene(), true);
  854. // Note, we don't need to call CacheRootConstantInterval() here because the root constant layout won't change
  855. // when we switch shader variants.
  856. }
  857. }
  858. }
  859. }
  860. m_enablePerMeshShaderOptionFlags = r_enablePerMeshShaderOptionFlags;
  861. }
  862. void MeshFeatureProcessor::OnEndPrepareRender()
  863. {
  864. m_meshDataChecker.soft_unlock();
  865. if (m_reportShaderOptionFlags)
  866. {
  867. m_reportShaderOptionFlags = false;
  868. PrintShaderOptionFlags();
  869. }
  870. for (auto& model : m_modelData)
  871. {
  872. model.m_cullable.m_prevShaderOptionFlags = model.m_cullable.m_shaderOptionFlags.exchange(0);
  873. model.m_cullable.m_flags = model.m_flags.m_isAlwaysDynamic ? m_meshMovedFlag.GetIndex() : 0;
  874. }
  875. }
  876. MeshFeatureProcessor::MeshHandle MeshFeatureProcessor::AcquireMesh(const MeshHandleDescriptor& descriptor)
  877. {
  878. AZ_PROFILE_SCOPE(AzRender, "MeshFeatureProcessor: AcquireMesh");
  879. // don't need to check the concurrency during emplace() because the StableDynamicArray won't move the other elements during
  880. // insertion
  881. StableDynamicArrayHandle<ModelDataInstance> meshDataHandle = m_modelData.emplace();
  882. meshDataHandle->m_descriptor = descriptor;
  883. meshDataHandle->m_descriptor.m_modelChangedEventHandler.Connect(meshDataHandle->m_modelChangedEvent);
  884. meshDataHandle->m_descriptor.m_objectSrgCreatedHandler.Connect(meshDataHandle->m_objectSrgCreatedEvent);
  885. meshDataHandle->m_scene = GetParentScene();
  886. meshDataHandle->m_objectId = m_transformService->ReserveObjectId();
  887. meshDataHandle->m_rayTracingUuid = AZ::Uuid::CreateRandom();
  888. meshDataHandle->m_originalModelAsset = descriptor.m_modelAsset;
  889. meshDataHandle->m_flags.m_keepBufferAssetsInMemory = descriptor.m_supportRayIntersection; // Note: the MeshLoader may need to read this flag. so it needs to be assigned because meshloader is created
  890. meshDataHandle->m_meshLoader = AZStd::make_shared<ModelDataInstance::MeshLoader>(descriptor.m_modelAsset, &*meshDataHandle);
  891. meshDataHandle->m_flags.m_isAlwaysDynamic = descriptor.m_isAlwaysDynamic;
  892. meshDataHandle->m_flags.m_isDrawMotion = descriptor.m_isAlwaysDynamic;
  893. if (descriptor.m_excludeFromReflectionCubeMaps)
  894. {
  895. meshDataHandle->m_cullable.m_cullData.m_hideFlags |= RPI::View::UsageReflectiveCubeMap;
  896. }
  897. return meshDataHandle;
  898. }
  899. bool MeshFeatureProcessor::ReleaseMesh(MeshHandle& meshHandle)
  900. {
  901. if (meshHandle.IsValid())
  902. {
  903. auto converted = StableDynamicArrayHandle<ModelDataInstance>(std::move(meshHandle));
  904. converted->m_meshLoader.reset();
  905. converted->DeInit(this);
  906. m_transformService->ReleaseObjectId(converted->m_objectId);
  907. AZStd::concurrency_check_scope scopeCheck(m_meshDataChecker);
  908. m_modelData.erase(converted);
  909. return true;
  910. }
  911. return false;
  912. }
  913. void MeshFeatureProcessor::SetDrawItemEnabled(const MeshHandle& meshHandle, RHI::DrawListTag drawListTag, bool enabled)
  914. {
  915. AZ::RPI::MeshDrawPacketLods& drawPacketListByLod = meshHandle.IsValid() && !r_meshInstancingEnabled
  916. ? ToModelDataInstance(meshHandle).m_meshDrawPacketListsByLod
  917. : m_emptyDrawPacketLods;
  918. for (AZ::RPI::MeshDrawPacketList& drawPacketList : drawPacketListByLod)
  919. {
  920. for (AZ::RPI::MeshDrawPacket& meshDrawPacket : drawPacketList)
  921. {
  922. RHI::DrawPacket* drawPacket = meshDrawPacket.GetRHIDrawPacket();
  923. if (drawPacket != nullptr)
  924. {
  925. size_t drawItemCount = drawPacket->GetDrawItemCount();
  926. for (size_t idx = 0; idx < drawItemCount; ++idx)
  927. {
  928. // Ensure that the draw item belongs to the specified tag
  929. if (drawPacket->GetDrawListTag(idx) == drawListTag)
  930. {
  931. drawPacket->GetDrawItem(idx)->SetEnabled(enabled);
  932. }
  933. }
  934. }
  935. }
  936. }
  937. }
  938. void MeshFeatureProcessor::PrintDrawPacketInfo(const MeshHandle& meshHandle)
  939. {
  940. AZStd::string stringOutput = "\n------- MESH INFO -------\n";
  941. AZ::RPI::MeshDrawPacketLods& drawPacketListByLod = meshHandle.IsValid() && !r_meshInstancingEnabled
  942. ? ToModelDataInstance(meshHandle).m_meshDrawPacketListsByLod
  943. : m_emptyDrawPacketLods;
  944. u32 lodCounter = 0;
  945. for (AZ::RPI::MeshDrawPacketList& drawPacketList : drawPacketListByLod)
  946. {
  947. stringOutput += AZStd::string::format("--- Mesh Lod %u ---\n", lodCounter++);
  948. u32 drawPacketCounter = 0;
  949. for (AZ::RPI::MeshDrawPacket& meshDrawPacket : drawPacketList)
  950. {
  951. RHI::DrawPacket* drawPacket = meshDrawPacket.GetRHIDrawPacket();
  952. if (drawPacket)
  953. {
  954. size_t numDrawItems = drawPacket->GetDrawItemCount();
  955. stringOutput += AZStd::string::format("-- Draw Packet %u (%zu Draw Items) --\n", drawPacketCounter++, numDrawItems);
  956. for (size_t drawItemIdx = 0; drawItemIdx < numDrawItems; ++drawItemIdx)
  957. {
  958. RHI::DrawItem* drawItem = drawPacket->GetDrawItem(drawItemIdx);
  959. RHI::DrawListTag tag = drawPacket->GetDrawListTag(drawItemIdx);
  960. stringOutput += AZStd::string::format("Item %zu | ", drawItemIdx);
  961. stringOutput += drawItem->GetEnabled() ? "Enabled | " : "Disabled | ";
  962. stringOutput += AZStd::string::format("%s Tag\n", RHI::GetDrawListName(tag).GetCStr());
  963. }
  964. }
  965. }
  966. }
  967. stringOutput += "\n";
  968. AZ_Printf("MeshFeatureProcessor", stringOutput.c_str());
  969. }
  970. MeshFeatureProcessor::MeshHandle MeshFeatureProcessor::CloneMesh(const MeshHandle& meshHandle)
  971. {
  972. if (meshHandle.IsValid())
  973. {
  974. return AcquireMesh(ToModelDataInstance(meshHandle).m_descriptor);
  975. }
  976. return MeshFeatureProcessor::MeshHandle();
  977. }
  978. Data::Instance<RPI::Model> MeshFeatureProcessor::GetModel(const MeshHandle& meshHandle) const
  979. {
  980. return meshHandle.IsValid() ? ToModelDataInstance(meshHandle).m_model : nullptr;
  981. }
  982. Data::Asset<RPI::ModelAsset> MeshFeatureProcessor::GetModelAsset(const MeshHandle& meshHandle) const
  983. {
  984. if (meshHandle.IsValid())
  985. {
  986. return ToModelDataInstance(meshHandle).m_originalModelAsset;
  987. }
  988. return {};
  989. }
  990. const RPI::MeshDrawPacketLods& MeshFeatureProcessor::GetDrawPackets(const MeshHandle& meshHandle) const
  991. {
  992. // This function is being deprecated. It's currently used to get draw packets so that we can print some
  993. // debug information about the draw packets in an imgui menu. But the ownership model for draw packets is changing.
  994. // We can no longer assume a meshHandle directly keeps a copy of all of its draw packets.
  995. return meshHandle.IsValid() && !r_meshInstancingEnabled ? ToModelDataInstance(meshHandle).m_meshDrawPacketListsByLod
  996. : m_emptyDrawPacketLods;
  997. }
  998. const AZStd::vector<Data::Instance<RPI::ShaderResourceGroup>>& MeshFeatureProcessor::GetObjectSrgs(const MeshHandle& meshHandle) const
  999. {
  1000. static AZStd::vector<Data::Instance<RPI::ShaderResourceGroup>> staticEmptyList;
  1001. return meshHandle.IsValid() ? ToModelDataInstance(meshHandle).m_objectSrgList : staticEmptyList;
  1002. }
  1003. void MeshFeatureProcessor::QueueObjectSrgForCompile(const MeshHandle& meshHandle) const
  1004. {
  1005. if (meshHandle.IsValid())
  1006. {
  1007. ToModelDataInstance(meshHandle).m_flags.m_objectSrgNeedsUpdate = true;
  1008. }
  1009. }
  1010. void MeshFeatureProcessor::SetCustomMaterials(const MeshHandle& meshHandle, const Data::Instance<RPI::Material>& material)
  1011. {
  1012. Render::CustomMaterialMap materials;
  1013. materials[AZ::Render::DefaultCustomMaterialId] = { material };
  1014. return SetCustomMaterials(meshHandle, materials);
  1015. }
  1016. void MeshFeatureProcessor::SetCustomMaterials(const MeshHandle& meshHandle, const CustomMaterialMap& materials)
  1017. {
  1018. if (meshHandle.IsValid())
  1019. {
  1020. auto& modelData = ToModelDataInstance(meshHandle);
  1021. modelData.m_descriptor.m_customMaterials = materials;
  1022. if (modelData.m_model)
  1023. {
  1024. modelData.ReInit(this);
  1025. }
  1026. modelData.m_flags.m_objectSrgNeedsUpdate = true;
  1027. }
  1028. }
  1029. const CustomMaterialMap& MeshFeatureProcessor::GetCustomMaterials(const MeshHandle& meshHandle) const
  1030. {
  1031. return meshHandle.IsValid() ? ToModelDataInstance(meshHandle).m_descriptor.m_customMaterials : DefaultCustomMaterialMap;
  1032. }
  1033. AZStd::unique_ptr<StreamBufferViewsBuilderInterface> MeshFeatureProcessor::CreateStreamBufferViewsBuilder(
  1034. const MeshHandle& meshHandle) const
  1035. {
  1036. return AZStd::make_unique<ShaderStreamBufferViewsBuilder>(meshHandle);
  1037. }
  1038. DispatchDrawItemList MeshFeatureProcessor::BuildDispatchDrawItemList(
  1039. const MeshHandle& meshHandle,
  1040. const uint32_t lodIndex,
  1041. const uint32_t meshIndex,
  1042. const RHI::DrawListMask drawListTagsFilter,
  1043. const RHI::DrawFilterMask materialPipelineFilter,
  1044. DispatchArgumentsSetupCB dispatchArgumentsSetupCB) const
  1045. {
  1046. DispatchDrawItemList retList;
  1047. const AZ::RPI::MeshDrawPacketLods& drawPacketListByLod = GetDrawPackets(meshHandle);
  1048. const uint32_t lodCount = aznumeric_caster(drawPacketListByLod.size());
  1049. if (lodIndex >= lodCount)
  1050. {
  1051. // This is normal. May happen if a caller got a valid MeshHandle before
  1052. // a mesh is fully loaded from assets.
  1053. return retList;
  1054. }
  1055. const AZ::RPI::MeshDrawPacketList& drawPacketList = drawPacketListByLod[lodIndex];
  1056. const uint32_t meshCount = aznumeric_caster(drawPacketList.size());
  1057. if (meshIndex >= meshCount)
  1058. {
  1059. AZ_Error("MeshFeatureProcessor", false,
  1060. "For lodIndex=%u, got invalid meshIndex=%u, maxMeshCount=%u",
  1061. lodIndex, meshIndex, meshCount);
  1062. return retList;
  1063. }
  1064. const AZ::RPI::MeshDrawPacket& meshDrawPacket = drawPacketList[meshIndex];
  1065. const RHI::DrawPacket* drawPacket = meshDrawPacket.GetRHIDrawPacket();
  1066. const auto& shadersList = meshDrawPacket.GetActiveShaderList();
  1067. if (drawPacket)
  1068. {
  1069. const uint32_t drawItemCount = aznumeric_caster(drawPacket->GetDrawItemCount());
  1070. for (uint32_t drawItemIdx = 0; drawItemIdx < drawItemCount; ++drawItemIdx)
  1071. {
  1072. const RHI::DrawItem* drawItem = drawPacket->GetDrawItem(drawItemIdx);
  1073. if (drawItem->GetPipelineStateType() != RHI::PipelineStateType::Dispatch)
  1074. {
  1075. continue;
  1076. }
  1077. // Only create the DispatchItems for DrawItems whose DrawListTag is included
  1078. // in @drawListTagsFilter AND their DrawFilterMask is included in @materialPipelineFilter.
  1079. RHI::DrawListTag tag = drawPacket->GetDrawListTag(drawItemIdx);
  1080. RHI::DrawFilterMask drawItemPipelineFilter = drawPacket->GetDrawFilterMask(drawItemIdx);
  1081. if (
  1082. drawListTagsFilter.test(tag.GetIndex()) &&
  1083. (materialPipelineFilter & drawItemPipelineFilter)
  1084. )
  1085. {
  1086. retList.emplace_back(DispatchDrawItem(drawItem));
  1087. auto& dispatchDrawItem = retList.back();
  1088. const auto& shaderAsset = shadersList[drawItemIdx].m_shader->GetAsset();
  1089. RHI::DispatchDirect dispatchDirect;
  1090. RPI::GetComputeShaderNumThreads(shaderAsset, dispatchDirect);
  1091. dispatchArgumentsSetupCB(lodIndex, meshIndex, drawItemIdx, drawItem, dispatchDirect);
  1092. InitializeDispatchItemFromDrawItem(dispatchDrawItem.m_distpatchItem, drawItem, dispatchDirect);
  1093. }
  1094. }
  1095. }
  1096. return retList;
  1097. }
  1098. void MeshFeatureProcessor::InitializeDispatchItemFromDrawItem(
  1099. RHI::DispatchItem& dstDispatchItem, const RHI::DrawItem* srcDrawItem, const RHI::DispatchDirect& dispatchDirect) const
  1100. {
  1101. RHI::DispatchArguments dispatchArguments(dispatchDirect);
  1102. dstDispatchItem.SetArguments(dispatchArguments);
  1103. bool deviceCommonDataIsSet = false;
  1104. RHI::MultiDeviceObject::IterateDevices(
  1105. RHI::MultiDevice::AllDevices,
  1106. [&](int deviceIndex)
  1107. {
  1108. const auto& deviceDrawItem = srcDrawItem->GetDeviceDrawItem(deviceIndex);
  1109. dstDispatchItem.SetDeviceShaderResourceGroups(
  1110. deviceIndex, deviceDrawItem.m_shaderResourceGroups, deviceDrawItem.m_shaderResourceGroupCount);
  1111. dstDispatchItem.SetUniqueDeviceShaderResourceGroup(deviceIndex, deviceDrawItem.m_uniqueShaderResourceGroup);
  1112. dstDispatchItem.SetDevicePipelineState(deviceIndex, deviceDrawItem.m_pipelineState);
  1113. if (!deviceCommonDataIsSet)
  1114. {
  1115. dstDispatchItem.SetRootConstantSize(deviceDrawItem.m_rootConstantSize);
  1116. dstDispatchItem.SetRootConstants(deviceDrawItem.m_rootConstants);
  1117. deviceCommonDataIsSet = true;
  1118. }
  1119. return true;
  1120. });
  1121. }
  1122. void MeshFeatureProcessor::SetTransform(const MeshHandle& meshHandle, const AZ::Transform& transform, const AZ::Vector3& nonUniformScale)
  1123. {
  1124. if (meshHandle.IsValid())
  1125. {
  1126. auto& modelData = ToModelDataInstance(meshHandle);
  1127. modelData.m_flags.m_cullBoundsNeedsUpdate = true;
  1128. modelData.m_flags.m_objectSrgNeedsUpdate = true;
  1129. modelData.m_cullable.m_flags = modelData.m_cullable.m_flags | m_meshMovedFlag.GetIndex();
  1130. // Only set m_dynamic flag if the model instance is initialized.
  1131. if (!modelData.m_flags.m_dynamic)
  1132. {
  1133. modelData.m_flags.m_dynamic = (modelData.m_model && !modelData.m_flags.m_needsInit) ? true : false;
  1134. // Enable draw motion for all the DrawPacket referenced by this model
  1135. if (r_meshInstancingEnabled && modelData.m_flags.m_dynamic)
  1136. {
  1137. for (size_t lodIndex = 0; lodIndex < modelData.m_postCullingInstanceDataByLod.size(); ++lodIndex)
  1138. {
  1139. ModelDataInstance::PostCullingInstanceDataList& postCullingInstanceDataList =
  1140. modelData.m_postCullingInstanceDataByLod[lodIndex];
  1141. for (const ModelDataInstance::PostCullingInstanceData& postCullingData : postCullingInstanceDataList)
  1142. {
  1143. AZStd::scoped_lock<AZStd::mutex> scopedLock(postCullingData.m_instanceGroupHandle->m_eventLock);
  1144. if (!postCullingData.m_instanceGroupHandle->m_isDrawMotion)
  1145. {
  1146. postCullingData.m_instanceGroupHandle->m_isDrawMotion = true;
  1147. postCullingData.m_instanceGroupHandle->m_drawPacket.SetEnableDraw(m_meshMotionDrawListTag, true);
  1148. }
  1149. }
  1150. }
  1151. }
  1152. }
  1153. m_transformService->SetTransformForId(modelData.m_objectId, transform, nonUniformScale);
  1154. // ray tracing data needs to be updated with the new transform
  1155. if (m_rayTracingFeatureProcessor)
  1156. {
  1157. m_rayTracingFeatureProcessor->SetMeshTransform(modelData.m_rayTracingUuid, transform, nonUniformScale);
  1158. }
  1159. }
  1160. }
  1161. void MeshFeatureProcessor::SetLocalAabb(const MeshHandle& meshHandle, const AZ::Aabb& localAabb)
  1162. {
  1163. if (meshHandle.IsValid())
  1164. {
  1165. ModelDataInstance& modelData = ToModelDataInstance(meshHandle);
  1166. modelData.m_aabb = localAabb;
  1167. modelData.m_flags.m_cullBoundsNeedsUpdate = true;
  1168. modelData.m_flags.m_objectSrgNeedsUpdate = true;
  1169. }
  1170. };
  1171. AZ::Aabb MeshFeatureProcessor::GetLocalAabb(const MeshHandle& meshHandle) const
  1172. {
  1173. if (meshHandle.IsValid())
  1174. {
  1175. return ToModelDataInstance(meshHandle).m_aabb;
  1176. }
  1177. else
  1178. {
  1179. AZ_Assert(false, "Invalid mesh handle");
  1180. return Aabb::CreateNull();
  1181. }
  1182. }
  1183. Transform MeshFeatureProcessor::GetTransform(const MeshHandle& meshHandle)
  1184. {
  1185. if (meshHandle.IsValid())
  1186. {
  1187. return m_transformService->GetTransformForId(ToModelDataInstance(meshHandle).m_objectId);
  1188. }
  1189. else
  1190. {
  1191. AZ_Assert(false, "Invalid mesh handle");
  1192. return Transform::CreateIdentity();
  1193. }
  1194. }
  1195. Vector3 MeshFeatureProcessor::GetNonUniformScale(const MeshHandle& meshHandle)
  1196. {
  1197. if (meshHandle.IsValid())
  1198. {
  1199. return m_transformService->GetNonUniformScaleForId(ToModelDataInstance(meshHandle).m_objectId);
  1200. }
  1201. else
  1202. {
  1203. AZ_Assert(false, "Invalid mesh handle");
  1204. return Vector3::CreateOne();
  1205. }
  1206. }
  1207. void MeshFeatureProcessor::SetSortKey(const MeshHandle& meshHandle, RHI::DrawItemSortKey sortKey)
  1208. {
  1209. if (meshHandle.IsValid())
  1210. {
  1211. ToModelDataInstance(meshHandle).SetSortKey(this, sortKey);
  1212. }
  1213. }
  1214. RHI::DrawItemSortKey MeshFeatureProcessor::GetSortKey(const MeshHandle& meshHandle) const
  1215. {
  1216. if (meshHandle.IsValid())
  1217. {
  1218. return ToModelDataInstance(meshHandle).GetSortKey();
  1219. }
  1220. else
  1221. {
  1222. AZ_Assert(false, "Invalid mesh handle");
  1223. return 0;
  1224. }
  1225. }
  1226. void ModelDataInstance::SetLightingChannelMask(uint32_t lightingChannelMask)
  1227. {
  1228. m_lightingChannelMask = lightingChannelMask;
  1229. }
  1230. void MeshFeatureProcessor::SetMeshLodConfiguration(const MeshHandle& meshHandle, const RPI::Cullable::LodConfiguration& meshLodConfig)
  1231. {
  1232. if (meshHandle.IsValid())
  1233. {
  1234. ToModelDataInstance(meshHandle).SetMeshLodConfiguration(meshLodConfig);
  1235. }
  1236. }
  1237. RPI::Cullable::LodConfiguration MeshFeatureProcessor::GetMeshLodConfiguration(const MeshHandle& meshHandle) const
  1238. {
  1239. if (meshHandle.IsValid())
  1240. {
  1241. return ToModelDataInstance(meshHandle).GetMeshLodConfiguration();
  1242. }
  1243. else
  1244. {
  1245. AZ_Assert(false, "Invalid mesh handle");
  1246. return { RPI::Cullable::LodType::Default, 0, 0.0f, 0.0f };
  1247. }
  1248. }
  1249. void MeshFeatureProcessor::SetIsAlwaysDynamic(const MeshHandle & meshHandle, bool isAlwaysDynamic)
  1250. {
  1251. if (meshHandle.IsValid())
  1252. {
  1253. ToModelDataInstance(meshHandle).m_flags.m_isAlwaysDynamic = isAlwaysDynamic;
  1254. }
  1255. }
  1256. bool MeshFeatureProcessor::GetIsAlwaysDynamic(const MeshHandle& meshHandle) const
  1257. {
  1258. if (!meshHandle.IsValid())
  1259. {
  1260. AZ_Assert(false, "Invalid mesh handle");
  1261. return false;
  1262. }
  1263. return ToModelDataInstance(meshHandle).m_flags.m_isAlwaysDynamic;
  1264. }
  1265. void MeshFeatureProcessor::SetExcludeFromReflectionCubeMaps(const MeshHandle& meshHandle, bool excludeFromReflectionCubeMaps)
  1266. {
  1267. if (meshHandle.IsValid())
  1268. {
  1269. auto& modelData = ToModelDataInstance(meshHandle);
  1270. modelData.m_descriptor.m_excludeFromReflectionCubeMaps = excludeFromReflectionCubeMaps;
  1271. if (excludeFromReflectionCubeMaps)
  1272. {
  1273. modelData.m_cullable.m_cullData.m_hideFlags |= RPI::View::UsageReflectiveCubeMap;
  1274. }
  1275. else
  1276. {
  1277. modelData.m_cullable.m_cullData.m_hideFlags &= ~RPI::View::UsageReflectiveCubeMap;
  1278. }
  1279. }
  1280. }
  1281. bool MeshFeatureProcessor::GetExcludeFromReflectionCubeMaps(const MeshHandle& meshHandle) const
  1282. {
  1283. if (meshHandle.IsValid())
  1284. {
  1285. return ToModelDataInstance(meshHandle).m_descriptor.m_excludeFromReflectionCubeMaps;
  1286. }
  1287. return false;
  1288. }
  1289. void MeshFeatureProcessor::SetRayTracingEnabled(const MeshHandle& meshHandle, bool enabled)
  1290. {
  1291. if (meshHandle.IsValid())
  1292. {
  1293. auto& modelData = ToModelDataInstance(meshHandle);
  1294. // update the ray tracing data based on the current state and the new state
  1295. if (enabled && !modelData.m_descriptor.m_isRayTracingEnabled)
  1296. {
  1297. // add to ray tracing
  1298. modelData.m_flags.m_needsSetRayTracingData = true;
  1299. }
  1300. else if (!enabled && modelData.m_descriptor.m_isRayTracingEnabled)
  1301. {
  1302. // remove from ray tracing
  1303. if (m_rayTracingFeatureProcessor)
  1304. {
  1305. m_rayTracingFeatureProcessor->RemoveMesh(modelData.m_rayTracingUuid);
  1306. }
  1307. }
  1308. // set new state
  1309. modelData.m_descriptor.m_isRayTracingEnabled = enabled;
  1310. }
  1311. }
  1312. bool MeshFeatureProcessor::GetRayTracingEnabled(const MeshHandle& meshHandle) const
  1313. {
  1314. if (meshHandle.IsValid())
  1315. {
  1316. return ToModelDataInstance(meshHandle).m_descriptor.m_isRayTracingEnabled;
  1317. }
  1318. else
  1319. {
  1320. AZ_Assert(false, "Invalid mesh handle");
  1321. return false;
  1322. }
  1323. }
  1324. bool MeshFeatureProcessor::GetVisible(const MeshHandle& meshHandle) const
  1325. {
  1326. if (meshHandle.IsValid())
  1327. {
  1328. return ToModelDataInstance(meshHandle).m_flags.m_visible;
  1329. }
  1330. return false;
  1331. }
  1332. void MeshFeatureProcessor::SetVisible(const MeshHandle& meshHandle, bool visible)
  1333. {
  1334. if (meshHandle.IsValid())
  1335. {
  1336. auto& modelData = ToModelDataInstance(meshHandle);
  1337. modelData.SetVisible(visible);
  1338. if (m_rayTracingFeatureProcessor && modelData.m_descriptor.m_isRayTracingEnabled)
  1339. {
  1340. // always remove from ray tracing first
  1341. m_rayTracingFeatureProcessor->RemoveMesh(modelData.m_rayTracingUuid);
  1342. // now add if it's visible
  1343. if (visible)
  1344. {
  1345. modelData.m_flags.m_needsSetRayTracingData = true;
  1346. }
  1347. }
  1348. }
  1349. }
  1350. void MeshFeatureProcessor::SetUseForwardPassIblSpecular(const MeshHandle& meshHandle, bool useForwardPassIblSpecular)
  1351. {
  1352. if (meshHandle.IsValid())
  1353. {
  1354. auto& modelData = ToModelDataInstance(meshHandle);
  1355. modelData.m_descriptor.m_useForwardPassIblSpecular = useForwardPassIblSpecular;
  1356. modelData.m_flags.m_objectSrgNeedsUpdate = true;
  1357. if (modelData.m_model)
  1358. {
  1359. const size_t modelLodCount = modelData.m_model->GetLodCount();
  1360. for (size_t modelLodIndex = 0; modelLodIndex < modelLodCount; ++modelLodIndex)
  1361. {
  1362. modelData.BuildDrawPacketList(this, modelLodIndex);
  1363. }
  1364. }
  1365. }
  1366. }
  1367. void MeshFeatureProcessor::SetRayTracingDirty(const MeshHandle& meshHandle)
  1368. {
  1369. if (meshHandle.IsValid())
  1370. {
  1371. ToModelDataInstance(meshHandle).m_flags.m_needsSetRayTracingData = true;
  1372. }
  1373. }
  1374. RHI::Ptr<MeshFeatureProcessor::FlagRegistry> MeshFeatureProcessor::GetShaderOptionFlagRegistry()
  1375. {
  1376. if (m_flagRegistry == nullptr)
  1377. {
  1378. m_flagRegistry = FlagRegistry::Create();
  1379. }
  1380. return m_flagRegistry;
  1381. };
  1382. void MeshFeatureProcessor::ForceRebuildDrawPackets([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments)
  1383. {
  1384. m_forceRebuildDrawPackets = true;
  1385. }
  1386. void MeshFeatureProcessor::OnRenderPipelineChanged([[maybe_unused]] RPI::RenderPipeline* pipeline,
  1387. [[maybe_unused]] RPI::SceneNotification::RenderPipelineChangeType changeType)
  1388. {
  1389. m_forceRebuildDrawPackets = true;
  1390. }
  1391. void MeshFeatureProcessor::UpdateMeshReflectionProbes()
  1392. {
  1393. for (auto& meshInstance : m_modelData)
  1394. {
  1395. // we need to rebuild the Srg for any meshes that are using the forward pass IBL specular option
  1396. if (meshInstance.m_descriptor.m_useForwardPassIblSpecular)
  1397. {
  1398. meshInstance.m_flags.m_objectSrgNeedsUpdate = true;
  1399. }
  1400. // update the raytracing reflection probe data if necessary
  1401. RayTracingFeatureProcessor::Mesh::ReflectionProbe reflectionProbe;
  1402. bool currentHasRayTracingReflectionProbe = meshInstance.m_flags.m_hasRayTracingReflectionProbe;
  1403. meshInstance.SetRayTracingReflectionProbeData(this, reflectionProbe);
  1404. if (meshInstance.m_flags.m_hasRayTracingReflectionProbe ||
  1405. (currentHasRayTracingReflectionProbe != meshInstance.m_flags.m_hasRayTracingReflectionProbe))
  1406. {
  1407. m_rayTracingFeatureProcessor->SetMeshReflectionProbe(meshInstance.m_rayTracingUuid, reflectionProbe);
  1408. }
  1409. }
  1410. }
  1411. void MeshFeatureProcessor::ReportShaderOptionFlags([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments)
  1412. {
  1413. m_reportShaderOptionFlags = true;
  1414. }
  1415. RayTracingFeatureProcessor* MeshFeatureProcessor::GetRayTracingFeatureProcessor() const
  1416. {
  1417. return m_rayTracingFeatureProcessor;
  1418. }
  1419. ReflectionProbeFeatureProcessor* MeshFeatureProcessor::GetReflectionProbeFeatureProcessor() const
  1420. {
  1421. return m_reflectionProbeFeatureProcessor;
  1422. }
  1423. TransformServiceFeatureProcessor* MeshFeatureProcessor::GetTransformServiceFeatureProcessor() const
  1424. {
  1425. return m_transformService;
  1426. }
  1427. RHI::DrawListTag MeshFeatureProcessor::GetTransparentDrawListTag() const
  1428. {
  1429. return m_transparentDrawListTag;
  1430. }
  1431. MeshInstanceManager& MeshFeatureProcessor::GetMeshInstanceManager()
  1432. {
  1433. return m_meshInstanceManager;
  1434. }
  1435. bool MeshFeatureProcessor::IsMeshInstancingEnabled() const
  1436. {
  1437. return m_enableMeshInstancing;
  1438. }
  1439. void MeshFeatureProcessor::PrintShaderOptionFlags()
  1440. {
  1441. AZStd::map<FlagRegistry::TagType, AZ::Name> tags;
  1442. AZStd::string registeredFoundMessage = "Registered flags: ";
  1443. auto gatherTags = [&](const Name& name, FlagRegistry::TagType tag)
  1444. {
  1445. tags[tag] = name;
  1446. registeredFoundMessage.append(name.GetCStr() + AZStd::string(", "));
  1447. };
  1448. m_flagRegistry->VisitTags(gatherTags);
  1449. registeredFoundMessage.erase(registeredFoundMessage.end() - 2);
  1450. AZ_Printf("MeshFeatureProcessor", registeredFoundMessage.c_str());
  1451. AZStd::map<uint32_t, uint32_t> flagStats;
  1452. for (auto& model : m_modelData)
  1453. {
  1454. ++flagStats[model.m_cullable.m_shaderOptionFlags.load()];
  1455. }
  1456. for (auto [flag, references] : flagStats)
  1457. {
  1458. AZStd::string flagList;
  1459. if (flag == 0)
  1460. {
  1461. flagList = "(None)";
  1462. }
  1463. else
  1464. {
  1465. for (auto [tag, name] : tags)
  1466. {
  1467. if ((tag.GetIndex() & flag) > 0)
  1468. {
  1469. flagList.append(name.GetCStr());
  1470. flagList.append(", ");
  1471. }
  1472. }
  1473. flagList.erase(flagList.end() - 2);
  1474. }
  1475. AZ_Printf("MeshFeatureProcessor", "Found %u references to [%s]", references, flagList.c_str());
  1476. }
  1477. }
  1478. const Data::Instance<RPI::ShaderResourceGroup>& MeshFeatureProcessor::GetDrawSrg(const MeshHandle& meshHandle,
  1479. uint32_t lodIndex, uint32_t subMeshIndex,
  1480. RHI::DrawListTag drawListTag, RHI::DrawFilterMask materialPipelineMask) const
  1481. {
  1482. if (!meshHandle.IsValid())
  1483. {
  1484. return RPI::MeshDrawPacket::InvalidSrg;
  1485. }
  1486. // We need to get the DrawPacket, from the DrawPacket we can query the index of the DrawItem
  1487. // that matches drawListTag & materialPipelineMask. We can use that index to fetch the DrawSrg
  1488. // from MeshDrawPacket::m_perDrawSrgs
  1489. auto& meshDrawPacketsByLod = ToModelDataInstance(meshHandle).m_meshDrawPacketListsByLod;
  1490. if (lodIndex >= aznumeric_cast<uint32_t>(meshDrawPacketsByLod.size()))
  1491. {
  1492. AZ_Error("MeshFeatureProcessor", false, "%s lodIndex=%u is invalid.\n", __FUNCTION__, lodIndex);
  1493. return RPI::MeshDrawPacket::InvalidSrg;
  1494. }
  1495. auto& meshDrawPackets = meshDrawPacketsByLod[lodIndex];
  1496. if (subMeshIndex >= meshDrawPackets.size())
  1497. {
  1498. AZ_Error("MeshFeatureProcessor", false, "%s subMeshIndex=%u is invalid.\n", __FUNCTION__, subMeshIndex);
  1499. return RPI::MeshDrawPacket::InvalidSrg;
  1500. }
  1501. auto& meshDrawPacket = meshDrawPackets[subMeshIndex];
  1502. auto drawItemIndex = meshDrawPacket.GetRHIDrawPacket()->GetDrawListIndex(drawListTag, materialPipelineMask);
  1503. if (drawItemIndex < 0)
  1504. {
  1505. return RPI::MeshDrawPacket::InvalidSrg;
  1506. }
  1507. return meshDrawPacket.GetDrawSrg(drawItemIndex);
  1508. }
  1509. // ModelDataInstance::MeshLoader...
  1510. ModelDataInstance::MeshLoader::MeshLoader(const Data::Asset<RPI::ModelAsset>& modelAsset, ModelDataInstance* parent)
  1511. : m_modelAsset(modelAsset)
  1512. , m_parent(parent)
  1513. {
  1514. if (!m_modelAsset.GetId().IsValid())
  1515. {
  1516. AZ_Error("ModelDataInstance::MeshLoader", false, "Invalid model asset Id.");
  1517. return;
  1518. }
  1519. m_modelAsset.QueueLoad();
  1520. Data::AssetBus::Handler::BusConnect(m_modelAsset.GetId());
  1521. AzFramework::AssetCatalogEventBus::Handler::BusConnect();
  1522. }
  1523. ModelDataInstance::MeshLoader::~MeshLoader()
  1524. {
  1525. AzFramework::AssetCatalogEventBus::Handler::BusDisconnect();
  1526. Data::AssetBus::Handler::BusDisconnect();
  1527. SystemTickBus::Handler::BusDisconnect();
  1528. }
  1529. void ModelDataInstance::MeshLoader::OnSystemTick()
  1530. {
  1531. SystemTickBus::Handler::BusDisconnect();
  1532. // Assign the fully loaded asset back to the mesh handle to not only hold asset id, but the actual data as well.
  1533. m_parent->m_originalModelAsset = m_modelAsset;
  1534. if (const auto& modelTags = m_modelAsset->GetTags(); !modelTags.empty())
  1535. {
  1536. RPI::AssetQuality highestLodBias = RPI::AssetQualityLowest;
  1537. for (const AZ::Name& tag : modelTags)
  1538. {
  1539. RPI::AssetQuality tagQuality = RPI::AssetQualityHighest;
  1540. RPI::ModelTagBus::BroadcastResult(tagQuality, &RPI::ModelTagBus::Events::GetQuality, tag);
  1541. highestLodBias = AZStd::min(highestLodBias, tagQuality);
  1542. }
  1543. if (highestLodBias >= m_modelAsset->GetLodCount())
  1544. {
  1545. highestLodBias = aznumeric_caster(m_modelAsset->GetLodCount() - 1);
  1546. }
  1547. m_parent->m_lodBias = highestLodBias;
  1548. for (const AZ::Name& tag : modelTags)
  1549. {
  1550. RPI::ModelTagBus::Broadcast(&RPI::ModelTagBus::Events::RegisterAsset, tag, m_modelAsset->GetId());
  1551. }
  1552. }
  1553. else
  1554. {
  1555. m_parent->m_lodBias = 0;
  1556. }
  1557. Data::Instance<RPI::Model> model;
  1558. // Check if a requires cloning callback got set and if so check if cloning the model asset is requested.
  1559. if (m_parent->m_descriptor.m_requiresCloneCallback && m_parent->m_descriptor.m_requiresCloneCallback(m_modelAsset))
  1560. {
  1561. // Clone the model asset to force create another model instance.
  1562. AZ::Data::AssetId newId(AZ::Uuid::CreateRandom(), /*subId=*/0);
  1563. Data::Asset<RPI::ModelAsset> clonedAsset;
  1564. // Assume cloned models will involve some kind of geometry deformation
  1565. m_parent->m_flags.m_isAlwaysDynamic = true;
  1566. if (AZ::RPI::ModelAssetCreator::Clone(m_modelAsset, clonedAsset, newId))
  1567. {
  1568. model = RPI::Model::FindOrCreate(clonedAsset);
  1569. }
  1570. else
  1571. {
  1572. AZ_Error("ModelDataInstance", false, "Cannot clone model for '%s'. Cloth simulation results won't be individual per entity.", m_modelAsset->GetName().GetCStr());
  1573. model = RPI::Model::FindOrCreate(m_modelAsset);
  1574. }
  1575. }
  1576. else
  1577. {
  1578. // Static mesh, no cloth buffer present.
  1579. model = RPI::Model::FindOrCreate(m_modelAsset);
  1580. }
  1581. if (model)
  1582. {
  1583. RayTracingFeatureProcessor* rayTracingFeatureProcessor =
  1584. m_parent->m_scene->GetFeatureProcessor<RayTracingFeatureProcessor>();
  1585. m_parent->RemoveRayTracingData(rayTracingFeatureProcessor);
  1586. m_parent->QueueInit(model);
  1587. m_parent->m_modelChangedEvent.Signal(AZStd::move(model));
  1588. // we always start out with a refcount of 1
  1589. model->GetModelAsset()->AddRefBufferAssets();
  1590. // if we don't want to keep them, this will drop the refcount to 0.
  1591. if (!m_parent->m_flags.m_keepBufferAssetsInMemory)
  1592. {
  1593. model->GetModelAsset()->ReleaseRefBufferAssets();
  1594. }
  1595. }
  1596. else
  1597. {
  1598. // when running with null renderer, the RPI::Model::FindOrCreate(...) is expected to return nullptr, so suppress this error.
  1599. AZ_Error("ModelDataInstance::OnAssetReady", RHI::IsNullRHI(), "Failed to create model instance for '%s'", m_modelAsset.GetHint().c_str());
  1600. }
  1601. }
  1602. //! AssetBus::Handler overrides...
  1603. void ModelDataInstance::MeshLoader::OnAssetReady(Data::Asset<Data::AssetData> asset)
  1604. {
  1605. // Update our model asset reference to contain the latest loaded version.
  1606. m_modelAsset = asset;
  1607. // The mesh loader queues the model asset to be loaded then connects to the asset bus. If the asset is already loaded
  1608. // OnAssetReady will be called before returning from the acquire function. Many callers connect handlers for model change
  1609. // events. Some of the handlers attempt to access their stored mesh handle member, which will not be up to date if the acquire
  1610. // function hasn't returned. This postpones sending the event until the next tick, allowing the acquire function to return and
  1611. // update and he stored mesh handles.
  1612. SystemTickBus::Handler::BusConnect();
  1613. }
  1614. void ModelDataInstance::MeshLoader::OnModelReloaded(Data::Asset<Data::AssetData> asset)
  1615. {
  1616. OnAssetReady(asset);
  1617. }
  1618. void ModelDataInstance::MeshLoader::OnAssetError([[maybe_unused]] Data::Asset<Data::AssetData> asset)
  1619. {
  1620. // Note: m_modelAsset and asset represents same asset, but only m_modelAsset contains the file path in its hint from serialization
  1621. AZ_Error(
  1622. "ModelDataInstance::MeshLoader", false, "Failed to load asset %s. It may be missing, or not be finished processing",
  1623. m_modelAsset.GetHint().c_str());
  1624. AzFramework::AssetSystemRequestBus::Broadcast(
  1625. &AzFramework::AssetSystem::AssetSystemRequests::EscalateAssetByUuid, m_modelAsset.GetId().m_guid);
  1626. }
  1627. void ModelDataInstance::MeshLoader::OnCatalogAssetRemoved(
  1628. const AZ::Data::AssetId& assetId, [[maybe_unused]] const AZ::Data::AssetInfo& assetInfo)
  1629. {
  1630. OnCatalogAssetChanged(assetId);
  1631. }
  1632. void ModelDataInstance::MeshLoader::OnCatalogAssetAdded(const AZ::Data::AssetId& assetId)
  1633. {
  1634. // If the asset didn't exist in the catalog when it first attempted to load, we need to try loading it again
  1635. OnCatalogAssetChanged(assetId);
  1636. }
  1637. void ModelDataInstance::MeshLoader::OnCatalogAssetChanged(const AZ::Data::AssetId& assetId)
  1638. {
  1639. if (assetId == m_modelAsset.GetId())
  1640. {
  1641. Data::Asset<RPI::ModelAsset> modelAssetReference = m_modelAsset;
  1642. // If the asset was modified, reload it. This will also cause a model to change back to the default missing
  1643. // asset if it was removed, and it will replace the default missing asset with the real asset if it was added.
  1644. AZ::SystemTickBus::QueueFunction(
  1645. [=, meshLoader = m_parent->m_meshLoader]() mutable
  1646. {
  1647. // Only trigger the reload if the meshLoader is still being used by something other than the lambda.
  1648. // If the lambda is the only owner, it will get destroyed after this queued call, so there's no point
  1649. // in reloading the model.
  1650. if (meshLoader.use_count() > 1)
  1651. {
  1652. ModelReloaderSystemInterface::Get()->ReloadModel(modelAssetReference, m_modelReloadedEventHandler);
  1653. }
  1654. });
  1655. }
  1656. }
  1657. ModelDataInstance::ModelDataInstance()
  1658. {
  1659. m_flags.m_cullBoundsNeedsUpdate = false;
  1660. m_flags.m_cullableNeedsRebuild = false;
  1661. m_flags.m_needsInit = false;
  1662. m_flags.m_objectSrgNeedsUpdate = true;
  1663. m_flags.m_isAlwaysDynamic = false;
  1664. m_flags.m_dynamic = false;
  1665. m_flags.m_isDrawMotion = false;
  1666. m_flags.m_visible = true;
  1667. m_flags.m_useForwardPassIblSpecular = false;
  1668. m_flags.m_hasForwardPassIblSpecularMaterial = false;
  1669. m_flags.m_needsSetRayTracingData = false;
  1670. m_flags.m_hasRayTracingReflectionProbe = false;
  1671. }
  1672. void ModelDataInstance::DeInit(MeshFeatureProcessor* meshFeatureProcessor)
  1673. {
  1674. RayTracingFeatureProcessor* rayTracingFeatureProcessor = meshFeatureProcessor->GetRayTracingFeatureProcessor();
  1675. m_scene->GetCullingScene()->UnregisterCullable(m_cullable);
  1676. RemoveRayTracingData(rayTracingFeatureProcessor);
  1677. // We're intentionally using the MeshFeatureProcessor's value instead of using the cvar directly here,
  1678. // because DeInit might be called after the cvar changes, but we want to do the de-initialization based
  1679. // on what the setting was before (when the resources were initialized). The MeshFeatureProcessor will still have the cached
  1680. // value in that case
  1681. if (!meshFeatureProcessor->IsMeshInstancingEnabled())
  1682. {
  1683. m_meshDrawPacketListsByLod.clear();
  1684. }
  1685. else
  1686. {
  1687. // Remove all the meshes from the MeshInstanceManager
  1688. MeshInstanceManager& meshInstanceManager = meshFeatureProcessor->GetMeshInstanceManager();
  1689. for (size_t lodIndex = 0; lodIndex < m_postCullingInstanceDataByLod.size(); ++lodIndex)
  1690. {
  1691. PostCullingInstanceDataList& postCullingInstanceDataList = m_postCullingInstanceDataByLod[lodIndex];
  1692. for (PostCullingInstanceData& postCullingData : postCullingInstanceDataList)
  1693. {
  1694. postCullingData.m_instanceGroupHandle->RemoveAssociatedInstance(this);
  1695. // Remove instance will decrement the use-count of the instance group, and only release the instance group
  1696. // if nothing else is referring to it.
  1697. meshInstanceManager.RemoveInstance(postCullingData.m_instanceGroupHandle);
  1698. }
  1699. postCullingInstanceDataList.clear();
  1700. }
  1701. m_postCullingInstanceDataByLod.clear();
  1702. }
  1703. m_descriptor.m_customMaterials.clear();
  1704. m_objectSrgList = {};
  1705. m_model = {};
  1706. }
  1707. void ModelDataInstance::ReInit(MeshFeatureProcessor* meshFeatureProcessor)
  1708. {
  1709. CustomMaterialMap customMaterials = m_descriptor.m_customMaterials;
  1710. const Data::Instance<RPI::Model> model = m_model;
  1711. DeInit(meshFeatureProcessor);
  1712. m_descriptor.m_customMaterials = customMaterials;
  1713. m_model = model;
  1714. QueueInit(m_model);
  1715. }
  1716. void ModelDataInstance::QueueInit(const Data::Instance<RPI::Model>& model)
  1717. {
  1718. m_model = model;
  1719. m_flags.m_needsInit = true;
  1720. m_aabb = m_model->GetModelAsset()->GetAabb();
  1721. }
  1722. void ModelDataInstance::Init(MeshFeatureProcessor* meshFeatureProcessor)
  1723. {
  1724. const size_t modelLodCount = m_model->GetLodCount();
  1725. if (!r_meshInstancingEnabled)
  1726. {
  1727. m_meshDrawPacketListsByLod.resize(modelLodCount);
  1728. }
  1729. else
  1730. {
  1731. m_postCullingInstanceDataByLod.resize(modelLodCount);
  1732. }
  1733. for (size_t modelLodIndex = 0; modelLodIndex < modelLodCount; ++modelLodIndex)
  1734. {
  1735. BuildDrawPacketList(meshFeatureProcessor, modelLodIndex);
  1736. }
  1737. for (auto& objectSrg : m_objectSrgList)
  1738. {
  1739. // Set object Id once since it never changes
  1740. RHI::ShaderInputNameIndex objectIdIndex = "m_objectId";
  1741. objectSrg->SetConstant(objectIdIndex, m_objectId.GetIndex());
  1742. objectIdIndex.AssertValid();
  1743. }
  1744. if (m_flags.m_visible && m_descriptor.m_isRayTracingEnabled)
  1745. {
  1746. m_flags.m_needsSetRayTracingData = true;
  1747. }
  1748. m_flags.m_cullableNeedsRebuild = true;
  1749. m_flags.m_cullBoundsNeedsUpdate = true;
  1750. m_flags.m_objectSrgNeedsUpdate = true;
  1751. m_flags.m_needsInit = false;
  1752. }
  1753. struct MeshInstancingSupport
  1754. {
  1755. bool m_canSupportInstancing = false;
  1756. bool m_isTransparent = false;
  1757. };
  1758. static MeshInstancingSupport CanSupportInstancing(
  1759. Data::Instance<RPI::Material> material, bool useForwardPassIbleSpecular, const RHI::DrawListTag& transparentDrawListTag)
  1760. {
  1761. MeshInstancingSupport result;
  1762. if (useForwardPassIbleSpecular)
  1763. {
  1764. // Forward pass ibl specular uses the ObjectSrg to set the closest reflection probe data
  1765. // Since all instances from a single instanced draw call share a single ObjectSrg, this
  1766. // will not work with instancing unless they happen to all share the same closes probe.
  1767. // In the future, we could make that part of the MeshInstanceGroupKey, but that impacts
  1768. // the initalization logic since at Init time we don't yet know the closest reflection probe.
  1769. // So initially we treat that case as not supporting instancing, and eventually we can re-order
  1770. // the logic in MeshFeatureProcessor::Simulate such that we know the up-to-date ObjectSrg data
  1771. // before this point
  1772. result.m_canSupportInstancing = false;
  1773. return result;
  1774. }
  1775. bool shadersSupportInstancing = true;
  1776. bool isTransparent = false;
  1777. material->ForAllShaderItems(
  1778. [&](const Name&, const RPI::ShaderCollection::Item& shaderItem)
  1779. {
  1780. if (shaderItem.IsEnabled())
  1781. {
  1782. // Check to see if the shaderItem has the o_meshInstancingEnabled option. All shader items in the draw packet must
  1783. // support this option
  1784. RPI::ShaderOptionIndex index = shaderItem.GetShaderOptionGroup().GetShaderOptionLayout()->FindShaderOptionIndex(
  1785. s_o_meshInstancingIsEnabled_Name);
  1786. if (!index.IsValid())
  1787. {
  1788. shadersSupportInstancing = false;
  1789. return false; // break
  1790. }
  1791. // Get the DrawListTag. Use the explicit draw list override if exists.
  1792. AZ::RHI::DrawListTag drawListTag = shaderItem.GetDrawListTagOverride();
  1793. if (drawListTag.IsNull())
  1794. {
  1795. drawListTag = RHI::RHISystemInterface::Get()->GetDrawListTagRegistry()->FindTag(
  1796. shaderItem.GetShaderAsset()->GetDrawListName());
  1797. }
  1798. // Check to see if the shaderItem is for a transparent pass. If any of the active shader items
  1799. // are for a transparent pass, we still support instancing, but we mark it as transparent so that
  1800. // we can sort by reverse-depth
  1801. if (drawListTag == transparentDrawListTag)
  1802. {
  1803. isTransparent = true;
  1804. if (!r_meshInstancingEnabledForTransparentObjects)
  1805. {
  1806. shadersSupportInstancing = false;
  1807. return false; // break
  1808. }
  1809. }
  1810. }
  1811. return true; // continue
  1812. });
  1813. result.m_canSupportInstancing = shadersSupportInstancing;
  1814. result.m_isTransparent = isTransparent;
  1815. return result;
  1816. }
  1817. void ModelDataInstance::BuildDrawPacketList(MeshFeatureProcessor* meshFeatureProcessor, size_t modelLodIndex)
  1818. {
  1819. RPI::ModelLod& modelLod = *m_model->GetLods()[modelLodIndex];
  1820. const size_t meshCount = modelLod.GetMeshes().size();
  1821. MeshInstanceManager& meshInstanceManager = meshFeatureProcessor->GetMeshInstanceManager();
  1822. if (!r_meshInstancingEnabled)
  1823. {
  1824. RPI::MeshDrawPacketList& drawPacketListOut = m_meshDrawPacketListsByLod[modelLodIndex];
  1825. drawPacketListOut.clear();
  1826. drawPacketListOut.reserve(meshCount);
  1827. }
  1828. auto meshMotionDrawListTag = AZ::RHI::RHISystemInterface::Get()->GetDrawListTagRegistry()->FindTag(MeshCommon::MotionDrawListTagName);
  1829. for (size_t meshIndex = 0; meshIndex < meshCount; ++meshIndex)
  1830. {
  1831. const auto meshes = modelLod.GetMeshes();
  1832. const RPI::ModelLod::Mesh& mesh = meshes[meshIndex];
  1833. // Determine if there is a custom material specified for this submission
  1834. const CustomMaterialId customMaterialId(aznumeric_cast<AZ::u64>(modelLodIndex), mesh.m_materialSlotStableId);
  1835. const auto& customMaterialInfo = GetCustomMaterialWithFallback(customMaterialId);
  1836. const auto& material = customMaterialInfo.m_material ? customMaterialInfo.m_material : mesh.m_material;
  1837. if (!material)
  1838. {
  1839. AZ_Warning("MeshFeatureProcessor", false, "No material provided for mesh. Skipping.");
  1840. continue;
  1841. }
  1842. auto& objectSrgLayout = material->GetAsset()->GetObjectSrgLayout();
  1843. if (!objectSrgLayout)
  1844. {
  1845. AZ_Warning("MeshFeatureProcessor", false, "No per-object ShaderResourceGroup found.");
  1846. continue;
  1847. }
  1848. Data::Instance<RPI::ShaderResourceGroup> meshObjectSrg;
  1849. // Note: If the material uses the SceneMaterialSrg, the ObjectSRG holds the
  1850. // materialType and Instance-ID, and needs to be unique for each submesh.
  1851. // TODO: We can avoid a separate ObjectSRG for each submesh if we move the data from the SceneMaterialSrg to the SceneSrg,
  1852. // and create a MaterialSrg again that only holds the materialType and Instance-ID
  1853. if (!material->UsesSceneMaterialSrg())
  1854. {
  1855. // See if the object SRG for this mesh is already in our list of object SRGs
  1856. for (auto& objectSrgIter : m_objectSrgList)
  1857. {
  1858. if (objectSrgIter->GetLayout()->GetHash() == objectSrgLayout->GetHash())
  1859. {
  1860. meshObjectSrg = objectSrgIter;
  1861. }
  1862. }
  1863. }
  1864. // If the object SRG for this mesh was not already in the list, create it and add it to the list
  1865. if (!meshObjectSrg)
  1866. {
  1867. auto& shaderAsset = material->GetAsset()->GetMaterialTypeAsset()->GetShaderAssetForObjectSrg();
  1868. meshObjectSrg = RPI::ShaderResourceGroup::Create(shaderAsset, objectSrgLayout->GetName());
  1869. if (!meshObjectSrg)
  1870. {
  1871. AZ_Warning("MeshFeatureProcessor", false, "Failed to create a new shader resource group, skipping.");
  1872. continue;
  1873. }
  1874. // Set the material-Id and materialInstance-Id
  1875. if (material->UsesSceneMaterialSrg())
  1876. {
  1877. {
  1878. RHI::ShaderInputNameIndex nameIndex(AZ_NAME_LITERAL("m_materialTypeId"));
  1879. meshObjectSrg->SetConstant(nameIndex, material->GetMaterialTypeId());
  1880. }
  1881. {
  1882. RHI::ShaderInputNameIndex nameIndex(AZ_NAME_LITERAL("m_materialInstanceId"));
  1883. meshObjectSrg->SetConstant(nameIndex, material->GetMaterialInstanceId());
  1884. }
  1885. }
  1886. m_objectSrgCreatedEvent.Signal(meshObjectSrg);
  1887. m_objectSrgList.push_back(meshObjectSrg);
  1888. }
  1889. bool materialRequiresForwardPassIblSpecular = MaterialRequiresForwardPassIblSpecular(material);
  1890. // Track whether any materials in this mesh require ForwardPassIblSpecular, we need this information when the ObjectSrg is
  1891. // updated
  1892. m_flags.m_hasForwardPassIblSpecularMaterial |= materialRequiresForwardPassIblSpecular;
  1893. MeshInstanceManager::InsertResult instanceGroupInsertResult{ MeshInstanceManager::Handle{}, 0 };
  1894. MeshInstancingSupport instancingSupport;
  1895. if (r_meshInstancingEnabled)
  1896. {
  1897. // Get the instance index for referencing the draw packet
  1898. MeshInstanceGroupKey key{};
  1899. // Only meshes from the same model and lod with a matching material instance can be instanced
  1900. key.m_modelId = m_model->GetId();
  1901. key.m_lodIndex = static_cast<uint32_t>(modelLodIndex);
  1902. key.m_meshIndex = static_cast<uint32_t>(meshIndex);
  1903. key.m_materialId = material->GetId();
  1904. // Two meshes that could otherwise be instanced but have manually specified sort keys will not be instanced together
  1905. key.m_sortKey = m_sortKey;
  1906. instancingSupport = CanSupportInstancing(
  1907. material, m_flags.m_hasForwardPassIblSpecularMaterial, meshFeatureProcessor->GetTransparentDrawListTag());
  1908. if (instancingSupport.m_canSupportInstancing && !r_meshInstancingDebugForceUniqueObjectsForProfiling)
  1909. {
  1910. // If this object can be instanced, it gets a null uuid that will match other objects that can be instanced with it
  1911. key.m_forceInstancingOff = Uuid::CreateNull();
  1912. }
  1913. else
  1914. {
  1915. // When instancing is enabled, everything goes down the instancing path, including this object
  1916. // However, using a random uuid here will give it its own unique instance group, with it's own unique ObjectSrg,
  1917. // so it will end up as an instanced draw call with a count of 1
  1918. // We also use this path when r_meshInstancingDebugForceUniqueObjectsForProfiling is true, which makes meshes that
  1919. // would otherwise be instanced end up in a unique group. This is helpful for performance profiling to test the
  1920. // worst case scenario of lots of objects that don't actually end up getting instanced but still go down the
  1921. // instancing path
  1922. key.m_forceInstancingOff = Uuid::CreateRandom();
  1923. }
  1924. instanceGroupInsertResult = meshInstanceManager.AddInstance(key);
  1925. PostCullingInstanceData postCullingData;
  1926. postCullingData.m_instanceGroupHandle = instanceGroupInsertResult.m_handle;
  1927. postCullingData.m_instanceGroupPageIndex = instanceGroupInsertResult.m_pageIndex;
  1928. postCullingData.m_objectId = m_objectId;
  1929. // Mark the group as transparent so that the depth can be sorted in reverse
  1930. postCullingData.m_instanceGroupHandle->m_isTransparent = instancingSupport.m_isTransparent;
  1931. m_postCullingInstanceDataByLod[modelLodIndex].push_back(postCullingData);
  1932. // The instaceGroup needs to keep a reference of this ModelDataInstance so it can
  1933. // notify the ModelDataInstance when the MeshDrawPacket is changed or get the cullable's flags
  1934. instanceGroupInsertResult.m_handle->AddAssociatedInstance(this);
  1935. }
  1936. // If this condition is true, we're dealing with a new, uninitialized draw packet, either because instancing is disabled
  1937. // or because this was the first object in the instance group. So we need to initialize it
  1938. if (!r_meshInstancingEnabled || instanceGroupInsertResult.m_instanceCount == 1)
  1939. {
  1940. // setup the mesh draw packet
  1941. RPI::MeshDrawPacket drawPacket(modelLod, meshIndex, material, meshObjectSrg, customMaterialInfo.m_uvMapping);
  1942. // set the shader option to select forward pass IBL specular if necessary
  1943. if (!drawPacket.SetShaderOption(s_o_meshUseForwardPassIBLSpecular_Name, AZ::RPI::ShaderOptionValue{ m_descriptor.m_useForwardPassIblSpecular }))
  1944. {
  1945. AZ_Warning("MeshDrawPacket", false, "Failed to set o_meshUseForwardPassIBLSpecular on mesh draw packet");
  1946. }
  1947. if (instancingSupport.m_canSupportInstancing)
  1948. {
  1949. drawPacket.SetShaderOption(s_o_meshInstancingIsEnabled_Name, AZ::RPI::ShaderOptionValue{ true });
  1950. }
  1951. bool blockSilhouettes = false;
  1952. if (auto index = material->FindPropertyIndex(s_block_silhouette_Name); index.IsValid())
  1953. {
  1954. blockSilhouettes = material->GetPropertyValue<bool>(index);
  1955. }
  1956. // stencil bits
  1957. uint8_t stencilRef = m_descriptor.m_useForwardPassIblSpecular || materialRequiresForwardPassIblSpecular
  1958. ? Render::StencilRefs::None
  1959. : Render::StencilRefs::UseIBLSpecularPass;
  1960. stencilRef |= Render::StencilRefs::UseDiffuseGIPass;
  1961. stencilRef |= blockSilhouettes ? Render::StencilRefs::BlockSilhouettes : 0;
  1962. drawPacket.SetStencilRef(stencilRef);
  1963. drawPacket.SetSortKey(m_sortKey);
  1964. drawPacket.SetEnableDraw(meshMotionDrawListTag, m_flags.m_isDrawMotion);
  1965. // Note: do not add drawPacket.Update() here. It's not needed.It may cause issue with m_shaderVariantHandler which captures 'this' pointer.
  1966. if (!r_meshInstancingEnabled)
  1967. {
  1968. m_meshDrawPacketListsByLod[modelLodIndex].emplace_back(AZStd::move(drawPacket));
  1969. }
  1970. else
  1971. {
  1972. MeshInstanceGroupData& instanceGroupData = meshInstanceManager[instanceGroupInsertResult.m_handle];
  1973. instanceGroupData.m_drawPacket = AZStd::move(drawPacket);
  1974. instanceGroupData.m_isDrawMotion = m_flags.m_isDrawMotion;
  1975. // We're going to need an interval for the root constant data that we update every frame for each draw item, so cache that here
  1976. CacheRootConstantInterval(instanceGroupData);
  1977. }
  1978. }
  1979. // For mesh instancing only
  1980. // If this model needs to draw motion, enable draw motion vector for the DrawPacket.
  1981. // This means any mesh instances which are using this draw packet would draw motion vector too. This is fine, just not optimized.
  1982. if (r_meshInstancingEnabled && m_flags.m_isDrawMotion)
  1983. {
  1984. MeshInstanceGroupData& instanceGroupData = meshInstanceManager[instanceGroupInsertResult.m_handle];
  1985. if (!instanceGroupData.m_isDrawMotion)
  1986. {
  1987. instanceGroupData.m_isDrawMotion = true;
  1988. instanceGroupData.m_drawPacket.SetEnableDraw(meshMotionDrawListTag, true);
  1989. }
  1990. }
  1991. }
  1992. }
  1993. void ModelDataInstance::SetRayTracingData(MeshFeatureProcessor* meshFeatureProcessor)
  1994. {
  1995. RayTracingFeatureProcessor* rayTracingFeatureProcessor = meshFeatureProcessor->GetRayTracingFeatureProcessor();
  1996. TransformServiceFeatureProcessor* transformServiceFeatureProcessor =
  1997. meshFeatureProcessor->GetTransformServiceFeatureProcessor();
  1998. RemoveRayTracingData(rayTracingFeatureProcessor);
  1999. if (!m_model)
  2000. {
  2001. return;
  2002. }
  2003. if (!rayTracingFeatureProcessor)
  2004. {
  2005. return;
  2006. }
  2007. const AZStd::span<const Data::Instance<RPI::ModelLod>>& modelLods = m_model->GetLods();
  2008. if (modelLods.empty())
  2009. {
  2010. return;
  2011. }
  2012. // use the lowest LOD for raytracing
  2013. uint32_t rayTracingLod = aznumeric_cast<uint32_t>(modelLods.size() - 1);
  2014. const Data::Instance<RPI::ModelLod>& modelLod = modelLods[rayTracingLod];
  2015. // setup a stream layout and shader input contract for the vertex streams
  2016. static const char* PositionSemantic = "POSITION";
  2017. static const char* NormalSemantic = "NORMAL";
  2018. static const char* TangentSemantic = "TANGENT";
  2019. static const char* BitangentSemantic = "BITANGENT";
  2020. static const char* UVSemantic = "UV";
  2021. static const RHI::Format PositionStreamFormat = RHI::Format::R32G32B32_FLOAT;
  2022. static const RHI::Format NormalStreamFormat = RHI::Format::R32G32B32_FLOAT;
  2023. static const RHI::Format TangentStreamFormat = RHI::Format::R32G32B32A32_FLOAT;
  2024. static const RHI::Format BitangentStreamFormat = RHI::Format::R32G32B32_FLOAT;
  2025. static const RHI::Format UVStreamFormat = RHI::Format::R32G32_FLOAT;
  2026. RPI::ShaderInputContract::StreamChannelInfo positionStreamChannelInfo;
  2027. positionStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(PositionSemantic));
  2028. positionStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(PositionStreamFormat);
  2029. RPI::ShaderInputContract::StreamChannelInfo normalStreamChannelInfo;
  2030. normalStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(NormalSemantic));
  2031. normalStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(NormalStreamFormat);
  2032. RPI::ShaderInputContract::StreamChannelInfo tangentStreamChannelInfo;
  2033. tangentStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(TangentSemantic));
  2034. tangentStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(TangentStreamFormat);
  2035. tangentStreamChannelInfo.m_isOptional = true;
  2036. RPI::ShaderInputContract::StreamChannelInfo bitangentStreamChannelInfo;
  2037. bitangentStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(BitangentSemantic));
  2038. bitangentStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(BitangentStreamFormat);
  2039. bitangentStreamChannelInfo.m_isOptional = true;
  2040. RPI::ShaderInputContract::StreamChannelInfo uvStreamChannelInfo;
  2041. uvStreamChannelInfo.m_semantic = RHI::ShaderSemantic(AZ::Name(UVSemantic));
  2042. uvStreamChannelInfo.m_componentCount = RHI::GetFormatComponentCount(UVStreamFormat);
  2043. uvStreamChannelInfo.m_isOptional = true;
  2044. RPI::ShaderInputContract shaderInputContract;
  2045. shaderInputContract.m_streamChannels.emplace_back(positionStreamChannelInfo);
  2046. shaderInputContract.m_streamChannels.emplace_back(normalStreamChannelInfo);
  2047. shaderInputContract.m_streamChannels.emplace_back(tangentStreamChannelInfo);
  2048. shaderInputContract.m_streamChannels.emplace_back(bitangentStreamChannelInfo);
  2049. shaderInputContract.m_streamChannels.emplace_back(uvStreamChannelInfo);
  2050. // setup the raytracing data for each sub-mesh
  2051. const size_t meshCount = modelLod->GetMeshes().size();
  2052. RayTracingFeatureProcessor::SubMeshVector subMeshes;
  2053. for (uint32_t meshIndex = 0; meshIndex < meshCount; ++meshIndex)
  2054. {
  2055. const auto meshes = modelLod->GetMeshes();
  2056. const RPI::ModelLod::Mesh& mesh = meshes[meshIndex];
  2057. // retrieve the material
  2058. const CustomMaterialId customMaterialId(rayTracingLod, mesh.m_materialSlotStableId);
  2059. const auto& customMaterialInfo = GetCustomMaterialWithFallback(customMaterialId);
  2060. const auto& material = customMaterialInfo.m_material ? customMaterialInfo.m_material : mesh.m_material;
  2061. if (!material)
  2062. {
  2063. AZ_Warning("MeshFeatureProcessor", false, "No material provided for mesh. Skipping.");
  2064. continue;
  2065. }
  2066. // retrieve vertex/index buffers
  2067. RHI::InputStreamLayout inputStreamLayout;
  2068. RHI::StreamBufferIndices streamIndices;
  2069. [[maybe_unused]] bool result = modelLod->GetStreamsForMesh(
  2070. inputStreamLayout,
  2071. streamIndices,
  2072. nullptr,
  2073. shaderInputContract,
  2074. meshIndex,
  2075. customMaterialInfo.m_uvMapping,
  2076. material->GetAsset()->GetMaterialTypeAsset()->GetUvNameMap());
  2077. AZ_Assert(result, "Failed to retrieve mesh stream buffer views");
  2078. // The code below expects streams for positions, normals, tangents, bitangents, and uvs.
  2079. constexpr size_t NumExpectedStreams = 5;
  2080. if (streamIndices.Size() < NumExpectedStreams)
  2081. {
  2082. AZ_Warning("MeshFeatureProcessor", false, "Model is missing one or more expected streams "
  2083. "(positions, normals, tangents, bitangents, uvs), skipping the raytracing data generation.");
  2084. continue;
  2085. }
  2086. auto streamIter = mesh.CreateStreamIterator(streamIndices);
  2087. // note that the element count is the size of the entire buffer, even though this mesh may only
  2088. // occupy a portion of the vertex buffer. This is necessary since we are accessing it using
  2089. // a ByteAddressBuffer in the raytracing shaders and passing the byte offset to the shader in a constant buffer.
  2090. uint32_t positionBufferByteCount = static_cast<uint32_t>(const_cast<RHI::Buffer*>(streamIter[0].GetBuffer())->GetDescriptor().m_byteCount);
  2091. RHI::BufferViewDescriptor positionBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, positionBufferByteCount);
  2092. uint32_t normalBufferByteCount = static_cast<uint32_t>(const_cast<RHI::Buffer*>(streamIter[1].GetBuffer())->GetDescriptor().m_byteCount);
  2093. RHI::BufferViewDescriptor normalBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, normalBufferByteCount);
  2094. uint32_t tangentBufferByteCount = static_cast<uint32_t>(const_cast<RHI::Buffer*>(streamIter[2].GetBuffer())->GetDescriptor().m_byteCount);
  2095. RHI::BufferViewDescriptor tangentBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, tangentBufferByteCount);
  2096. uint32_t bitangentBufferByteCount = static_cast<uint32_t>(const_cast<RHI::Buffer*>(streamIter[3].GetBuffer())->GetDescriptor().m_byteCount);
  2097. RHI::BufferViewDescriptor bitangentBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, bitangentBufferByteCount);
  2098. uint32_t uvBufferByteCount = static_cast<uint32_t>(const_cast<RHI::Buffer*>(streamIter[4].GetBuffer())->GetDescriptor().m_byteCount);
  2099. RHI::BufferViewDescriptor uvBufferDescriptor = RHI::BufferViewDescriptor::CreateRaw(0, uvBufferByteCount);
  2100. const RHI::IndexBufferView& indexBufferView = mesh.GetIndexBufferView();
  2101. uint32_t indexElementSize = indexBufferView.GetIndexFormat() == RHI::IndexFormat::Uint16 ? 2 : 4;
  2102. uint32_t indexElementCount = (uint32_t)indexBufferView.GetBuffer()->GetDescriptor().m_byteCount / indexElementSize;
  2103. RHI::BufferViewDescriptor indexBufferDescriptor;
  2104. indexBufferDescriptor.m_elementOffset = 0;
  2105. indexBufferDescriptor.m_elementCount = indexElementCount;
  2106. indexBufferDescriptor.m_elementSize = indexElementSize;
  2107. indexBufferDescriptor.m_elementFormat = indexBufferView.GetIndexFormat() == RHI::IndexFormat::Uint16 ? RHI::Format::R16_UINT : RHI::Format::R32_UINT;
  2108. // set the SubMesh data to pass to the RayTracingFeatureProcessor, starting with vertex/index data
  2109. RayTracingFeatureProcessor::SubMesh subMesh;
  2110. RayTracingFeatureProcessor::SubMeshMaterial& subMeshMaterial = subMesh.m_material;
  2111. subMesh.m_positionFormat = RHI::ConvertToVertexFormat(PositionStreamFormat);
  2112. subMesh.m_positionVertexBufferView = streamIter[0];
  2113. subMesh.m_positionShaderBufferView =
  2114. const_cast<RHI::Buffer*>(streamIter[0].GetBuffer())->GetBufferView(positionBufferDescriptor);
  2115. subMesh.m_normalFormat = RHI::ConvertToVertexFormat(NormalStreamFormat);
  2116. subMesh.m_normalVertexBufferView = streamIter[1];
  2117. subMesh.m_normalShaderBufferView =
  2118. const_cast<RHI::Buffer*>(streamIter[1].GetBuffer())->GetBufferView(normalBufferDescriptor);
  2119. if (tangentBufferByteCount > 0)
  2120. {
  2121. subMesh.m_bufferFlags |= RayTracingSubMeshBufferFlags::Tangent;
  2122. subMesh.m_tangentFormat = RHI::ConvertToVertexFormat(TangentStreamFormat);
  2123. subMesh.m_tangentVertexBufferView = streamIter[2];
  2124. subMesh.m_tangentShaderBufferView =
  2125. const_cast<RHI::Buffer*>(streamIter[2].GetBuffer())->GetBufferView(tangentBufferDescriptor);
  2126. }
  2127. if (bitangentBufferByteCount > 0)
  2128. {
  2129. subMesh.m_bufferFlags |= RayTracingSubMeshBufferFlags::Bitangent;
  2130. subMesh.m_bitangentFormat = RHI::ConvertToVertexFormat(BitangentStreamFormat);
  2131. subMesh.m_bitangentVertexBufferView = streamIter[3];
  2132. subMesh.m_bitangentShaderBufferView =
  2133. const_cast<RHI::Buffer*>(streamIter[3].GetBuffer())->GetBufferView(bitangentBufferDescriptor);
  2134. }
  2135. if (uvBufferByteCount > 0)
  2136. {
  2137. subMesh.m_bufferFlags |= RayTracingSubMeshBufferFlags::UV;
  2138. subMesh.m_uvFormat = RHI::ConvertToVertexFormat(UVStreamFormat);
  2139. subMesh.m_uvVertexBufferView = streamIter[4];
  2140. subMesh.m_uvShaderBufferView = const_cast<RHI::Buffer*>(streamIter[4].GetBuffer())->GetBufferView(uvBufferDescriptor);
  2141. }
  2142. subMesh.m_indexBufferView = mesh.GetIndexBufferView();
  2143. subMesh.m_indexShaderBufferView =
  2144. const_cast<RHI::Buffer*>(mesh.GetIndexBufferView().GetBuffer())->GetBufferView(indexBufferDescriptor);
  2145. // add material data
  2146. if (material)
  2147. {
  2148. RPI::MaterialPropertyIndex propertyIndex;
  2149. // base color
  2150. propertyIndex = material->FindPropertyIndex(s_baseColor_color_Name);
  2151. if (propertyIndex.IsValid())
  2152. {
  2153. subMeshMaterial.m_baseColor = material->GetPropertyValue<AZ::Color>(propertyIndex);
  2154. }
  2155. propertyIndex = material->FindPropertyIndex(s_baseColor_factor_Name);
  2156. if (propertyIndex.IsValid())
  2157. {
  2158. subMeshMaterial.m_baseColor *= material->GetPropertyValue<float>(propertyIndex);
  2159. }
  2160. // metallic
  2161. propertyIndex = material->FindPropertyIndex(s_metallic_factor_Name);
  2162. if (propertyIndex.IsValid())
  2163. {
  2164. subMeshMaterial.m_metallicFactor = material->GetPropertyValue<float>(propertyIndex);
  2165. }
  2166. // roughness
  2167. propertyIndex = material->FindPropertyIndex(s_roughness_factor_Name);
  2168. if (propertyIndex.IsValid())
  2169. {
  2170. subMeshMaterial.m_roughnessFactor = material->GetPropertyValue<float>(propertyIndex);
  2171. }
  2172. // emissive color
  2173. propertyIndex = material->FindPropertyIndex(s_emissive_enable_Name);
  2174. if (propertyIndex.IsValid())
  2175. {
  2176. if (material->GetPropertyValue<bool>(propertyIndex))
  2177. {
  2178. propertyIndex = material->FindPropertyIndex(s_emissive_color_Name);
  2179. if (propertyIndex.IsValid())
  2180. {
  2181. subMeshMaterial.m_emissiveColor = material->GetPropertyValue<AZ::Color>(propertyIndex);
  2182. }
  2183. // When we have an emissive intensity, the unit of the intensity is defined in the material settings.
  2184. // For non-raytracing materials, the intensity is converted, and set in the shader, by a Functor.
  2185. // This (and the other) Functors are normally called in the Compile function of the Material
  2186. // We can't use the Compile function here, because the raytracing material behaves bit differently
  2187. // Therefor we need to look for the right Functor to convert the intensity here
  2188. propertyIndex = material->FindPropertyIndex(s_emissive_intensity_Name);
  2189. if (propertyIndex.IsValid())
  2190. {
  2191. auto unitPropertyIndex = material->FindPropertyIndex(s_emissive_unit_Name);
  2192. AZ_WarningOnce(
  2193. "MeshFeatureProcessor",
  2194. propertyIndex.IsValid(),
  2195. "Emissive intensity property missing in material %s. Materials with an emissive intensity need a unit for the intensity.",
  2196. material->GetAsset()->GetId().ToFixedString().c_str());
  2197. if (unitPropertyIndex.IsValid())
  2198. {
  2199. auto intensity = material->GetPropertyValue<float>(propertyIndex);
  2200. auto unit = material->GetPropertyValue<uint32_t>(unitPropertyIndex);
  2201. bool foundEmissiveUnitFunctor = false;
  2202. for (const auto& functor : material->GetAsset()->GetMaterialFunctors())
  2203. {
  2204. auto emissiveFunctor = azdynamic_cast<ConvertEmissiveUnitFunctor*>(functor);
  2205. if (emissiveFunctor != nullptr)
  2206. {
  2207. intensity = emissiveFunctor->GetProcessedValue(intensity, unit);
  2208. foundEmissiveUnitFunctor = true;
  2209. break;
  2210. }
  2211. }
  2212. AZ_WarningOnce(
  2213. "MeshFeatureProcessor",
  2214. foundEmissiveUnitFunctor,
  2215. "Could not find ConvertEmissiveUnitFunctor for material %s",
  2216. material->GetAsset()->GetId().ToFixedString().c_str());
  2217. if (foundEmissiveUnitFunctor)
  2218. {
  2219. subMeshMaterial.m_emissiveColor *= intensity;
  2220. }
  2221. }
  2222. }
  2223. }
  2224. }
  2225. // textures
  2226. Data::Instance<RPI::Image> baseColorImage; // can be used for irradiance color below
  2227. propertyIndex = material->FindPropertyIndex(s_baseColor_textureMap_Name);
  2228. if (propertyIndex.IsValid())
  2229. {
  2230. Data::Instance<RPI::Image> image = material->GetPropertyValue<Data::Instance<RPI::Image>>(propertyIndex);
  2231. if (image.get())
  2232. {
  2233. subMeshMaterial.m_textureFlags |= RayTracingSubMeshTextureFlags::BaseColor;
  2234. subMeshMaterial.m_baseColorImageView = image->GetImageView();
  2235. baseColorImage = image;
  2236. }
  2237. }
  2238. propertyIndex = material->FindPropertyIndex(s_normal_textureMap_Name);
  2239. if (propertyIndex.IsValid())
  2240. {
  2241. Data::Instance<RPI::Image> image = material->GetPropertyValue<Data::Instance<RPI::Image>>(propertyIndex);
  2242. if (image.get())
  2243. {
  2244. subMeshMaterial.m_textureFlags |= RayTracingSubMeshTextureFlags::Normal;
  2245. subMeshMaterial.m_normalImageView = image->GetImageView();
  2246. }
  2247. }
  2248. propertyIndex = material->FindPropertyIndex(s_metallic_textureMap_Name);
  2249. if (propertyIndex.IsValid())
  2250. {
  2251. Data::Instance<RPI::Image> image = material->GetPropertyValue<Data::Instance<RPI::Image>>(propertyIndex);
  2252. if (image.get())
  2253. {
  2254. subMeshMaterial.m_textureFlags |= RayTracingSubMeshTextureFlags::Metallic;
  2255. subMeshMaterial.m_metallicImageView = image->GetImageView();
  2256. }
  2257. }
  2258. propertyIndex = material->FindPropertyIndex(s_roughness_textureMap_Name);
  2259. if (propertyIndex.IsValid())
  2260. {
  2261. Data::Instance<RPI::Image> image = material->GetPropertyValue<Data::Instance<RPI::Image>>(propertyIndex);
  2262. if (image.get())
  2263. {
  2264. subMeshMaterial.m_textureFlags |= RayTracingSubMeshTextureFlags::Roughness;
  2265. subMeshMaterial.m_roughnessImageView = image->GetImageView();
  2266. }
  2267. }
  2268. propertyIndex = material->FindPropertyIndex(s_emissive_textureMap_Name);
  2269. if (propertyIndex.IsValid())
  2270. {
  2271. Data::Instance<RPI::Image> image = material->GetPropertyValue<Data::Instance<RPI::Image>>(propertyIndex);
  2272. if (image.get())
  2273. {
  2274. subMeshMaterial.m_textureFlags |= RayTracingSubMeshTextureFlags::Emissive;
  2275. subMeshMaterial.m_emissiveImageView = image->GetImageView();
  2276. }
  2277. }
  2278. // irradiance color
  2279. SetIrradianceData(subMesh, material, baseColorImage);
  2280. }
  2281. subMeshes.push_back(subMesh);
  2282. }
  2283. // setup the RayTracing Mesh
  2284. RayTracingFeatureProcessor::Mesh rayTracingMesh;
  2285. rayTracingMesh.m_assetId = m_model->GetModelAsset()->GetId();
  2286. rayTracingMesh.m_transform = transformServiceFeatureProcessor->GetTransformForId(m_objectId);
  2287. rayTracingMesh.m_nonUniformScale = transformServiceFeatureProcessor->GetNonUniformScaleForId(m_objectId);
  2288. rayTracingMesh.m_isSkinnedMesh = m_descriptor.m_isSkinnedMesh;
  2289. rayTracingMesh.m_instanceMask |= (rayTracingMesh.m_isSkinnedMesh)
  2290. ? static_cast<uint32_t>(AZ::RHI::RayTracingAccelerationStructureInstanceInclusionMask::SKINNED_MESH)
  2291. : static_cast<uint32_t>(AZ::RHI::RayTracingAccelerationStructureInstanceInclusionMask::STATIC_MESH);
  2292. // setup the reflection probe data, and track if this mesh is currently affected by a reflection probe
  2293. SetRayTracingReflectionProbeData(meshFeatureProcessor, rayTracingMesh.m_reflectionProbe);
  2294. // add the mesh
  2295. rayTracingFeatureProcessor->AddMesh(m_rayTracingUuid, rayTracingMesh, subMeshes);
  2296. m_flags.m_needsSetRayTracingData = false;
  2297. }
  2298. void ModelDataInstance::SetIrradianceData(
  2299. RayTracingFeatureProcessor::SubMesh& subMesh,
  2300. const Data::Instance<RPI::Material> material,
  2301. const Data::Instance<RPI::Image> baseColorImage)
  2302. {
  2303. RPI::MaterialPropertyIndex propertyIndex = material->FindPropertyIndex(s_irradiance_irradianceColorSource_Name);
  2304. if (!propertyIndex.IsValid())
  2305. {
  2306. return;
  2307. }
  2308. uint32_t enumVal = material->GetPropertyValue<uint32_t>(propertyIndex);
  2309. AZ::Name irradianceColorSource = material->GetMaterialPropertiesLayout()->GetPropertyDescriptor(propertyIndex)->GetEnumName(enumVal);
  2310. RayTracingFeatureProcessor::SubMeshMaterial& subMeshMaterial = subMesh.m_material;
  2311. if (irradianceColorSource.IsEmpty() || irradianceColorSource == s_Manual_Name)
  2312. {
  2313. propertyIndex = material->FindPropertyIndex(s_irradiance_manualColor_Name);
  2314. if (propertyIndex.IsValid())
  2315. {
  2316. subMeshMaterial.m_irradianceColor = material->GetPropertyValue<AZ::Color>(propertyIndex);
  2317. }
  2318. else
  2319. {
  2320. // Couldn't find irradiance.manualColor -> check for an irradiance.color in case the material type
  2321. // doesn't have the concept of manual vs. automatic irradiance color, allow a simpler property name
  2322. propertyIndex = material->FindPropertyIndex(s_irradiance_color_Name);
  2323. if (propertyIndex.IsValid())
  2324. {
  2325. subMeshMaterial.m_irradianceColor = material->GetPropertyValue<AZ::Color>(propertyIndex);
  2326. }
  2327. else
  2328. {
  2329. AZ_Warning(
  2330. "MeshFeatureProcessor", false,
  2331. "No irradiance.manualColor or irradiance.color field found. Defaulting to 1.0f.");
  2332. subMeshMaterial.m_irradianceColor = AZ::Colors::White;
  2333. }
  2334. }
  2335. }
  2336. else if (irradianceColorSource == s_BaseColorTint_Name)
  2337. {
  2338. // Use only the baseColor, no texture on top of it
  2339. subMeshMaterial.m_irradianceColor = subMeshMaterial.m_baseColor;
  2340. }
  2341. else if (irradianceColorSource == s_BaseColor_Name)
  2342. {
  2343. // Check if texturing is enabled
  2344. bool useTexture;
  2345. propertyIndex = material->FindPropertyIndex(s_baseColor_useTexture_Name);
  2346. if (propertyIndex.IsValid())
  2347. {
  2348. useTexture = material->GetPropertyValue<bool>(propertyIndex);
  2349. }
  2350. else
  2351. {
  2352. // No explicit baseColor.useTexture switch found, assuming the user wants to use
  2353. // a texture if a texture was found.
  2354. useTexture = true;
  2355. }
  2356. // If texturing was requested: check if we found a texture and use it
  2357. if (useTexture && baseColorImage.get())
  2358. {
  2359. // Currently GetAverageColor() is only implemented for a StreamingImage
  2360. auto baseColorStreamingImg = azdynamic_cast<RPI::StreamingImage*>(baseColorImage.get());
  2361. if (baseColorStreamingImg)
  2362. {
  2363. // Note: there are quite a few hidden assumptions in using the average
  2364. // texture color. For instance, (1) it assumes that every texel in the
  2365. // texture actually gets mapped to the surface (or non-mapped regions are
  2366. // colored with a meaningful 'average' color, or have zero opacity); (2) it
  2367. // assumes that the mapping from uv space to the mesh surface is
  2368. // (approximately) area-preserving to get a properly weighted average; and
  2369. // mostly, (3) it assumes that a single 'average color' is a meaningful
  2370. // characterisation of the full material.
  2371. Color avgColor = baseColorStreamingImg->GetAverageColor();
  2372. // We do a simple 'multiply' blend with the base color
  2373. // Note: other blend modes are currently not supported
  2374. subMeshMaterial.m_irradianceColor = avgColor * subMeshMaterial.m_baseColor;
  2375. }
  2376. else
  2377. {
  2378. AZ_Warning("MeshFeatureProcessor", false, "Using BaseColor as irradianceColorSource "
  2379. "is currently only supported for textures of type StreamingImage");
  2380. // Default to the flat base color
  2381. subMeshMaterial.m_irradianceColor = subMeshMaterial.m_baseColor;
  2382. }
  2383. }
  2384. else
  2385. {
  2386. // No texture, simply copy the baseColor
  2387. subMeshMaterial.m_irradianceColor = subMeshMaterial.m_baseColor;
  2388. }
  2389. }
  2390. else
  2391. {
  2392. AZ_Warning("MeshFeatureProcessor", false, "Unknown irradianceColorSource value: %s, "
  2393. "defaulting to 1.0f.", irradianceColorSource.GetCStr());
  2394. subMeshMaterial.m_irradianceColor = AZ::Colors::White;
  2395. }
  2396. // Overall scale factor
  2397. propertyIndex = material->FindPropertyIndex(s_irradiance_factor_Name);
  2398. if (propertyIndex.IsValid())
  2399. {
  2400. subMeshMaterial.m_irradianceColor *= material->GetPropertyValue<float>(propertyIndex);
  2401. }
  2402. // set the raytracing transparency from the material opacity factor
  2403. float opacity = 1.0f;
  2404. propertyIndex = material->FindPropertyIndex(s_opacity_mode_Name);
  2405. if (propertyIndex.IsValid())
  2406. {
  2407. // only query the opacity factor if it's a non-Opaque mode
  2408. uint32_t mode = material->GetPropertyValue<uint32_t>(propertyIndex);
  2409. if (mode > 0)
  2410. {
  2411. propertyIndex = material->FindPropertyIndex(s_opacity_factor_Name);
  2412. if (propertyIndex.IsValid())
  2413. {
  2414. opacity = material->GetPropertyValue<float>(propertyIndex);
  2415. }
  2416. }
  2417. }
  2418. subMeshMaterial.m_irradianceColor.SetA(opacity);
  2419. }
  2420. void ModelDataInstance::SetRayTracingReflectionProbeData(
  2421. MeshFeatureProcessor* meshFeatureProcessor,
  2422. RayTracingFeatureProcessor::Mesh::ReflectionProbe& reflectionProbe)
  2423. {
  2424. TransformServiceFeatureProcessor* transformServiceFeatureProcessor = meshFeatureProcessor->GetTransformServiceFeatureProcessor();
  2425. ReflectionProbeFeatureProcessor* reflectionProbeFeatureProcessor = meshFeatureProcessor->GetReflectionProbeFeatureProcessor();
  2426. AZ::Transform transform = transformServiceFeatureProcessor->GetTransformForId(m_objectId);
  2427. // retrieve reflection probes
  2428. Aabb aabbWS = m_aabb;
  2429. aabbWS.ApplyTransform(transform);
  2430. ReflectionProbeHandleVector reflectionProbeHandles;
  2431. reflectionProbeFeatureProcessor->FindReflectionProbes(aabbWS, reflectionProbeHandles);
  2432. m_flags.m_hasRayTracingReflectionProbe = !reflectionProbeHandles.empty();
  2433. if (m_flags.m_hasRayTracingReflectionProbe)
  2434. {
  2435. // take the last handle from the list, which will be the smallest (most influential) probe
  2436. ReflectionProbeHandle handle = reflectionProbeHandles.back();
  2437. reflectionProbe.m_modelToWorld = reflectionProbeFeatureProcessor->GetTransform(handle);
  2438. reflectionProbe.m_outerObbHalfLengths = reflectionProbeFeatureProcessor->GetOuterObbWs(handle).GetHalfLengths();
  2439. reflectionProbe.m_innerObbHalfLengths = reflectionProbeFeatureProcessor->GetInnerObbWs(handle).GetHalfLengths();
  2440. reflectionProbe.m_useParallaxCorrection = reflectionProbeFeatureProcessor->GetUseParallaxCorrection(handle);
  2441. reflectionProbe.m_exposure = reflectionProbeFeatureProcessor->GetRenderExposure(handle);
  2442. reflectionProbe.m_reflectionProbeCubeMap = reflectionProbeFeatureProcessor->GetCubeMap(handle);
  2443. }
  2444. }
  2445. void ModelDataInstance::RemoveRayTracingData(RayTracingFeatureProcessor* rayTracingFeatureProcessor)
  2446. {
  2447. // remove from ray tracing
  2448. if (rayTracingFeatureProcessor)
  2449. {
  2450. rayTracingFeatureProcessor->RemoveMesh(m_rayTracingUuid);
  2451. }
  2452. }
  2453. void ModelDataInstance::SetSortKey(MeshFeatureProcessor* meshFeatureProcessor, RHI::DrawItemSortKey sortKey)
  2454. {
  2455. RHI::DrawItemSortKey previousSortKey = m_sortKey;
  2456. m_sortKey = sortKey;
  2457. if (previousSortKey != m_sortKey)
  2458. {
  2459. if (!r_meshInstancingEnabled)
  2460. {
  2461. for (auto& drawPacketList : m_meshDrawPacketListsByLod)
  2462. {
  2463. for (auto& drawPacket : drawPacketList)
  2464. {
  2465. drawPacket.SetSortKey(sortKey);
  2466. }
  2467. }
  2468. }
  2469. else
  2470. {
  2471. // If the ModelDataInstance has already been initialized
  2472. if (m_model && !m_flags.m_needsInit)
  2473. {
  2474. // DeInit/ReInit is overkill (destroys and re-creates ray-tracing data)
  2475. // but it works for now since SetSortKey is infrequent
  2476. // Init needs to be called because that is where we determine what can be part of the same instance group,
  2477. // and the sort key is part of that.
  2478. ReInit(meshFeatureProcessor);
  2479. }
  2480. }
  2481. }
  2482. }
  2483. RHI::DrawItemSortKey ModelDataInstance::GetSortKey() const
  2484. {
  2485. return m_sortKey;
  2486. }
  2487. void ModelDataInstance::SetMeshLodConfiguration(RPI::Cullable::LodConfiguration meshLodConfig)
  2488. {
  2489. m_cullable.m_lodData.m_lodConfiguration = meshLodConfig;
  2490. }
  2491. RPI::Cullable::LodConfiguration ModelDataInstance::GetMeshLodConfiguration() const
  2492. {
  2493. return m_cullable.m_lodData.m_lodConfiguration;
  2494. }
  2495. void ModelDataInstance::UpdateDrawPackets(bool forceUpdate /*= false*/)
  2496. {
  2497. AZ_Assert(!r_meshInstancingEnabled, "If mesh instancing is enabled, the draw packet update should be going through the MeshInstanceManager.");
  2498. // Only enable draw motion if model is dynamic and draw motion was disabled
  2499. bool enableDrawMotion = !m_flags.m_isDrawMotion && m_flags.m_dynamic;
  2500. RHI::DrawListTag meshMotionDrawListTag;
  2501. if (enableDrawMotion)
  2502. {
  2503. meshMotionDrawListTag = AZ::RHI::RHISystemInterface::Get()->GetDrawListTagRegistry()->FindTag(MeshCommon::MotionDrawListTagName);
  2504. }
  2505. uint32_t lodIndex = 0;
  2506. for (auto& meshDrawPacketList : m_meshDrawPacketListsByLod)
  2507. {
  2508. uint32_t meshIndex = 0;
  2509. for (auto& meshDrawPacket : meshDrawPacketList)
  2510. {
  2511. if (enableDrawMotion)
  2512. {
  2513. meshDrawPacket.SetEnableDraw(meshMotionDrawListTag, true);
  2514. }
  2515. if (meshDrawPacket.Update(*m_scene, forceUpdate))
  2516. {
  2517. HandleDrawPacketUpdate(lodIndex, meshIndex, meshDrawPacket);
  2518. }
  2519. meshIndex++;
  2520. }
  2521. lodIndex++;
  2522. }
  2523. }
  2524. void ModelDataInstance::BuildCullable()
  2525. {
  2526. AZ_Assert(m_flags.m_cullableNeedsRebuild, "This function only needs to be called if the cullable to be rebuilt");
  2527. AZ_Assert(m_model, "The model has not finished loading yet");
  2528. RPI::Cullable::CullData& cullData = m_cullable.m_cullData;
  2529. RPI::Cullable::LodData& lodData = m_cullable.m_lodData;
  2530. const Aabb& localAabb = m_aabb;
  2531. lodData.m_lodSelectionRadius = 0.5f * localAabb.GetExtents().GetMaxElement();
  2532. const size_t modelLodCount = m_model->GetLodCount();
  2533. const auto& lodAssets = m_model->GetModelAsset()->GetLodAssets();
  2534. AZ_Assert(lodAssets.size() == modelLodCount, "Number of asset lods must match number of model lods");
  2535. AZ_Assert(m_lodBias <= modelLodCount - 1, "Incorrect lod bias");
  2536. lodData.m_lods.resize(modelLodCount);
  2537. cullData.m_drawListMask.reset();
  2538. const size_t lodCount = lodAssets.size();
  2539. for (size_t lodIndex = 0; lodIndex < lodCount; ++lodIndex)
  2540. {
  2541. //initialize the lod
  2542. RPI::Cullable::LodData::Lod& lod = lodData.m_lods[lodIndex];
  2543. // non-used lod (except if forced)
  2544. if (lodIndex < m_lodBias)
  2545. {
  2546. // set impossible screen coverage to disable it
  2547. lod.m_screenCoverageMax = 0.0f;
  2548. lod.m_screenCoverageMin = 1.0f;
  2549. }
  2550. else
  2551. {
  2552. if (lodIndex == m_lodBias)
  2553. {
  2554. //first lod
  2555. lod.m_screenCoverageMax = 1.0f;
  2556. }
  2557. else
  2558. {
  2559. //every other lod: use the previous lod's min
  2560. lod.m_screenCoverageMax = AZStd::GetMax(lodData.m_lods[lodIndex - 1].m_screenCoverageMin, lodData.m_lodConfiguration.m_minimumScreenCoverage);
  2561. }
  2562. if (lodIndex < lodAssets.size() - 1)
  2563. {
  2564. //first and middle lods: compute a stepdown value for the min
  2565. lod.m_screenCoverageMin = AZStd::GetMax(lodData.m_lodConfiguration.m_qualityDecayRate * lod.m_screenCoverageMax, lodData.m_lodConfiguration.m_minimumScreenCoverage);
  2566. }
  2567. else
  2568. {
  2569. //last lod: use MinimumScreenCoverage for the min
  2570. lod.m_screenCoverageMin = lodData.m_lodConfiguration.m_minimumScreenCoverage;
  2571. }
  2572. }
  2573. lod.m_drawPackets.clear();
  2574. if (!r_meshInstancingEnabled)
  2575. {
  2576. const RPI::MeshDrawPacketList& drawPacketList = m_meshDrawPacketListsByLod[lodIndex + m_lodBias];
  2577. for (const RPI::MeshDrawPacket& drawPacket : drawPacketList)
  2578. {
  2579. // If mesh instancing is disabled, get the draw packets directly from this ModelDataInstance
  2580. const RHI::DrawPacket* rhiDrawPacket = drawPacket.GetRHIDrawPacket();
  2581. if (rhiDrawPacket)
  2582. {
  2583. // OR-together all the drawListMasks (so we know which views to cull against)
  2584. cullData.m_drawListMask |= rhiDrawPacket->GetDrawListMask();
  2585. lod.m_drawPackets.push_back(rhiDrawPacket);
  2586. }
  2587. }
  2588. }
  2589. else
  2590. {
  2591. const PostCullingInstanceDataList& postCullingInstanceDataList = m_postCullingInstanceDataByLod[lodIndex + m_lodBias];
  2592. for (const ModelDataInstance::PostCullingInstanceData& postCullingData : postCullingInstanceDataList)
  2593. {
  2594. // If mesh instancing is enabled, get the draw packet from the MeshInstanceManager
  2595. const RHI::DrawPacket* rhiDrawPacket = postCullingData.m_instanceGroupHandle->m_drawPacket.GetRHIDrawPacket();
  2596. if (rhiDrawPacket)
  2597. {
  2598. // OR-together all the drawListMasks (so we know which views to cull against)
  2599. cullData.m_drawListMask |= rhiDrawPacket->GetDrawListMask();
  2600. }
  2601. // Set the user data for the cullable lod to reference the intance group handles for the lod
  2602. lod.m_visibleObjectUserData = static_cast<void*>(&m_postCullingInstanceDataByLod[lodIndex + m_lodBias]);
  2603. }
  2604. }
  2605. }
  2606. cullData.m_hideFlags = RPI::View::UsageNone;
  2607. if (m_descriptor.m_excludeFromReflectionCubeMaps)
  2608. {
  2609. cullData.m_hideFlags |= RPI::View::UsageReflectiveCubeMap;
  2610. }
  2611. #ifdef AZ_CULL_DEBUG_ENABLED
  2612. m_cullable.SetDebugName(AZ::Name(AZStd::string::format("%s - objectId: %u", m_model->GetModelAsset()->GetName().GetCStr(), m_objectId.GetIndex())));
  2613. #endif
  2614. m_flags.m_cullableNeedsRebuild = false;
  2615. m_flags.m_cullBoundsNeedsUpdate = true;
  2616. }
  2617. void ModelDataInstance::UpdateCullBounds(const MeshFeatureProcessor* meshFeatureProcessor)
  2618. {
  2619. AZ_Assert(m_flags.m_cullBoundsNeedsUpdate, "This function only needs to be called if the culling bounds need to be rebuilt");
  2620. AZ_Assert(m_model, "The model has not finished loading yet");
  2621. const TransformServiceFeatureProcessor* transformService = meshFeatureProcessor->GetTransformServiceFeatureProcessor();
  2622. Transform localToWorld = transformService->GetTransformForId(m_objectId);
  2623. Vector3 nonUniformScale = transformService->GetNonUniformScaleForId(m_objectId);
  2624. Vector3 center;
  2625. float radius;
  2626. Aabb localAabb = m_aabb;
  2627. localAabb.MultiplyByScale(nonUniformScale);
  2628. localAabb.GetTransformedAabb(localToWorld).GetAsSphere(center, radius);
  2629. m_cullable.m_lodData.m_lodSelectionRadius = 0.5f*localAabb.GetExtents().GetMaxElement();
  2630. m_cullable.m_cullData.m_boundingSphere = Sphere(center, radius);
  2631. m_cullable.m_cullData.m_boundingObb = localAabb.GetTransformedObb(localToWorld);
  2632. m_cullable.m_cullData.m_visibilityEntry.m_boundingVolume = localAabb.GetTransformedAabb(localToWorld);
  2633. m_cullable.m_cullData.m_visibilityEntry.m_userData = &m_cullable;
  2634. m_cullable.m_cullData.m_entityId = m_descriptor.m_entityId;
  2635. if (!r_meshInstancingEnabled)
  2636. {
  2637. m_cullable.m_cullData.m_visibilityEntry.m_typeFlags = AzFramework::VisibilityEntry::TYPE_RPI_Cullable;
  2638. }
  2639. else
  2640. {
  2641. m_cullable.m_cullData.m_visibilityEntry.m_typeFlags = AzFramework::VisibilityEntry::TYPE_RPI_VisibleObjectList;
  2642. }
  2643. m_scene->GetCullingScene()->RegisterOrUpdateCullable(m_cullable);
  2644. m_flags.m_cullBoundsNeedsUpdate = false;
  2645. }
  2646. void ModelDataInstance::UpdateObjectSrg(MeshFeatureProcessor* meshFeatureProcessor)
  2647. {
  2648. ReflectionProbeFeatureProcessor* reflectionProbeFeatureProcessor = meshFeatureProcessor->GetReflectionProbeFeatureProcessor();
  2649. TransformServiceFeatureProcessor* transformServiceFeatureProcessor = meshFeatureProcessor->GetTransformServiceFeatureProcessor();
  2650. for (auto& objectSrg : m_objectSrgList)
  2651. {
  2652. if (reflectionProbeFeatureProcessor && (m_descriptor.m_useForwardPassIblSpecular || m_flags.m_hasForwardPassIblSpecularMaterial))
  2653. {
  2654. // retrieve probe constant indices
  2655. AZ::RHI::ShaderInputConstantIndex modelToWorldConstantIndex = objectSrg->FindShaderInputConstantIndex(Name("m_reflectionProbeData.m_modelToWorld"));
  2656. AZ_Error("ModelDataInstance", modelToWorldConstantIndex.IsValid(), "Failed to find ReflectionProbe constant index");
  2657. AZ::RHI::ShaderInputConstantIndex modelToWorldInverseConstantIndex = objectSrg->FindShaderInputConstantIndex(Name("m_reflectionProbeData.m_modelToWorldInverse"));
  2658. AZ_Error("ModelDataInstance", modelToWorldInverseConstantIndex.IsValid(), "Failed to find ReflectionProbe constant index");
  2659. AZ::RHI::ShaderInputConstantIndex outerObbHalfLengthsConstantIndex = objectSrg->FindShaderInputConstantIndex(Name("m_reflectionProbeData.m_outerObbHalfLengths"));
  2660. AZ_Error("ModelDataInstance", outerObbHalfLengthsConstantIndex.IsValid(), "Failed to find ReflectionProbe constant index");
  2661. AZ::RHI::ShaderInputConstantIndex innerObbHalfLengthsConstantIndex = objectSrg->FindShaderInputConstantIndex(Name("m_reflectionProbeData.m_innerObbHalfLengths"));
  2662. AZ_Error("ModelDataInstance", innerObbHalfLengthsConstantIndex.IsValid(), "Failed to find ReflectionProbe constant index");
  2663. AZ::RHI::ShaderInputConstantIndex useReflectionProbeConstantIndex = objectSrg->FindShaderInputConstantIndex(Name("m_reflectionProbeData.m_useReflectionProbe"));
  2664. AZ_Error("ModelDataInstance", useReflectionProbeConstantIndex.IsValid(), "Failed to find ReflectionProbe constant index");
  2665. AZ::RHI::ShaderInputConstantIndex useParallaxCorrectionConstantIndex = objectSrg->FindShaderInputConstantIndex(Name("m_reflectionProbeData.m_useParallaxCorrection"));
  2666. AZ_Error("ModelDataInstance", useParallaxCorrectionConstantIndex.IsValid(), "Failed to find ReflectionProbe constant index");
  2667. AZ::RHI::ShaderInputConstantIndex exposureConstantIndex = objectSrg->FindShaderInputConstantIndex(Name("m_reflectionProbeData.m_exposure"));
  2668. AZ_Error("ModelDataInstance", exposureConstantIndex.IsValid(), "Failed to find ReflectionProbe constant index");
  2669. // retrieve probe cubemap index
  2670. Name reflectionCubeMapImageName = Name("m_reflectionProbeCubeMap");
  2671. RHI::ShaderInputImageIndex reflectionCubeMapImageIndex = objectSrg->FindShaderInputImageIndex(reflectionCubeMapImageName);
  2672. AZ_Error("ModelDataInstance", reflectionCubeMapImageIndex.IsValid(), "Failed to find shader image index [%s]", reflectionCubeMapImageName.GetCStr());
  2673. // retrieve the list of probes that overlap the mesh bounds
  2674. Transform transform = transformServiceFeatureProcessor->GetTransformForId(m_objectId);
  2675. Aabb aabbWS = m_aabb;
  2676. aabbWS.ApplyTransform(transform);
  2677. ReflectionProbeHandleVector reflectionProbeHandles;
  2678. reflectionProbeFeatureProcessor->FindReflectionProbes(aabbWS, reflectionProbeHandles);
  2679. if (!reflectionProbeHandles.empty())
  2680. {
  2681. // take the last handle from the list, which will be the smallest (most influential) probe
  2682. ReflectionProbeHandle handle = reflectionProbeHandles.back();
  2683. objectSrg->SetConstant(modelToWorldConstantIndex, Matrix3x4::CreateFromTransform(reflectionProbeFeatureProcessor->GetTransform(handle)));
  2684. objectSrg->SetConstant(modelToWorldInverseConstantIndex, Matrix3x4::CreateFromTransform(reflectionProbeFeatureProcessor->GetTransform(handle)).GetInverseFull());
  2685. objectSrg->SetConstant(outerObbHalfLengthsConstantIndex, reflectionProbeFeatureProcessor->GetOuterObbWs(handle).GetHalfLengths());
  2686. objectSrg->SetConstant(innerObbHalfLengthsConstantIndex, reflectionProbeFeatureProcessor->GetInnerObbWs(handle).GetHalfLengths());
  2687. objectSrg->SetConstant(useReflectionProbeConstantIndex, true);
  2688. objectSrg->SetConstant(useParallaxCorrectionConstantIndex, reflectionProbeFeatureProcessor->GetUseParallaxCorrection(handle));
  2689. objectSrg->SetConstant(exposureConstantIndex, reflectionProbeFeatureProcessor->GetRenderExposure(handle));
  2690. objectSrg->SetImage(reflectionCubeMapImageIndex, reflectionProbeFeatureProcessor->GetCubeMap(handle));
  2691. }
  2692. else
  2693. {
  2694. objectSrg->SetConstant(useReflectionProbeConstantIndex, false);
  2695. }
  2696. }
  2697. RHI::ShaderInputConstantIndex lightingChannelMaskIndex = objectSrg->FindShaderInputConstantIndex(AZ::Name("m_lightingChannelMask"));
  2698. if (lightingChannelMaskIndex.IsValid())
  2699. {
  2700. objectSrg->SetConstant(lightingChannelMaskIndex, m_lightingChannelMask);
  2701. }
  2702. objectSrg->Compile();
  2703. }
  2704. // Set m_objectSrgNeedsUpdate to false if there are object SRGs in the list
  2705. m_flags.m_objectSrgNeedsUpdate = m_flags.m_objectSrgNeedsUpdate && (m_objectSrgList.size() == 0);
  2706. }
  2707. bool ModelDataInstance::MaterialRequiresForwardPassIblSpecular(Data::Instance<RPI::Material> material) const
  2708. {
  2709. bool requiresForwardPassIbl = false;
  2710. // look for a shader that has the o_materialUseForwardPassIBLSpecular option set
  2711. // Note: this should be changed to have the material automatically set the forwardPassIBLSpecular
  2712. // property and look for that instead of the shader option.
  2713. // [GFX TODO][ATOM-5040] Address Property Metadata Feedback Loop
  2714. material->ForAllShaderItems(
  2715. [&](const Name&, const RPI::ShaderCollection::Item& shaderItem)
  2716. {
  2717. if (shaderItem.IsEnabled())
  2718. {
  2719. RPI::ShaderOptionIndex index = shaderItem.GetShaderOptionGroup().GetShaderOptionLayout()->FindShaderOptionIndex(Name{"o_materialUseForwardPassIBLSpecular"});
  2720. if (index.IsValid())
  2721. {
  2722. RPI::ShaderOptionValue value = shaderItem.GetShaderOptionGroup().GetValue(Name{"o_materialUseForwardPassIBLSpecular"});
  2723. if (value.GetIndex() == 1)
  2724. {
  2725. requiresForwardPassIbl = true;
  2726. return false; // break
  2727. }
  2728. }
  2729. }
  2730. return true; // continue
  2731. });
  2732. return requiresForwardPassIbl;
  2733. }
  2734. void ModelDataInstance::SetVisible(bool isVisible)
  2735. {
  2736. m_flags.m_visible = isVisible;
  2737. m_cullable.m_isHidden = !isVisible;
  2738. }
  2739. CustomMaterialInfo ModelDataInstance::GetCustomMaterialWithFallback(const CustomMaterialId& id) const
  2740. {
  2741. const CustomMaterialId ignoreLodId(DefaultCustomMaterialLodIndex, id.second);
  2742. for (const auto& currentId : { id, ignoreLodId, DefaultCustomMaterialId })
  2743. {
  2744. if (auto itr = m_descriptor.m_customMaterials.find(currentId); itr != m_descriptor.m_customMaterials.end() && itr->second.m_material)
  2745. {
  2746. return itr->second;
  2747. }
  2748. }
  2749. return CustomMaterialInfo{};
  2750. }
  2751. void ModelDataInstance::HandleDrawPacketUpdate(uint32_t lodIndex, uint32_t meshIndex, RPI::MeshDrawPacket& meshDrawPacket)
  2752. {
  2753. // When the drawpacket is updated, the cullable must be rebuilt to use the latest draw packet
  2754. m_flags.m_cullableNeedsRebuild = true;
  2755. m_meshDrawPacketUpdatedEvent.Signal(*this, lodIndex, meshIndex, meshDrawPacket);
  2756. }
  2757. void ModelDataInstance::ConnectMeshDrawPacketUpdatedHandler(MeshDrawPacketUpdatedEvent::Handler& handler)
  2758. {
  2759. if (handler.IsConnected())
  2760. {
  2761. handler.Disconnect();
  2762. }
  2763. handler.Connect(m_meshDrawPacketUpdatedEvent);
  2764. }
  2765. } // namespace Render
  2766. } // namespace AZ