SampleComponentManager.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  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 <SampleComponentManager.h>
  9. #include <SampleComponentConfig.h>
  10. #include <Atom/Component/DebugCamera/CameraComponent.h>
  11. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  12. #include <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  13. #include <Atom/Feature/AuxGeom/AuxGeomFeatureProcessor.h>
  14. #include <Atom/Feature/ImGui/ImGuiUtils.h>
  15. #include <Atom/Feature/ImGui/SystemBus.h>
  16. #include <Atom/Feature/Mesh/MeshFeatureProcessor.h>
  17. #include <Atom/Feature/PostProcessing/PostProcessingConstants.h>
  18. #include <Atom/Feature/SkinnedMesh/SkinnedMeshInputBuffers.h>
  19. #include <Atom/RPI.Public/Pass/Pass.h>
  20. #include <Atom/RPI.Public/Pass/ParentPass.h>
  21. #include <Atom/RPI.Public/Pass/PassSystemInterface.h>
  22. #include <Atom/RPI.Public/Pass/RenderPass.h>
  23. #include <Atom/RPI.Public/Pass/Specific/SwapChainPass.h>
  24. #include <Atom/RPI.Public/RenderPipeline.h>
  25. #include <Atom/RPI.Public/RPISystemInterface.h>
  26. #include <Atom/RPI.Public/Scene.h>
  27. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  28. #include <Atom/RPI.Reflect/Image/AttachmentImageAsset.h>
  29. #include <Atom/RPI.Reflect/Shader/IShaderVariantFinder.h>
  30. #include <Atom/RHI/Factory.h>
  31. #include <Atom/RHI/RHISystemInterface.h>
  32. #include <Atom/RHI.Reflect/AliasedHeapEnums.h>
  33. #include <Automation/ScriptManager.h>
  34. #include <RHI/AlphaToCoverageExampleComponent.h>
  35. #include <RHI/AsyncComputeExampleComponent.h>
  36. #include <RHI/BasicRHIComponent.h>
  37. #include <RHI/ComputeExampleComponent.h>
  38. #include <RHI/CopyQueueComponent.h>
  39. #include <RHI/DualSourceBlendingComponent.h>
  40. #include <RHI/IndirectRenderingExampleComponent.h>
  41. #include <RHI/InputAssemblyExampleComponent.h>
  42. #include <RHI/SubpassExampleComponent.h>
  43. #include <RHI/MRTExampleComponent.h>
  44. #include <RHI/MSAAExampleComponent.h>
  45. #include <RHI/MultiThreadComponent.h>
  46. #include <RHI/MultiViewportSwapchainComponent.h>
  47. #include <RHI/MultipleViewsComponent.h>
  48. #include <RHI/QueryExampleComponent.h>
  49. #include <RHI/StencilExampleComponent.h>
  50. #include <RHI/SwapchainExampleComponent.h>
  51. #include <RHI/SphericalHarmonicsExampleComponent.h>
  52. #include <RHI/Texture3dExampleComponent.h>
  53. #include <RHI/TextureArrayExampleComponent.h>
  54. #include <RHI/TextureExampleComponent.h>
  55. #include <RHI/TextureMapExampleComponent.h>
  56. #include <RHI/TriangleExampleComponent.h>
  57. #include <RHI/XRExampleComponent.h>
  58. #include <RHI/TrianglesConstantBufferExampleComponent.h>
  59. #include <RHI/BindlessPrototypeExampleComponent.h>
  60. #include <RHI/RayTracingExampleComponent.h>
  61. #include <RHI/MatrixAlignmentTestExampleComponent.h>
  62. #include <Performance/100KDrawable_SingleView_ExampleComponent.h>
  63. #include <Performance/100KDraw_10KDrawable_MultiView_ExampleComponent.h>
  64. #include <AreaLightExampleComponent.h>
  65. #include <AssetLoadTestComponent.h>
  66. #include <AuxGeomExampleComponent.h>
  67. #include <BakedShaderVariantExampleComponent.h>
  68. #include <SponzaBenchmarkComponent.h>
  69. #include <BloomExampleComponent.h>
  70. #include <CheckerboardExampleComponent.h>
  71. #include <CullingAndLodExampleComponent.h>
  72. #include <DecalExampleComponent.h>
  73. #include <DepthOfFieldExampleComponent.h>
  74. #include <DynamicDrawExampleComponent.h>
  75. #include <DynamicMaterialTestComponent.h>
  76. #include <ExposureExampleComponent.h>
  77. #include <EyeMaterialExampleComponent.h>
  78. #include <SceneReloadSoakTestComponent.h>
  79. #include <LightCullingExampleComponent.h>
  80. #include <MeshExampleComponent.h>
  81. #include <MSAA_RPI_ExampleComponent.h>
  82. #include <MultiRenderPipelineExampleComponent.h>
  83. #include <MultiSceneExampleComponent.h>
  84. #include <ParallaxMappingExampleComponent.h>
  85. #include <RenderTargetTextureExampleComponent.h>
  86. #include <SceneReloadSoakTestComponent.h>
  87. #include <ShadowExampleComponent.h>
  88. #include <ShadowedSponzaExampleComponent.h>
  89. #include <SkinnedMeshExampleComponent.h>
  90. #include <SsaoExampleComponent.h>
  91. #include <StreamingImageExampleComponent.h>
  92. #include <RootConstantsExampleComponent.h>
  93. #include <MultiViewSingleSceneAuxGeomExampleComponent.h>
  94. #include <TonemappingExampleComponent.h>
  95. #include <TransparencyExampleComponent.h>
  96. #include <DiffuseGIExampleComponent.h>
  97. #include <SSRExampleComponent.h>
  98. #include <XRRPIExampleComponent.h>
  99. #include <ShaderReloadTestComponent.h>
  100. #include <ReadbackExampleComponent.h>
  101. #include <Atom/Bootstrap/DefaultWindowBus.h>
  102. #include <AzCore/Component/Entity.h>
  103. #include <AzCore/Debug/Profiler.h>
  104. #include <AzCore/Debug/ProfilerBus.h>
  105. #include <AzCore/IO/IStreamerProfiler.h>
  106. #include <AzCore/Serialization/SerializeContext.h>
  107. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  108. #include <AzCore/std/smart_ptr/make_shared.h>
  109. #include <AzCore/std/algorithm.h>
  110. #include <AzFramework/API/ApplicationAPI.h>
  111. #include <AzFramework/Components/ConsoleBus.h>
  112. #include <AzFramework/Components/TransformComponent.h>
  113. #include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
  114. #include <AzFramework/Entity/GameEntityContextBus.h>
  115. #include <AzFramework/Scene/Scene.h>
  116. #include <AzFramework/Scene/SceneSystemInterface.h>
  117. #include <Passes/RayTracingAmbientOcclusionPass.h>
  118. #include <Utils/Utils.h>
  119. #include <Profiler/ProfilerImGuiBus.h>
  120. #include "ExampleComponentBus.h"
  121. #include <EntityUtilityFunctions.h>
  122. namespace Platform
  123. {
  124. const char* GetPipelineName();
  125. }
  126. namespace AtomSampleViewer
  127. {
  128. namespace
  129. {
  130. constexpr const char* PassTreeToolName = "PassTree";
  131. constexpr const char* CpuProfilerToolName = "CPU Profiler";
  132. constexpr const char* GpuProfilerToolName = "GPU Profiler";
  133. constexpr const char* FileIoProfilerToolName = "File IO Profiler";
  134. constexpr const char* TransientAttachmentProfilerToolName = "Transient Attachment Profiler";
  135. constexpr const char* SampleSetting = "/O3DE/AtomSampleViewer/Sample";
  136. }
  137. bool IsValidNumMSAASamples(int numSamples)
  138. {
  139. return (numSamples == 1) || (numSamples == 2) || (numSamples == 4) || (numSamples == 8);
  140. }
  141. template <typename T>
  142. static SampleEntry NewSample(SamplePipelineType type, const char* menuName, const AZStd::string& name)
  143. {
  144. SampleEntry entry;
  145. entry.m_sampleName = name;
  146. entry.m_sampleUuid = azrtti_typeid<T>();
  147. entry.m_pipelineType = type;
  148. entry.m_componentDescriptor = T::CreateDescriptor();
  149. entry.m_parentMenuName = menuName;
  150. entry.m_fullName = entry.m_parentMenuName + '/' + entry.m_sampleName;
  151. entry.m_contentWarning = T::ContentWarning;
  152. entry.m_contentWarningTitle = T::ContentWarningTitle;
  153. return entry;
  154. }
  155. template <typename T>
  156. static SampleEntry NewSample(SamplePipelineType type, const char* menuName, const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  157. {
  158. SampleEntry entry = NewSample<T>(type, menuName, name);
  159. entry.m_isSupportedFunc = isSupportedFunction;
  160. return entry;
  161. }
  162. template <typename T>
  163. static SampleEntry NewRHISample(const AZStd::string& name)
  164. {
  165. return NewSample<T>(SamplePipelineType::RHI, "RHI", name);
  166. }
  167. template <typename T>
  168. static SampleEntry NewRHISample(const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  169. {
  170. SampleEntry entry = NewSample<T>(SamplePipelineType::RHI, "RHI", name, isSupportedFunction);
  171. entry.m_isSupportedFunc = isSupportedFunction;
  172. return entry;
  173. }
  174. template <typename T>
  175. static SampleEntry NewRPISample(const AZStd::string& name)
  176. {
  177. return NewSample<T>(SamplePipelineType::RPI, "RPI", name);
  178. }
  179. template <typename T>
  180. static SampleEntry NewRPISample(const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  181. {
  182. return NewSample<T>(SamplePipelineType::RPI, "RPI", name, isSupportedFunction);
  183. }
  184. template <typename T>
  185. static SampleEntry NewFeaturesSample(const AZStd::string& name)
  186. {
  187. return NewSample<T>(SamplePipelineType::RPI, "Features", name);
  188. }
  189. template <typename T>
  190. static SampleEntry NewFeaturesSample(const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  191. {
  192. return NewSample<T>(SamplePipelineType::RPI, "Features", name, isSupportedFunction);
  193. }
  194. template <typename T>
  195. static SampleEntry NewPerfSample(const AZStd::string& name)
  196. {
  197. return NewSample<T>(SamplePipelineType::RPI, "Performance", name);
  198. }
  199. template <typename T>
  200. static SampleEntry NewPerfSample(const AZStd::string& name, AZStd::function<bool()> isSupportedFunction)
  201. {
  202. return NewSample<T>(SamplePipelineType::RPI, "Performance", name, isSupportedFunction);
  203. }
  204. static AZStd::string GetTargetSampleName()
  205. {
  206. //Check command line option
  207. const AzFramework::CommandLine* commandLine = nullptr;
  208. AzFramework::ApplicationRequests::Bus::BroadcastResult(commandLine, &AzFramework::ApplicationRequests::GetCommandLine);
  209. if (commandLine->HasSwitch("sample"))
  210. {
  211. AZStd::string targetSampleName = commandLine->GetSwitchValue("sample", 0);
  212. return targetSampleName;
  213. }
  214. //Check settings registry
  215. if (AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get())
  216. {
  217. if (AZStd::string targetSampleName;
  218. settingsRegistry->Get(targetSampleName, SampleSetting))
  219. {
  220. return targetSampleName;
  221. }
  222. }
  223. return {};
  224. }
  225. void SampleComponentManager::Reflect(AZ::ReflectContext* context)
  226. {
  227. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  228. {
  229. serializeContext->Class<SampleComponentManager, AZ::Component>()
  230. ->Version(0)
  231. ;
  232. // This registration matches ShaderOptionValuesSourceData, which is needed by ImGuiShaderUtils, to support
  233. // generating JSON for shader variants.
  234. serializeContext->RegisterGenericType<AZStd::unordered_map<Name, Name>>();
  235. }
  236. }
  237. void SampleComponentManager::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
  238. {
  239. required.push_back(AZ_CRC("PrototypeLmbrCentralService", 0xe35e6de0));
  240. }
  241. void SampleComponentManager::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
  242. {
  243. dependent.push_back(AZ_CRC("AzFrameworkConfigurationSystemComponentService", 0xcc49c96e)); // Ensures a scene is created for the GameEntityContext
  244. }
  245. AZStd::vector<SampleEntry> SampleComponentManager::GetSamples()
  246. {
  247. return {
  248. NewRHISample<AlphaToCoverageExampleComponent>("AlphaToCoverage"),
  249. NewRHISample<AsyncComputeExampleComponent>("AsyncCompute"),
  250. NewRHISample<BindlessPrototypeExampleComponent>("BindlessPrototype", []() {return Utils::GetRHIDevice()->GetFeatures().m_unboundedArrays; }),
  251. NewRHISample<ComputeExampleComponent>("Compute"),
  252. NewRHISample<CopyQueueComponent>("CopyQueue"),
  253. NewRHISample<DualSourceBlendingComponent>("DualSourceBlending", []() {return Utils::GetRHIDevice()->GetFeatures().m_dualSourceBlending; }),
  254. NewRHISample<IndirectRenderingExampleComponent>("IndirectRendering", []() {return Utils::GetRHIDevice()->GetFeatures().m_indirectCommandTier > RHI::IndirectCommandTiers::Tier0; }),
  255. NewRHISample<InputAssemblyExampleComponent>("InputAssembly"),
  256. NewRHISample<MSAAExampleComponent>("MSAA"),
  257. NewRHISample<MultipleViewsComponent>("MultipleViews"),
  258. NewRHISample<MRTExampleComponent>("MultiRenderTarget"),
  259. NewRHISample<MultiThreadComponent>("MultiThread"),
  260. NewRHISample<MultiViewportSwapchainComponent>("MultiViewportSwapchainComponent", [] { return IsMultiViewportSwapchainSampleSupported(); }),
  261. NewRHISample<QueryExampleComponent>("Queries"),
  262. NewRHISample<RayTracingExampleComponent>("RayTracing", []() {return Utils::GetRHIDevice()->GetFeatures().m_rayTracing; }),
  263. NewRHISample<SphericalHarmonicsExampleComponent>("SphericalHarmonics"),
  264. NewRHISample<StencilExampleComponent>("Stencil"),
  265. NewRHISample<SubpassExampleComponent>("Subpass", []() {return Utils::GetRHIDevice()->GetFeatures().m_renderTargetSubpassInputSupport != AZ::RHI::SubpassInputSupportType::NotSupported; }),
  266. NewRHISample<SwapchainExampleComponent>("Swapchain"),
  267. NewRHISample<TextureExampleComponent>("Texture"),
  268. NewRHISample<Texture3dExampleComponent>("Texture3d"),
  269. NewRHISample<TextureArrayExampleComponent>("TextureArray"),
  270. NewRHISample<TextureMapExampleComponent>("TextureMap"),
  271. NewRHISample<TriangleExampleComponent>("Triangle"),
  272. NewRHISample<TrianglesConstantBufferExampleComponent>("TrianglesConstantBuffer"),
  273. NewRHISample<XRExampleComponent>("OpenXr"),
  274. NewRHISample<MatrixAlignmentTestExampleComponent>("MatrixAlignmentTest"),
  275. NewRPISample<AssetLoadTestComponent>("AssetLoadTest"),
  276. NewRPISample<AuxGeomExampleComponent>("AuxGeom"),
  277. NewRPISample<BakedShaderVariantExampleComponent>("BakedShaderVariant"),
  278. NewRPISample<SponzaBenchmarkComponent>("SponzaBenchmark"),
  279. NewRPISample<CullingAndLodExampleComponent>("CullingAndLod"),
  280. NewRPISample<DecalExampleComponent>("Decals"),
  281. NewRPISample<DynamicDrawExampleComponent>("DynamicDraw"),
  282. NewRPISample<DynamicMaterialTestComponent>("DynamicMaterialTest"),
  283. NewRPISample<MeshExampleComponent>("Mesh"),
  284. NewRPISample<MSAA_RPI_ExampleComponent>("MSAA"),
  285. NewRPISample<MultiRenderPipelineExampleComponent>("MultiRenderPipeline"),
  286. NewRPISample<MultiSceneExampleComponent>("MultiScene"),
  287. NewRPISample<MultiViewSingleSceneAuxGeomExampleComponent>("MultiViewSingleSceneAuxGeom"),
  288. NewRPISample<ReadbackExampleComponent>("Readback"),
  289. NewRPISample<RenderTargetTextureExampleComponent>("RenderTargetTexture"),
  290. NewRPISample<RootConstantsExampleComponent>("RootConstants"),
  291. NewRPISample<SceneReloadSoakTestComponent>("SceneReloadSoakTest"),
  292. NewRPISample<StreamingImageExampleComponent>("StreamingImage"),
  293. NewRPISample<ShaderReloadTestComponent>("ShaderReloadTest"),
  294. NewFeaturesSample<AreaLightExampleComponent>("AreaLight"),
  295. NewFeaturesSample<BloomExampleComponent>("Bloom"),
  296. NewFeaturesSample<CheckerboardExampleComponent>("Checkerboard", []() {return (Utils::GetRHIDevice()->GetPhysicalDevice().GetDescriptor().m_vendorId != RHI::VendorId::ARM && Utils::GetRHIDevice()->GetPhysicalDevice().GetDescriptor().m_vendorId != RHI::VendorId::Qualcomm); }),
  297. NewFeaturesSample<DepthOfFieldExampleComponent>("DepthOfField"),
  298. NewFeaturesSample<DiffuseGIExampleComponent>("DiffuseGI", []() {return Utils::GetRHIDevice()->GetFeatures().m_rayTracing; }),
  299. NewFeaturesSample<ExposureExampleComponent>("Exposure"),
  300. NewFeaturesSample<EyeMaterialExampleComponent>("EyeMaterial"),
  301. NewFeaturesSample<LightCullingExampleComponent>("LightCulling"),
  302. NewFeaturesSample<ParallaxMappingExampleComponent>("Parallax"),
  303. NewFeaturesSample<ShadowExampleComponent>("Shadow"),
  304. NewFeaturesSample<ShadowedSponzaExampleComponent>("ShadowedSponza"),
  305. NewFeaturesSample<SkinnedMeshExampleComponent>("SkinnedMesh"),
  306. NewFeaturesSample<SsaoExampleComponent>("SSAO"),
  307. NewFeaturesSample<SSRExampleComponent>("SSR"),
  308. NewFeaturesSample<XRRPIExampleComponent>("OpenXR"),
  309. NewFeaturesSample<TonemappingExampleComponent>("Tonemapping"),
  310. NewFeaturesSample<TransparencyExampleComponent>("Transparency"),
  311. NewPerfSample<_100KDrawableExampleComponent>("100KDrawable_SingleView"),
  312. NewPerfSample<_100KDraw10KDrawableExampleComponent>("100KDraw_10KDrawable_MultiView"),
  313. };
  314. }
  315. void SampleComponentManager::RegisterSampleComponent(const SampleEntry& sample)
  316. {
  317. if (AZStd::find(m_availableSamples.begin(), m_availableSamples.end(), sample) == m_availableSamples.end())
  318. {
  319. m_availableSamples.push_back(sample);
  320. m_groupedSamples[sample.m_parentMenuName].push_back(static_cast<int32_t>(m_availableSamples.size() - 1));
  321. }
  322. }
  323. SampleComponentManager::SampleComponentManager()
  324. : m_imguiFrameCaptureSaver("@user@/frame_capture.xml")
  325. {
  326. m_imGuiFrameTimer = AZStd::make_unique<ImGuiHistogramQueue>(FrameTimeDefaultLogSize, FrameTimeDefaultLogSize, 250.0f);
  327. m_exampleEntity = aznew AZ::Entity();
  328. m_entityContextId = AzFramework::EntityContextId::CreateNull();
  329. }
  330. SampleComponentManager::~SampleComponentManager()
  331. {
  332. m_exampleEntity = nullptr;
  333. m_cameraEntity = nullptr;
  334. m_windowContext = nullptr;
  335. m_availableSamples.clear();
  336. }
  337. void SampleComponentManager::Init()
  338. {
  339. AZStd::vector<SampleEntry> samples = GetSamples();
  340. for (const SampleEntry& sample : samples)
  341. {
  342. RegisterSampleComponent(sample);
  343. }
  344. m_scriptManager = AZStd::make_unique<ScriptManager>();
  345. }
  346. void SampleComponentManager::Activate()
  347. {
  348. // We can only initialize this component after the asset catalog has been loaded.
  349. AzFramework::AssetCatalogEventBus::Handler::BusConnect();
  350. AZ::Render::ImGuiSystemNotificationBus::Handler::BusConnect();
  351. auto* passSystem = AZ::RPI::PassSystemInterface::Get();
  352. AZ_Assert(passSystem, "Cannot get the pass system.");
  353. passSystem->AddPassCreator(Name("RayTracingAmbientOcclusionPass"), &AZ::Render::RayTracingAmbientOcclusionPass::Create);
  354. m_numMSAASamples = GetDefaultNumMSAASamples();
  355. }
  356. void SampleComponentManager::ActivateInternal()
  357. {
  358. using namespace AZ;
  359. AZ::ApplicationTypeQuery appType;
  360. ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  361. if (!appType.IsValid() || !appType.IsGame())
  362. {
  363. return;
  364. }
  365. // ActivateInternal() may get called twice because the OnCatalogLoaded was called twice When run AtomSampleViewer launcher. One of those two events is from ly launcher framework and the other one is from
  366. // LoadCatalog call in AtomSampleViewer system component. Although load the same asset catalog twice doesn't seem to cause other issue.
  367. if (m_wasActivated)
  368. {
  369. return;
  370. }
  371. Render::Bootstrap::DefaultWindowBus::BroadcastResult(m_windowContext, &Render::Bootstrap::DefaultWindowBus::Events::GetDefaultWindowContext);
  372. AzFramework::GameEntityContextRequestBus::BroadcastResult(m_entityContextId, &AzFramework::GameEntityContextRequestBus::Events::GetGameEntityContextId);
  373. CreateDefaultCamera();
  374. // Add customized pass classes
  375. auto* passSystem = RPI::PassSystemInterface::Get();
  376. passSystem->AddPassCreator(Name("RHISamplePass"), &AtomSampleViewer::RHISamplePass::Create);
  377. // Use scene and render pipeline for RHI samples as default scene and render pipeline
  378. CreateSceneForRHISample();
  379. m_exampleEntity->Init();
  380. m_exampleEntity->Activate();
  381. m_isSampleSupported.resize(m_availableSamples.size());
  382. for (size_t i = 0; i < m_availableSamples.size(); ++i)
  383. {
  384. // Assume that the sample is supported if no m_isSupportedFunc is provided.
  385. m_isSampleSupported[i] = m_availableSamples[i].m_isSupportedFunc ? m_availableSamples[i].m_isSupportedFunc() : true;
  386. }
  387. AZ_Printf("SampleComponentManager", "Available Samples -------------------------\n");
  388. for (size_t i = 0; i < m_availableSamples.size(); ++i)
  389. {
  390. AZStd::string printStr = "\t[" + m_availableSamples[i].m_fullName + "]";
  391. if (!m_isSampleSupported[i])
  392. {
  393. printStr += " Not Supported ";
  394. }
  395. if (i < 9)
  396. {
  397. printStr += AZStd::string::format("\tctrl+%lu", i + 1);
  398. }
  399. printStr += "\n";
  400. AZ_Printf("SampleComponentManager", printStr.data());
  401. }
  402. AZ_Printf("SampleComponentManager", "-------------------------------------------\n");
  403. AzFramework::InputChannelEventListener::BusConnect();
  404. TickBus::Handler::BusConnect();
  405. bool targetSampleFound = false;
  406. if (AZStd::string targetSampleName = GetTargetSampleName();
  407. !targetSampleName.empty())
  408. {
  409. AZStd::to_lower(targetSampleName.begin(), targetSampleName.end());
  410. for (int32_t i = 0; i < m_availableSamples.size(); ++i)
  411. {
  412. AZStd::string sampleName = m_availableSamples[i].m_fullName;
  413. AZStd::to_lower(sampleName.begin(), sampleName.end());
  414. if (sampleName == targetSampleName)
  415. {
  416. if (m_isSampleSupported[i])
  417. {
  418. if (m_availableSamples[i].m_contentWarning.empty())
  419. {
  420. m_selectedSampleIndex = i;
  421. m_sampleChangeRequest = true;
  422. }
  423. else
  424. {
  425. m_contentWarningDialog.OpenPopupConfirmation(
  426. m_availableSamples[i].m_contentWarningTitle,
  427. m_availableSamples[i].m_contentWarning,
  428. [this, i]() {
  429. m_selectedSampleIndex = i;
  430. m_sampleChangeRequest = true;
  431. });
  432. }
  433. targetSampleFound = true;
  434. }
  435. break;
  436. }
  437. }
  438. AZ_Warning("SampleComponentManager", targetSampleFound, "Failed find target sample %s", targetSampleName.c_str());
  439. }
  440. const AzFramework::CommandLine* commandLine = nullptr;
  441. AzFramework::ApplicationRequests::Bus::BroadcastResult(commandLine, &AzFramework::ApplicationRequests::GetCommandLine);
  442. if (commandLine->HasSwitch("timingSamples"))
  443. {
  444. AZStd::string timingSamplesStr = commandLine->GetSwitchValue("timingSamples", 0);
  445. int timingSamplesCount = 0;
  446. if (AZ::StringFunc::LooksLikeInt(timingSamplesStr.c_str(), &timingSamplesCount))
  447. {
  448. timingSamplesCount = AZStd::clamp<int>(timingSamplesCount, FrameTimeMinLogSize, FrameTimeMaxLogSize);
  449. m_imGuiFrameTimer = AZStd::make_unique<ImGuiHistogramQueue>(timingSamplesCount, timingSamplesCount, 250.0f);
  450. }
  451. }
  452. // Set default screenshot folder to relative path 'Screenshots'
  453. AZ::IO::Path screenshotFolder = "Screenshots";
  454. // Get folder from command line if it exists
  455. static const char* screenshotFolderFlagName = "screenshotFolder";
  456. if (commandLine->HasSwitch(screenshotFolderFlagName))
  457. {
  458. screenshotFolder = commandLine->GetSwitchValue(screenshotFolderFlagName, 0);
  459. }
  460. // Make the screenshot directory relative to the Writeable Storage Path
  461. // The Path::operator/ smartly knows how to concatenate two absolute paths
  462. // i.e <absolute path1> / <absolute path2> = <absolute path2>
  463. auto settingsRegistry = AZ::SettingsRegistry::Get();
  464. AZ::IO::Path writableStoragePath;
  465. settingsRegistry->Get(writableStoragePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_DevWriteStorage);
  466. screenshotFolder = writableStoragePath / screenshotFolder;
  467. m_imguiFrameCaptureSaver.SetDefaultFolder(screenshotFolder.Native());
  468. m_imguiFrameCaptureSaver.SetDefaultFileName("screenshot");
  469. m_imguiFrameCaptureSaver.SetAvailableExtensions({ "png", "ppm", "dds" });
  470. m_imguiFrameCaptureSaver.Activate();
  471. SampleComponentManagerRequestBus::Handler::BusConnect();
  472. m_scriptManager->Activate();
  473. m_wasActivated = true;
  474. SampleComponentManagerNotificationBus::Broadcast(&SampleComponentManagerNotificationBus::Events::OnSampleManagerActivated);
  475. }
  476. void SampleComponentManager::Deactivate()
  477. {
  478. DestroyEntity(m_cameraEntity);
  479. AzFramework::AssetCatalogEventBus::Handler::BusDisconnect();
  480. AZ::Render::ImGuiSystemNotificationBus::Handler::BusDisconnect();
  481. m_scriptManager->Deactivate();
  482. m_imguiFrameCaptureSaver.Deactivate();
  483. SampleComponentManagerRequestBus::Handler::BusDisconnect();
  484. AZ::TickBus::Handler::BusDisconnect();
  485. AzFramework::InputChannelEventListener::Disconnect();
  486. Render::ImGuiSystemRequestBus::Broadcast(&Render::ImGuiSystemRequests::PopActiveContext);
  487. m_imguiPassTree.Reset();
  488. m_imguiFrameGraphVisualizer.Reset();
  489. m_windowContext = nullptr;
  490. m_brdfTexture.reset();
  491. ReleaseRHIScene();
  492. ReleaseRPIScene();
  493. }
  494. void SampleComponentManager::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  495. {
  496. AZ::RPI::RPISystemInterface* rpiSystem = AZ::RPI::RPISystemInterface::Get();
  497. if (rpiSystem->GetXRSystem())
  498. {
  499. //Only enable XR pipelines if the XR drivers indicate we have accurate pose information from the device
  500. if (rpiSystem->GetXRSystem()->ShouldRender())
  501. {
  502. EnableXrPipelines();
  503. }
  504. else
  505. {
  506. DisableXrPipelines();
  507. }
  508. }
  509. if (m_imGuiFrameTimer)
  510. {
  511. m_imGuiFrameTimer->PushValue(deltaTime * 1000.0f);
  512. }
  513. bool screenshotRequest = false;
  514. if (m_ctrlModifierLDown || m_ctrlModifierRDown)
  515. {
  516. if (m_alphanumericQDown)
  517. {
  518. RequestExit();
  519. return;
  520. }
  521. if (m_alphanumericTDown && m_canCaptureRADTM)
  522. {
  523. #ifdef AZ_PROFILE_TELEMETRY
  524. Utils::ToggleRadTMCapture();
  525. m_canCaptureRADTM = false;
  526. #endif
  527. }
  528. else if (!m_alphanumericTDown)
  529. {
  530. m_canCaptureRADTM = true;
  531. }
  532. if (m_alphanumericPDown)
  533. {
  534. screenshotRequest = true;
  535. }
  536. }
  537. // Request a frame capture only once per key press, even if the keys are held down for multiple ticks.
  538. if (screenshotRequest)
  539. {
  540. ++m_screenshotKeyDownCount;
  541. if (m_screenshotKeyDownCount == 1)
  542. {
  543. RequestFrameCapture(m_imguiFrameCaptureSaver.GetNextAutoSaveFilePath(), true);
  544. }
  545. }
  546. else
  547. {
  548. m_screenshotKeyDownCount = 0;
  549. }
  550. RenderImGui(deltaTime);
  551. // SampleChange needs to happen after RenderImGui as some of the samples create sidebars on a separate ImGui context
  552. // which can interfere with m_imguiContext in the first frame
  553. if (m_sampleChangeRequest && m_canSwitchSample)
  554. {
  555. SampleChange();
  556. m_canSwitchSample = false;
  557. }
  558. else if (m_escapeDown && m_canSwitchSample)
  559. {
  560. Reset();
  561. m_canSwitchSample = false;
  562. Utils::ReportScriptableAction("OpenSample('')");
  563. }
  564. // Once a SampleChange/Reset request has been handled, it will not be handled again until there has been at least one frame where the sample hasn't changed
  565. if (!m_sampleChangeRequest && !m_escapeDown)
  566. {
  567. m_canSwitchSample = true;
  568. }
  569. // Since the event has been handled, clear the request
  570. m_sampleChangeRequest = false;
  571. m_escapeDown = false;
  572. m_scriptManager->TickScript(deltaTime);
  573. if (m_isFrameCapturePending)
  574. {
  575. if (m_countdownForFrameCapture > 0)
  576. {
  577. m_countdownForFrameCapture--;
  578. }
  579. else if (m_countdownForFrameCapture == 0)
  580. {
  581. AZ::Render::FrameCaptureRequestBus::BroadcastResult(m_frameCaptureId, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshot, m_frameCaptureFilePath);
  582. if (m_frameCaptureId != AZ::Render::InvalidFrameCaptureId ) // if unsuccessfull leave state to attempt again next tick
  583. {
  584. AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(m_frameCaptureId);
  585. m_countdownForFrameCapture = -1; // Don't call CaptureScreenshot again
  586. }
  587. }
  588. }
  589. }
  590. bool SampleComponentManager::OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel)
  591. {
  592. const size_t samplesAvailableCount = m_availableSamples.size();
  593. AZStd::vector<AzFramework::InputChannelId> sampleInputMapping;
  594. sampleInputMapping.reserve(samplesAvailableCount);
  595. for (size_t i = 0; i < samplesAvailableCount; ++i)
  596. {
  597. switch (i)
  598. {
  599. case 0:
  600. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric1);
  601. break;
  602. case 1:
  603. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric2);
  604. break;
  605. case 2:
  606. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric3);
  607. break;
  608. case 3:
  609. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric4);
  610. break;
  611. case 4:
  612. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric5);
  613. break;
  614. case 5:
  615. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric6);
  616. break;
  617. case 6:
  618. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric7);
  619. break;
  620. case 7:
  621. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric8);
  622. break;
  623. case 8:
  624. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric9);
  625. break;
  626. case 9:
  627. sampleInputMapping.push_back(AzFramework::InputDeviceKeyboard::Key::Alphanumeric0);
  628. break;
  629. default:
  630. break;
  631. }
  632. }
  633. const AzFramework::InputChannelId& inputChannelId = inputChannel.GetInputChannelId();
  634. switch (inputChannel.GetState())
  635. {
  636. case AzFramework::InputChannel::State::Began:
  637. case AzFramework::InputChannel::State::Updated:
  638. {
  639. if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlL)
  640. {
  641. m_ctrlModifierLDown = true;
  642. }
  643. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlR)
  644. {
  645. m_ctrlModifierRDown = true;
  646. }
  647. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericQ)
  648. {
  649. m_alphanumericQDown = true;
  650. }
  651. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericT)
  652. {
  653. m_alphanumericTDown = true;
  654. }
  655. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericP)
  656. {
  657. m_alphanumericPDown = true;
  658. }
  659. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Escape)
  660. {
  661. m_escapeDown = true;
  662. }
  663. break;
  664. }
  665. case AzFramework::InputChannel::State::Ended:
  666. {
  667. if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlL)
  668. {
  669. m_ctrlModifierLDown = false;
  670. }
  671. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::ModifierCtrlR)
  672. {
  673. m_ctrlModifierRDown = false;
  674. }
  675. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericQ)
  676. {
  677. m_alphanumericQDown = false;
  678. }
  679. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericT)
  680. {
  681. m_alphanumericTDown = false;
  682. }
  683. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::AlphanumericP)
  684. {
  685. m_alphanumericPDown = false;
  686. }
  687. else if (inputChannelId == AzFramework::InputDeviceKeyboard::Key::Escape)
  688. {
  689. m_escapeDown = false;
  690. }
  691. break;
  692. }
  693. default:
  694. {
  695. break;
  696. }
  697. }
  698. return false;
  699. }
  700. void SampleComponentManager::RenderImGui(float deltaTime)
  701. {
  702. if (!m_isImGuiAvailable)
  703. {
  704. return;
  705. }
  706. ShowMenuBar();
  707. if (m_exitRequested)
  708. {
  709. return;
  710. }
  711. if (m_showResizeViewportDialog)
  712. {
  713. ShowResizeViewportDialog();
  714. }
  715. if (m_showFramerateHistogram)
  716. {
  717. ShowFramerateHistogram(deltaTime);
  718. }
  719. if (m_showFrameCaptureDialog)
  720. {
  721. ShowFrameCaptureDialog();
  722. }
  723. if (m_showImGuiMetrics)
  724. {
  725. ImGui::ShowMetricsWindow(&m_showImGuiMetrics);
  726. }
  727. if (m_showSampleHelper)
  728. {
  729. ShowSampleHelper();
  730. }
  731. if (m_showAbout)
  732. {
  733. ShowAboutWindow();
  734. }
  735. if (m_showPassTree)
  736. {
  737. ShowPassTreeWindow();
  738. }
  739. if (m_showFrameGraphVisualizer)
  740. {
  741. ShowFrameGraphVisualizerWindow();
  742. }
  743. if (m_showCullingDebugWindow)
  744. {
  745. AZ::RPI::Scene* rpiScene = AZ::RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("RPI"));
  746. if (rpiScene)
  747. {
  748. AZ::Render::ImGuiDrawCullingDebug(m_showCullingDebugWindow, rpiScene);
  749. }
  750. }
  751. if (m_showCpuProfiler)
  752. {
  753. ShowCpuProfilerWindow();
  754. }
  755. if (m_showGpuProfiler)
  756. {
  757. ShowGpuProfilerWindow();
  758. }
  759. if (m_showFileIoProfiler)
  760. {
  761. ShowFileIoProfilerWindow();
  762. }
  763. if (m_showTransientAttachmentProfiler)
  764. {
  765. ShowTransientAttachmentProfilerWindow();
  766. }
  767. m_scriptManager->TickImGui();
  768. m_contentWarningDialog.TickPopup();
  769. }
  770. void SampleComponentManager::ShowMenuBar()
  771. {
  772. if (ImGui::BeginMainMenuBar())
  773. {
  774. // If imgui doesn't have enough room to render a menu, it will fall back to the safe area which
  775. // is typically 3 pixels. This causes the menu to overlap the menu bar, and makes it easy to
  776. // accidentally select the first item on that menu bar. By altering the safe area temporarily
  777. // while drawing the menu, this problem can be avoided.
  778. ImVec2 cachedSafeArea = ImGui::GetStyle().DisplaySafeAreaPadding;
  779. ImGui::GetStyle().DisplaySafeAreaPadding = ImVec2(cachedSafeArea.x, cachedSafeArea.y + 16.0f);
  780. if (ImGui::BeginMenu("File"))
  781. {
  782. if (ImGui::MenuItem("Exit", "Ctrl-Q"))
  783. {
  784. RequestExit();
  785. }
  786. if (ImGui::MenuItem("Capture Frame...", "Ctrl-P"))
  787. {
  788. m_showFrameCaptureDialog = true;
  789. }
  790. ImGui::EndMenu();
  791. }
  792. if (ImGui::BeginMenu("View"))
  793. {
  794. if (Utils::SupportsResizeClientArea() && ImGui::MenuItem("Resize Viewport..."))
  795. {
  796. m_showResizeViewportDialog = true;
  797. }
  798. if (Utils::SupportsToggleFullScreenOfDefaultWindow() && ImGui::MenuItem("Toggle Full Screen"))
  799. {
  800. Utils::ToggleFullScreenOfDefaultWindow();
  801. }
  802. if (ImGui::MenuItem("Frame Time Histogram"))
  803. {
  804. m_showFramerateHistogram = !m_showFramerateHistogram;
  805. }
  806. if (ImGui::MenuItem("ImGui Metrics"))
  807. {
  808. m_showImGuiMetrics = !m_showImGuiMetrics;
  809. }
  810. if (ImGui::MenuItem("Sample Helper"))
  811. {
  812. m_showSampleHelper = !m_showSampleHelper;
  813. }
  814. if (ImGui::MenuItem("Frame Graph Visualizer"))
  815. {
  816. m_showFrameGraphVisualizer = !m_showFrameGraphVisualizer;
  817. }
  818. ImGui::EndMenu();
  819. }
  820. if (ImGui::BeginMenu("Samples"))
  821. {
  822. for (auto&& [parentMenuName, samples] : m_groupedSamples)
  823. {
  824. if (ImGui::BeginMenu(parentMenuName.c_str()))
  825. {
  826. for (int32_t index : samples)
  827. {
  828. SampleEntry& sample = m_availableSamples[index];
  829. const char* sampleName = sample.m_sampleName.c_str();
  830. bool enabled = m_isSampleSupported[index];
  831. if (ImGui::MenuItem(sampleName, nullptr, false, enabled))
  832. {
  833. Utils::ReportScriptableAction("OpenSample('%s')", sample.m_sampleName.c_str());
  834. if (sample.m_contentWarning.empty())
  835. {
  836. m_sampleChangeRequest = true;
  837. m_selectedSampleIndex = index;
  838. }
  839. else
  840. {
  841. m_contentWarningDialog.OpenPopupConfirmation(
  842. sample.m_contentWarningTitle,
  843. sample.m_contentWarning,
  844. [this, index]() {
  845. m_sampleChangeRequest = true;
  846. m_selectedSampleIndex = index;
  847. });
  848. }
  849. }
  850. }
  851. ImGui::EndMenu();
  852. }
  853. }
  854. ImGui::EndMenu();
  855. }
  856. #ifdef AZ_PROFILE_TELEMETRY
  857. if (ImGui::BeginMenu("RADTelemetry"))
  858. {
  859. if (ImGui::MenuItem("Toggle Capture", "Ctrl-T"))
  860. {
  861. Utils::ToggleRadTMCapture();
  862. }
  863. ImGui::EndMenu();
  864. }
  865. #endif // AZ_PROFILE_TELEMETRY
  866. if (ImGui::BeginMenu("Automation"))
  867. {
  868. const char* AutomationContentWarningTitle = AtomSampleComponent::CommonPhotosensitiveWarningTitle;
  869. const char* AutomationContentWarning = "Running automated scripts will trigger flashing images that could cause seizures or other adverse effects in photosensitive individuals.";
  870. if (ImGui::MenuItem("Run Script..."))
  871. {
  872. m_contentWarningDialog.OpenPopupConfirmation(
  873. AutomationContentWarningTitle,
  874. AutomationContentWarning,
  875. [this]() {
  876. m_scriptManager->OpenScriptRunnerDialog();
  877. });
  878. }
  879. if (ImGui::MenuItem("Run Precommit Wizard..."))
  880. {
  881. m_contentWarningDialog.OpenPopupConfirmation(
  882. AutomationContentWarningTitle,
  883. AutomationContentWarning,
  884. [this]() {
  885. m_scriptManager->OpenPrecommitWizard();
  886. });
  887. }
  888. ImGui::EndMenu();
  889. }
  890. if (ImGui::BeginMenu("Pass"))
  891. {
  892. if (ImGui::MenuItem(PassTreeToolName))
  893. {
  894. m_showPassTree = !m_showPassTree;
  895. Utils::ReportScriptableAction("ShowTool('%s', %s)", PassTreeToolName, m_showPassTree?"true":"false");
  896. }
  897. ImGui::EndMenu();
  898. }
  899. if (ImGui::BeginMenu("Culling"))
  900. {
  901. if (ImGui::MenuItem("Culling Debug Window"))
  902. {
  903. m_showCullingDebugWindow = !m_showCullingDebugWindow;
  904. }
  905. ImGui::EndMenu();
  906. }
  907. if (ImGui::BeginMenu("Profile"))
  908. {
  909. if (ImGui::MenuItem(CpuProfilerToolName))
  910. {
  911. m_showCpuProfiler = !m_showCpuProfiler;
  912. if (auto profilerSystem = AZ::Debug::ProfilerSystemInterface::Get(); profilerSystem)
  913. {
  914. profilerSystem->SetActive(m_showCpuProfiler);
  915. }
  916. Utils::ReportScriptableAction("ShowTool('%s', %s)", CpuProfilerToolName, m_showCpuProfiler ? "true" : "false");
  917. }
  918. if (AZ::IO::StreamerProfiler::Get() != nullptr)
  919. {
  920. if (ImGui::MenuItem(FileIoProfilerToolName))
  921. {
  922. m_showFileIoProfiler = !m_showFileIoProfiler;
  923. Utils::ReportScriptableAction(
  924. "ShowTool('%s', %s)", FileIoProfilerToolName, m_showFileIoProfiler ? "true" : "false");
  925. }
  926. }
  927. if (ImGui::MenuItem(GpuProfilerToolName))
  928. {
  929. m_showGpuProfiler = !m_showGpuProfiler;
  930. Utils::ReportScriptableAction("ShowTool('%s', %s)", GpuProfilerToolName, m_showGpuProfiler ? "true" : "false");
  931. }
  932. if (ImGui::MenuItem(TransientAttachmentProfilerToolName))
  933. {
  934. m_showTransientAttachmentProfiler = !m_showTransientAttachmentProfiler;
  935. AZ::RHI::RHISystemInterface::Get()->ModifyFrameSchedulerStatisticsFlags(
  936. AZ::RHI::FrameSchedulerStatisticsFlags::GatherTransientAttachmentStatistics,
  937. m_showTransientAttachmentProfiler);
  938. Utils::ReportScriptableAction("ShowTool('%s', %s)", TransientAttachmentProfilerToolName, m_showTransientAttachmentProfiler ? "true" : "false");
  939. }
  940. ImGui::EndMenu();
  941. }
  942. if (ImGui::BeginMenu("Help"))
  943. {
  944. if (ImGui::MenuItem("About"))
  945. {
  946. m_showAbout = !m_showAbout;
  947. }
  948. ImGui::EndMenu();
  949. }
  950. // Restore original safe area.
  951. ImGui::GetStyle().DisplaySafeAreaPadding = cachedSafeArea;
  952. ImGui::EndMainMenuBar();
  953. }
  954. }
  955. void SampleComponentManager::ShowSampleHelper()
  956. {
  957. if (ImGui::Begin("Sample Helper", &m_showSampleHelper, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  958. {
  959. if (ImGui::Button("Reset"))
  960. {
  961. //Removes the existing sample component and
  962. //resets the selection index
  963. Reset();
  964. CameraReset();
  965. m_selectedSampleIndex = -1;
  966. }
  967. ImGui::SameLine();
  968. if (ImGui::Button("Reset Sample"))
  969. {
  970. //Force a sample change event when the selection index
  971. //hasn't changed. This resets the sample component.
  972. SampleChange();
  973. }
  974. ImGui::SameLine();
  975. if (ImGui::Button("Reset Camera"))
  976. {
  977. CameraReset();
  978. }
  979. }
  980. ImGui::End();
  981. }
  982. void SampleComponentManager::ShowAboutWindow()
  983. {
  984. if (ImGui::Begin("About", &m_showAbout, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  985. {
  986. ImGui::Text("RHI API: %s", AZ::RHI::Factory::Get().GetName().GetCStr());
  987. }
  988. ImGui::End();
  989. }
  990. void SampleComponentManager::ShowPassTreeWindow()
  991. {
  992. m_imguiPassTree.Draw(m_showPassTree, AZ::RPI::PassSystemInterface::Get()->GetRootPass().get());
  993. }
  994. void SampleComponentManager::ShowFrameGraphVisualizerWindow()
  995. {
  996. AZ::RHI::Device* rhiDevice = Utils::GetRHIDevice().get();
  997. m_imguiFrameGraphVisualizer.Init(rhiDevice);
  998. m_imguiFrameGraphVisualizer.Draw(m_showFrameGraphVisualizer);
  999. }
  1000. void SampleComponentManager::ShowCpuProfilerWindow()
  1001. {
  1002. if (auto profilerImGui = Profiler::ProfilerImGuiInterface::Get(); profilerImGui)
  1003. {
  1004. profilerImGui->ShowCpuProfilerWindow(m_showCpuProfiler);
  1005. }
  1006. }
  1007. void SampleComponentManager::ShowFileIoProfilerWindow()
  1008. {
  1009. if (auto profilerImGui = AZ::IO::StreamerProfiler::Get(); profilerImGui)
  1010. {
  1011. profilerImGui->DrawStatistics(m_showFileIoProfiler);
  1012. }
  1013. }
  1014. void SampleComponentManager::ShowGpuProfilerWindow()
  1015. {
  1016. m_imguiGpuProfiler.Draw(m_showGpuProfiler, AZ::RPI::PassSystemInterface::Get()->GetRootPass());
  1017. }
  1018. void SampleComponentManager::ShowTransientAttachmentProfilerWindow()
  1019. {
  1020. auto* transientStats = AZ::RHI::RHISystemInterface::Get()->GetTransientAttachmentStatistics();
  1021. if (transientStats)
  1022. {
  1023. m_showTransientAttachmentProfiler = m_imguiTransientAttachmentProfiler.Draw(*transientStats);
  1024. }
  1025. }
  1026. void SampleComponentManager::ShowResizeViewportDialog()
  1027. {
  1028. static int size[2] = { 0, 0 };
  1029. if (size[0] <= 0)
  1030. {
  1031. size[0] = aznumeric_cast<int>(m_windowContext->GetViewport().m_maxX - m_windowContext->GetViewport().m_minX);
  1032. }
  1033. if (size[1] <= 0)
  1034. {
  1035. size[1] = aznumeric_cast<int>(m_windowContext->GetViewport().m_maxY - m_windowContext->GetViewport().m_minY);
  1036. }
  1037. bool dialogWasOpen = m_showResizeViewportDialog;
  1038. if (ImGui::Begin("Resize Viewport", &m_showResizeViewportDialog, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  1039. {
  1040. ImGui::InputInt2("Size", size);
  1041. if (ImGui::Button("Resize"))
  1042. {
  1043. Utils::ResizeClientArea(size[0], size[1], AzFramework::WindowPosOptions());
  1044. Utils::ReportScriptableAction("ResizeViewport(%d, %d)", size[0], size[1]);
  1045. // Re-initialize the size fields on the next frame so we can see whether the
  1046. // correct size was achieved (should be the same values the user entered)...
  1047. size[0] = 0;
  1048. size[1] = 0;
  1049. }
  1050. }
  1051. ImGui::End();
  1052. if (dialogWasOpen && !m_showResizeViewportDialog)
  1053. {
  1054. // Re-initialize the size fields next time the dialog is shown...
  1055. size[0] = 0;
  1056. size[1] = 0;
  1057. }
  1058. }
  1059. void SampleComponentManager::ShowFramerateHistogram(float deltaTime)
  1060. {
  1061. if (m_imGuiFrameTimer && ImGui::Begin("Frame Time Histogram", &m_showFramerateHistogram, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
  1062. {
  1063. ImGuiHistogramQueue::WidgetSettings settings;
  1064. settings.m_reportInverse = false;
  1065. settings.m_units = "ms";
  1066. m_imGuiFrameTimer->Tick(deltaTime * 1000.0f, settings);
  1067. }
  1068. ImGui::End();
  1069. }
  1070. void SampleComponentManager::RequestFrameCapture(const AZStd::string& filePath, bool hideImGui)
  1071. {
  1072. AZ_Assert(false == m_isFrameCapturePending, "Frame capture already in progress");
  1073. AZ_Assert(AZ::Render::InvalidFrameCaptureId == m_frameCaptureId, "Unfinished frame capture detected");
  1074. m_isFrameCapturePending = true;
  1075. m_hideImGuiDuringFrameCapture = hideImGui;
  1076. m_frameCaptureFilePath = filePath;
  1077. // Don't continue the script while a frame capture is pending in case subsequent changes
  1078. // interfere with the pending capture.
  1079. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  1080. if (m_hideImGuiDuringFrameCapture)
  1081. {
  1082. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::HideAllImGuiPasses);
  1083. // We also hide Open 3D Engine's debug text
  1084. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, "r_DisplayInfo 0");
  1085. // The ExecuteConsoleCommand request is handled in a deferred manner, so we have to delay the screenshot a bit.
  1086. m_countdownForFrameCapture = 1;
  1087. }
  1088. else
  1089. {
  1090. m_countdownForFrameCapture = 0;
  1091. }
  1092. }
  1093. void SampleComponentManager::OnFrameCaptureFinished(AZ::Render::FrameCaptureResult /*result*/, const AZStd::string& /*info*/)
  1094. {
  1095. AZ::Render::FrameCaptureNotificationBus::Handler::BusDisconnect();
  1096. if (m_hideImGuiDuringFrameCapture)
  1097. {
  1098. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::ShowAllImGuiPasses);
  1099. // We also show Open 3D Engine's debug text
  1100. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, "r_DisplayInfo 1");
  1101. }
  1102. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  1103. m_isFrameCapturePending = false;
  1104. }
  1105. bool SampleComponentManager::IsFrameCapturePending()
  1106. {
  1107. return m_isFrameCapturePending;
  1108. }
  1109. void SampleComponentManager::RunMainTestSuite(const AZStd::string& suiteFilePath, bool exitOnTestEnd, int randomSeed)
  1110. {
  1111. if (m_scriptManager)
  1112. {
  1113. m_scriptManager->RunMainTestSuite(suiteFilePath, exitOnTestEnd, randomSeed);
  1114. }
  1115. }
  1116. void SampleComponentManager::SetNumMSAASamples(int numMSAASamples)
  1117. {
  1118. AZ_Assert(IsValidNumMSAASamples(numMSAASamples), "Invalid MSAA sample setting");
  1119. m_numMSAASamples = numMSAASamples;
  1120. }
  1121. void SampleComponentManager::ResetNumMSAASamples()
  1122. {
  1123. m_numMSAASamples = GetDefaultNumMSAASamples();
  1124. }
  1125. void SampleComponentManager::ResetRPIScene()
  1126. {
  1127. ReleaseRPIScene();
  1128. SwitchSceneForRPISample();
  1129. }
  1130. void SampleComponentManager::ClearRPIScene()
  1131. {
  1132. ReleaseRPIScene();
  1133. }
  1134. void SampleComponentManager::ShowFrameCaptureDialog()
  1135. {
  1136. static bool requestCaptureOnNextFrame = false;
  1137. static bool hideImGuiFromFrameCapture = true;
  1138. if (requestCaptureOnNextFrame)
  1139. {
  1140. requestCaptureOnNextFrame = false;
  1141. RequestFrameCapture(m_imguiFrameCaptureSaver.GetSaveFilePath(), hideImGuiFromFrameCapture);
  1142. }
  1143. else if (!m_isFrameCapturePending) // Hide this dialog while taking a capture
  1144. {
  1145. if (ImGui::Begin("Frame Capture", &m_showFrameCaptureDialog))
  1146. {
  1147. ImGui::Checkbox("Hide ImGui", &hideImGuiFromFrameCapture);
  1148. ImGuiSaveFilePath::WidgetSettings settings;
  1149. settings.m_labels.m_filePath = "File Path (.png, .ppm, or .dds):";
  1150. m_imguiFrameCaptureSaver.Tick(settings);
  1151. if (ImGui::Button("Capture"))
  1152. {
  1153. // Don't actually do the capture until the next frame, so we can hide this dialog first
  1154. requestCaptureOnNextFrame = true;
  1155. if (hideImGuiFromFrameCapture)
  1156. {
  1157. Utils::ReportScriptableAction("CaptureScreenshot('%s')", m_imguiFrameCaptureSaver.GetSaveFilePath().c_str());
  1158. }
  1159. else
  1160. {
  1161. Utils::ReportScriptableAction("CaptureScreenshotWithImGui('%s')", m_imguiFrameCaptureSaver.GetSaveFilePath().c_str());
  1162. }
  1163. }
  1164. }
  1165. ImGui::End();
  1166. }
  1167. }
  1168. void SampleComponentManager::RequestExit()
  1169. {
  1170. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  1171. AZ::TickBus::Handler::BusDisconnect();
  1172. AzFramework::InputChannelEventListener::Disconnect();
  1173. m_exitRequested = true;
  1174. }
  1175. void SampleComponentManager::ShutdownActiveSample()
  1176. {
  1177. m_exampleEntity->Deactivate();
  1178. // Pointer to all the passes within m_rhiSamplePasses must be nullified before all the samples within m_activeSamples are destroyed.
  1179. SetRHISamplePass(nullptr);
  1180. for (AZ::Component* activeComponent : m_activeSamples)
  1181. {
  1182. if (activeComponent != nullptr)
  1183. {
  1184. // Disable the camera controller just in case the active sample enabled it and didn't disable in Deactivate().
  1185. AZ::Debug::CameraControllerRequestBus::Event(m_cameraEntity->GetId(), &AZ::Debug::CameraControllerRequestBus::Events::Disable);
  1186. m_exampleEntity->RemoveComponent(activeComponent);
  1187. delete activeComponent;
  1188. }
  1189. }
  1190. m_activeSamples.clear();
  1191. // Force a reset of the shader variant finder to get more consistent testing of samples every time they are run, rather
  1192. // than the first time for each sample being "special".
  1193. auto variantFinder = AZ::Interface<AZ::RPI::IShaderVariantFinder>::Get();
  1194. variantFinder->Reset();
  1195. }
  1196. void SampleComponentManager::Reset()
  1197. {
  1198. ShutdownActiveSample();
  1199. m_exampleEntity->Activate();
  1200. // Reset to RHI sample pipeline
  1201. SwitchSceneForRHISample();
  1202. SetRHISamplePass(nullptr);
  1203. }
  1204. void SampleComponentManager::CreateDefaultCamera()
  1205. {
  1206. if (m_cameraEntity)
  1207. {
  1208. return;
  1209. }
  1210. // A camera entity will be created by the entity context request bus so that the component for this entity can use a feature processor.
  1211. AzFramework::EntityContextRequestBus::EventResult(m_cameraEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "CameraEntity");
  1212. //Add debug camera and controller components
  1213. AZ::Debug::CameraComponentConfig cameraConfig(m_windowContext);
  1214. cameraConfig.m_fovY = AZ::Constants::QuarterPi;
  1215. cameraConfig.m_depthFar = 1000.0f;
  1216. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::CameraComponent>())
  1217. ->SetConfiguration(cameraConfig);
  1218. m_cameraEntity->CreateComponent(azrtti_typeid<AzFramework::TransformComponent>());
  1219. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::ArcBallControllerComponent>());
  1220. m_cameraEntity->CreateComponent(azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  1221. m_cameraEntity->Activate();
  1222. m_scriptManager->SetCameraEntity(m_cameraEntity);
  1223. }
  1224. void SampleComponentManager::SetupImGuiContext()
  1225. {
  1226. AdjustImGuiFontScale();
  1227. // Add imgui context
  1228. Render::ImGuiSystemRequestBus::BroadcastResult(m_isImGuiAvailable, &Render::ImGuiSystemRequests::PushActiveContextFromDefaultPass);
  1229. AZ_Assert(m_isImGuiAvailable, "Unable set default imgui context to active. Does your pipeline have an ImGui pass marked as default? Your pass assets may need to be rebuilt.");
  1230. }
  1231. void SampleComponentManager::ActiveImGuiContextChanged(ImGuiContext* context)
  1232. {
  1233. ImGui::SetCurrentContext(context);
  1234. }
  1235. bool SampleComponentManager::OpenSample(const AZStd::string& sampleName)
  1236. {
  1237. for (int32_t i = 0; i < m_availableSamples.size(); i++)
  1238. {
  1239. if (m_availableSamples[i].m_parentMenuName + '/' + m_availableSamples[i].m_sampleName == sampleName)
  1240. {
  1241. if (!m_availableSamples[i].m_isSupportedFunc || m_availableSamples[i].m_isSupportedFunc())
  1242. {
  1243. m_selectedSampleIndex = i;
  1244. m_sampleChangeRequest = true;
  1245. return true;
  1246. }
  1247. else
  1248. {
  1249. AZ_Error("SampleComponentManager", false, "Sample '%s' is not supported on this platform.", sampleName.c_str());
  1250. }
  1251. }
  1252. }
  1253. return false;
  1254. }
  1255. bool SampleComponentManager::ShowTool(const AZStd::string& toolName, bool enable)
  1256. {
  1257. if (toolName == PassTreeToolName)
  1258. {
  1259. m_showPassTree = enable;
  1260. return true;
  1261. }
  1262. else if (toolName == CpuProfilerToolName)
  1263. {
  1264. m_showCpuProfiler = enable;
  1265. return true;
  1266. }
  1267. else if (toolName == FileIoProfilerToolName)
  1268. {
  1269. m_showFileIoProfiler = enable;
  1270. return true;
  1271. }
  1272. else if (toolName == GpuProfilerToolName)
  1273. {
  1274. m_showGpuProfiler = enable;
  1275. return true;
  1276. }
  1277. else if (toolName == TransientAttachmentProfilerToolName)
  1278. {
  1279. m_showTransientAttachmentProfiler = enable;
  1280. return true;
  1281. }
  1282. return false;
  1283. }
  1284. void SampleComponentManager::SampleChange()
  1285. {
  1286. if (m_selectedSampleIndex == -1)
  1287. {
  1288. return;
  1289. }
  1290. ShutdownActiveSample();
  1291. // Reset the camera *before* activating the sample, because the sample's Activate() function might
  1292. // want to reposition the camera.
  1293. CameraReset();
  1294. const SampleEntry& sampleEntry = m_availableSamples[m_selectedSampleIndex];
  1295. // Create scene and render pipeline before create sample component
  1296. if (sampleEntry.m_pipelineType == SamplePipelineType::RHI)
  1297. {
  1298. SwitchSceneForRHISample();
  1299. }
  1300. else if (sampleEntry.m_pipelineType == SamplePipelineType::RPI)
  1301. {
  1302. SwitchSceneForRPISample();
  1303. }
  1304. SampleComponentConfig config(m_windowContext, m_cameraEntity->GetId(), m_entityContextId);
  1305. // special setup for RHI samples
  1306. if (sampleEntry.m_pipelineType == SamplePipelineType::RHI)
  1307. {
  1308. for (AZ::RPI::Ptr<RHISamplePass> samplePass : m_rhiSamplePasses)
  1309. {
  1310. BasicRHIComponent* rhiSampleComponent = static_cast<BasicRHIComponent*>(m_exampleEntity->CreateComponent(sampleEntry.m_sampleUuid));
  1311. rhiSampleComponent->SetConfiguration(config);
  1312. rhiSampleComponent->SetViewIndex(samplePass->GetViewIndex());
  1313. if (rhiSampleComponent->IsSupportedRHISamplePipeline())
  1314. {
  1315. samplePass->SetRHISample(rhiSampleComponent);
  1316. }
  1317. else
  1318. {
  1319. samplePass->SetRHISample(nullptr);
  1320. }
  1321. m_activeSamples.push_back(rhiSampleComponent);
  1322. }
  1323. }
  1324. else
  1325. {
  1326. AZ::Component* newComponent = m_exampleEntity->CreateComponent(sampleEntry.m_sampleUuid);
  1327. newComponent->SetConfiguration(config);
  1328. m_activeSamples.push_back(newComponent);
  1329. }
  1330. m_exampleEntity->Activate();
  1331. // Even though this is done in CameraReset(), the example component wasn't activated at the time so we have to send this event again.
  1332. ExampleComponentRequestBus::Event(m_exampleEntity->GetId(), &ExampleComponentRequestBus::Events::ResetCamera);
  1333. }
  1334. void SampleComponentManager::CameraReset()
  1335. {
  1336. // Reset the camera transform. Some examples do not use a controller or use a controller that doesn't override the whole transform.
  1337. // Set to a transform that is 5 units away from the origin and looking at the origin along the Y axis.
  1338. const AZ::EntityId cameraEntityId = m_cameraEntity->GetId();
  1339. AZ::TransformBus::Event(cameraEntityId, &AZ::TransformBus::Events::SetWorldTM, AZ::Transform::CreateTranslation(AZ::Vector3(0.0f, -5.0f, 0.0f)));
  1340. AZ::Debug::CameraControllerRequestBus::Event(cameraEntityId, &AZ::Debug::CameraControllerRequestBus::Events::Reset);
  1341. // Tell the current example to reset the camera, any example that controls the camera and preserves controller state should implement this event
  1342. ExampleComponentRequestBus::Event(m_exampleEntity->GetId(), &ExampleComponentRequestBus::Events::ResetCamera);
  1343. }
  1344. void SampleComponentManager::CreateSceneForRHISample()
  1345. {
  1346. // Create and register the rhi scene with only feature processors required for AtomShimRenderer (only for AtomSampleViewerLauncher)
  1347. RPI::SceneDescriptor sceneDesc;
  1348. sceneDesc.m_nameId = AZ::Name("RHI");
  1349. sceneDesc.m_featureProcessorNames.push_back("AZ::Render::AuxGeomFeatureProcessor");
  1350. m_rhiScene = RPI::Scene::CreateScene(sceneDesc);
  1351. m_rhiScene->Activate();
  1352. RPI::RenderPipelineDescriptor pipelineDesc;
  1353. pipelineDesc.m_name = "RHISamplePipeline";
  1354. pipelineDesc.m_rootPassTemplate = "RHISamplePipelineTemplate";
  1355. // Add view to pipeline since there are few RHI samples are using ViewSrg
  1356. pipelineDesc.m_mainViewTagName = "MainCamera";
  1357. m_renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get());
  1358. m_rhiScene->AddRenderPipeline(m_renderPipeline);
  1359. m_renderPipeline->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1360. // Get RHISamplePass
  1361. AZ::RPI::PassFilter passFilter = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), m_renderPipeline.get());
  1362. m_rhiSamplePasses.push_back(azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(passFilter)));
  1363. AZ::RPI::RPISystemInterface* rpiSystem = AZ::RPI::RPISystemInterface::Get();
  1364. if (rpiSystem->GetXRSystem())
  1365. {
  1366. // Build the pipeline for left eye
  1367. pipelineDesc.m_name = "RHISamplePipelineXRLeft";
  1368. pipelineDesc.m_rootPassTemplate = "RHISamplePipelineXRLeftTemplate";
  1369. RPI::RenderPipelinePtr renderPipelineLeft = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get(), AZ::RPI::WindowContext::SwapChainMode::XrLeft);
  1370. // Build the pipeline for right eye
  1371. pipelineDesc.m_name = "RHISamplePipelineXRRight";
  1372. pipelineDesc.m_rootPassTemplate = "RHISamplePipelineXRRightTemplate";
  1373. RPI::RenderPipelinePtr renderPipelineRight = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get(), AZ::RPI::WindowContext::SwapChainMode::XrRight);
  1374. //Add both the pipelines to the scene
  1375. m_rhiScene->AddRenderPipeline(renderPipelineLeft);
  1376. m_rhiScene->AddRenderPipeline(renderPipelineRight);
  1377. renderPipelineLeft->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1378. renderPipelineRight->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1379. // Set the correct view index for the RHI sample passes
  1380. AZ::RPI::PassFilter rhiSamplePassFilterLeft = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), renderPipelineLeft.get());
  1381. AZ::RPI::Ptr<RHISamplePass> rhiSamplePassLeft = azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(rhiSamplePassFilterLeft));
  1382. rhiSamplePassLeft->SetViewIndex(0);
  1383. m_rhiSamplePasses.push_back(rhiSamplePassLeft);
  1384. AZ::RPI::PassFilter rhiSamplePassFilterRight = AZ::RPI::PassFilter::CreateWithPassName(AZ::Name("RHISamplePass"), renderPipelineRight.get());
  1385. AZ::RPI::Ptr<RHISamplePass> rhiSamplePassRight = azrtti_cast<RHISamplePass*>(AZ::RPI::PassSystemInterface::Get()->FindFirstPass(rhiSamplePassFilterRight));
  1386. rhiSamplePassRight->SetViewIndex(1);
  1387. m_rhiSamplePasses.push_back(rhiSamplePassRight);
  1388. //Cache the pipelines in case we want to enable/disable them
  1389. m_xrPipelines.push_back(renderPipelineLeft);
  1390. m_xrPipelines.push_back(renderPipelineRight);
  1391. //Disable XR pipelines by default
  1392. DisableXrPipelines();
  1393. }
  1394. // Register the RHi scene
  1395. RPI::RPISystemInterface::Get()->RegisterScene(m_rhiScene);
  1396. // Setup imGui since a new render pipeline with imgui pass was created
  1397. SetupImGuiContext();
  1398. }
  1399. void SampleComponentManager::ReleaseRHIScene()
  1400. {
  1401. if (m_rhiScene)
  1402. {
  1403. m_rhiSamplePasses.clear();
  1404. m_xrPipelines.clear();
  1405. m_renderPipeline = nullptr;
  1406. RPI::RPISystemInterface::Get()->UnregisterScene(m_rhiScene);
  1407. m_rhiScene = nullptr;
  1408. }
  1409. }
  1410. void SampleComponentManager::SwitchSceneForRHISample()
  1411. {
  1412. ReleaseRPIScene();
  1413. ReleaseRHIScene();
  1414. CreateSceneForRHISample();
  1415. }
  1416. void SampleComponentManager::CreateSceneForRPISample()
  1417. {
  1418. // Create and register a scene with all available feature processors
  1419. RPI::SceneDescriptor sceneDesc;
  1420. sceneDesc.m_nameId = AZ::Name("RPI");
  1421. m_rpiScene = RPI::Scene::CreateScene(sceneDesc);
  1422. m_rpiScene->EnableAllFeatureProcessors();
  1423. // Bind m_rpiScene to the GameEntityContext's AzFramework::Scene so the RPI Scene can be found by the entity context
  1424. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  1425. AZ_Assert(sceneSystem, "SampleComponentManager requires an implementation of the scene system.");
  1426. AZStd::shared_ptr<AzFramework::Scene> mainScene = sceneSystem->GetScene(AzFramework::Scene::MainSceneName);
  1427. AZ_Assert(mainScene, "Main scene missing during system component initialization"); // This should never happen unless scene creation has changed.
  1428. // Add RPI::Scene as a sub system for the default AzFramework Scene
  1429. [[maybe_unused]] bool result = mainScene->SetSubsystem(m_rpiScene);
  1430. AZ_Assert(result, "SampleComponentManager failed to register the RPI scene with the general scene.");
  1431. m_rpiScene->Activate();
  1432. // Register scene to RPI system so it will be processed/rendered per tick
  1433. RPI::RPISystemInterface::Get()->RegisterScene(m_rpiScene);
  1434. // Create MainPipeline as its render pipeline
  1435. RPI::RenderPipelineDescriptor pipelineDesc;
  1436. pipelineDesc.m_name = "RPISamplePipeline";
  1437. pipelineDesc.m_rootPassTemplate = GetRootPassTemplateName();
  1438. pipelineDesc.m_mainViewTagName = "MainCamera";
  1439. pipelineDesc.m_allowModification = true;
  1440. // set pipeline MSAA samples
  1441. AZ_Assert(IsValidNumMSAASamples(m_numMSAASamples), "Invalid MSAA sample setting");
  1442. pipelineDesc.m_renderSettings.m_multisampleState.m_samples = static_cast<uint16_t>(m_numMSAASamples);
  1443. bool isNonMsaaPipeline = (pipelineDesc.m_renderSettings.m_multisampleState.m_samples == 1);
  1444. const char* supervariantName = isNonMsaaPipeline ? AZ::RPI::NoMsaaSupervariantName : "";
  1445. AZ::RPI::ShaderSystemInterface::Get()->SetSupervariantName(AZ::Name(supervariantName));
  1446. RPI::RenderPipelinePtr renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get());
  1447. m_rpiScene->AddRenderPipeline(renderPipeline);
  1448. renderPipeline->SetDefaultViewFromEntity(m_cameraEntity->GetId());
  1449. AZ::RPI::RPISystemInterface* rpiSystem = AZ::RPI::RPISystemInterface::Get();
  1450. if (rpiSystem->GetXRSystem())
  1451. {
  1452. // Build the pipeline for left eye
  1453. pipelineDesc.m_name = "RPISamplePipelineXRLeft";
  1454. pipelineDesc.m_rootPassTemplate = "LowEndPipelineXRLeftTemplate";
  1455. RPI::RenderPipelinePtr renderPipelineLeft = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get(), AZ::RPI::WindowContext::SwapChainMode::XrLeft);
  1456. // Build the pipeline for right eye
  1457. pipelineDesc.m_name = "RHISamplePipelineXRRight";
  1458. pipelineDesc.m_rootPassTemplate = "LowEndPipelineXRRightTemplate";
  1459. RPI::RenderPipelinePtr renderPipelineRight = RPI::RenderPipeline::CreateRenderPipelineForWindow(pipelineDesc, *m_windowContext.get(), AZ::RPI::WindowContext::SwapChainMode::XrRight);
  1460. //Add both the pipelines to the scene
  1461. m_rpiScene->AddRenderPipeline(renderPipelineLeft);
  1462. m_rpiScene->AddRenderPipeline(renderPipelineRight);
  1463. renderPipelineLeft->SetDefaultStereoscopicViewFromEntity(m_cameraEntity->GetId(), RPI::ViewType::XrLeft); //Left eye
  1464. renderPipelineRight->SetDefaultStereoscopicViewFromEntity(m_cameraEntity->GetId(), RPI::ViewType::XrRight); //Right eye
  1465. //Cache the pipelines in case we want to enable/disable them
  1466. m_xrPipelines.push_back(renderPipelineLeft);
  1467. m_xrPipelines.push_back(renderPipelineRight);
  1468. // Disable XR pipelines by default
  1469. DisableXrPipelines();
  1470. }
  1471. // As part of our initialization we need to create the BRDF texture generation pipeline
  1472. AZ::RPI::RenderPipelineDescriptor brdfPipelineDesc;
  1473. brdfPipelineDesc.m_mainViewTagName = "MainCamera";
  1474. brdfPipelineDesc.m_name = "BRDFTexturePipeline";
  1475. brdfPipelineDesc.m_rootPassTemplate = "BRDFTexturePipeline";
  1476. brdfPipelineDesc.m_executeOnce = true;
  1477. RPI::RenderPipelinePtr brdfTexturePipeline = AZ::RPI::RenderPipeline::CreateRenderPipeline(brdfPipelineDesc);
  1478. m_rpiScene->AddRenderPipeline(brdfTexturePipeline);
  1479. // Save a reference to the generated BRDF texture so it doesn't get deleted if all the passes referring to it get deleted and it's ref count goes to zero
  1480. if (!m_brdfTexture)
  1481. {
  1482. const AZStd::shared_ptr<const RPI::PassTemplate> brdfTextureTemplate = RPI::PassSystemInterface::Get()->GetPassTemplate(Name("BRDFTextureTemplate"));
  1483. Data::Asset<RPI::AttachmentImageAsset> brdfImageAsset = RPI::AssetUtils::LoadAssetById<RPI::AttachmentImageAsset>(
  1484. brdfTextureTemplate->m_imageAttachments[0].m_assetRef.m_assetId, RPI::AssetUtils::TraceLevel::Error);
  1485. if (brdfImageAsset.IsReady())
  1486. {
  1487. m_brdfTexture = RPI::AttachmentImage::FindOrCreate(brdfImageAsset);
  1488. }
  1489. }
  1490. // Setup imGui since a new render pipeline with imgui pass was created
  1491. SetupImGuiContext();
  1492. }
  1493. void SampleComponentManager::ReleaseRPIScene()
  1494. {
  1495. if (m_rpiScene)
  1496. {
  1497. RPI::RPISystemInterface::Get()->UnregisterScene(m_rpiScene);
  1498. auto sceneSystem = AzFramework::SceneSystemInterface::Get();
  1499. AZ_Assert(sceneSystem, "Scene system was destroyed before SampleComponentManager was able to unregister the RPI scene.");
  1500. AZStd::shared_ptr<AzFramework::Scene> scene = sceneSystem->GetScene(AzFramework::Scene::MainSceneName);
  1501. AZ_Assert(scene, "The main scene wasn't found in the scene system.");
  1502. [[maybe_unused]] bool result = scene->UnsetSubsystem(m_rpiScene);
  1503. AZ_Assert(result, "SampleComponentManager failed to unregister its RPI scene from the general scene.");
  1504. m_xrPipelines.clear();
  1505. m_rpiScene = nullptr;
  1506. }
  1507. }
  1508. void SampleComponentManager::SwitchSceneForRPISample()
  1509. {
  1510. ReleaseRHIScene();
  1511. ReleaseRPIScene();
  1512. CreateSceneForRPISample();
  1513. }
  1514. // AzFramework::AssetCatalogEventBus::Handler overrides ...
  1515. void SampleComponentManager::OnCatalogLoaded([[maybe_unused]] const char* catalogFile)
  1516. {
  1517. AZ::TickBus::QueueFunction([&]()
  1518. {
  1519. ActivateInternal();
  1520. });
  1521. }
  1522. void SampleComponentManager::SetRHISamplePass(BasicRHIComponent* sampleComponent)
  1523. {
  1524. for (AZ::RPI::Ptr<RHISamplePass> samplePass : m_rhiSamplePasses)
  1525. {
  1526. samplePass->SetRHISample(sampleComponent);
  1527. }
  1528. }
  1529. void SampleComponentManager::DisableXrPipelines()
  1530. {
  1531. for (RPI::RenderPipelinePtr xrPipeline : m_xrPipelines)
  1532. {
  1533. xrPipeline->RemoveFromRenderTick();
  1534. }
  1535. }
  1536. void SampleComponentManager::EnableXrPipelines()
  1537. {
  1538. for (RPI::RenderPipelinePtr xrPipeline : m_xrPipelines)
  1539. {
  1540. xrPipeline->AddToRenderTick();
  1541. }
  1542. }
  1543. } // namespace AtomSampleViewer