MeshFeatureProcessor.cpp 160 KB

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