BootstrapSystemComponent.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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 <BootstrapSystemComponent.h>
  9. #include <AzCore/Asset/AssetCommon.h>
  10. #include <AzCore/Component/ComponentApplicationBus.h>
  11. #include <AzCore/Component/ComponentApplicationLifecycle.h>
  12. #include <AzCore/Component/Entity.h>
  13. #include <AzCore/NativeUI/NativeUIRequests.h>
  14. #include <AzCore/Serialization/SerializeContext.h>
  15. #include <AzCore/std/smart_ptr/make_shared.h>
  16. #include <AzCore/Utils/Utils.h>
  17. #include <AzCore/StringFunc/StringFunc.h>
  18. #include <AzFramework/API/ApplicationAPI.h>
  19. #include <AzFramework/Components/TransformComponent.h>
  20. #include <AzFramework/Entity/GameEntityContextBus.h>
  21. #include <AzFramework/Asset/AssetSystemBus.h>
  22. #include <ISystem.h>
  23. #include <Atom/RHI/RHISystemInterface.h>
  24. #include <Atom/RPI.Reflect/Image/AttachmentImageAsset.h>
  25. #include <Atom/RPI.Reflect/Image/AttachmentImageAssetCreator.h>
  26. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  27. #include <Atom/RPI.Public/Pass/Pass.h>
  28. #include <Atom/RPI.Public/Pass/PassSystemInterface.h>
  29. #include <Atom/RPI.Public/RenderPipeline.h>
  30. #include <Atom/RPI.Public/ViewportContextBus.h>
  31. #include <Atom/RPI.Public/RPISystemInterface.h>
  32. #include <Atom/RPI.Public/Shader/ShaderResourceGroup.h>
  33. #include <Atom/RPI.Public/Shader/ShaderSystem.h>
  34. #include <Atom/Bootstrap/DefaultWindowBus.h>
  35. #include <Atom/Bootstrap/BootstrapNotificationBus.h>
  36. #include <Atom/RPI.Reflect/System/AnyAsset.h>
  37. #include <AzCore/Console/IConsole.h>
  38. #include <BootstrapSystemComponent_Traits_Platform.h>
  39. void cvar_r_renderPipelinePath_Changed(const AZ::CVarFixedString& newPipelinePath)
  40. {
  41. auto viewportContextManager = AZ::Interface<AZ::RPI::ViewportContextRequestsInterface>::Get();
  42. if (!viewportContextManager)
  43. {
  44. return;
  45. }
  46. auto viewportContext = viewportContextManager->GetDefaultViewportContext();
  47. if (!viewportContext)
  48. {
  49. return;
  50. }
  51. AZ::Data::Asset<AZ::RPI::AnyAsset> pipelineAsset =
  52. AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::AnyAsset>(newPipelinePath.data(), AZ::RPI::AssetUtils::TraceLevel::Error);
  53. if (pipelineAsset)
  54. {
  55. AZ::RPI::RenderPipelineDescriptor renderPipelineDescriptor =
  56. *AZ::RPI::GetDataFromAnyAsset<AZ::RPI::RenderPipelineDescriptor>(pipelineAsset); // Copy descriptor from asset
  57. AZ::Render::Bootstrap::RequestBus::Broadcast(&AZ::Render::Bootstrap::RequestBus::Events::SwitchRenderPipeline, renderPipelineDescriptor, viewportContext);
  58. }
  59. else
  60. {
  61. AZ_Warning("SetDefaultPipeline", false, "Failed to switch default render pipeline to %s: can't load the asset", newPipelinePath.data());
  62. }
  63. }
  64. AZ_CVAR(AZ::CVarFixedString, r_renderPipelinePath, AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME, cvar_r_renderPipelinePath_Changed, AZ::ConsoleFunctorFlags::DontReplicate, "The asset (.azasset) path for default render pipeline");
  65. AZ_CVAR(AZ::CVarFixedString, r_default_openxr_pipeline_name, "passes/MultiViewRenderPipeline.azasset", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Default openXr render pipeline name");
  66. AZ_CVAR(AZ::CVarFixedString, r_default_openxr_left_pipeline_name, "passes/XRLeftRenderPipeline.azasset", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Default openXr Left eye render pipeline name");
  67. AZ_CVAR(AZ::CVarFixedString, r_default_openxr_right_pipeline_name, "passes/XRRightRenderPipeline.azasset", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Default openXr Right eye render pipeline name");
  68. AZ_CVAR(uint32_t, r_width, 1920, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Starting window width in pixels.");
  69. AZ_CVAR(uint32_t, r_height, 1080, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Starting window height in pixels.");
  70. AZ_CVAR(uint32_t, r_fullscreen, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Starting fullscreen state.");
  71. AZ_CVAR(uint32_t, r_resolutionMode, 0, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "0: render resolution same as window client area size, 1: render resolution use the values specified by r_width and r_height");
  72. namespace AZ
  73. {
  74. namespace Render
  75. {
  76. namespace Bootstrap
  77. {
  78. void BootstrapSystemComponent::Reflect(ReflectContext* context)
  79. {
  80. if (SerializeContext* serialize = azrtti_cast<SerializeContext*>(context))
  81. {
  82. serialize->Class<BootstrapSystemComponent, Component>()
  83. ->Version(1)
  84. ;
  85. if (EditContext* ec = serialize->GetEditContext())
  86. {
  87. ec->Class<BootstrapSystemComponent>("Atom RPI", "Atom Renderer")
  88. ->ClassElement(Edit::ClassElements::EditorData, "")
  89. ->Attribute(Edit::Attributes::AutoExpand, true)
  90. ;
  91. }
  92. }
  93. }
  94. void BootstrapSystemComponent::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided)
  95. {
  96. provided.push_back(AZ_CRC("BootstrapSystemComponent", 0xb8f32711));
  97. }
  98. void BootstrapSystemComponent::GetRequiredServices(ComponentDescriptor::DependencyArrayType& required)
  99. {
  100. required.push_back(AZ_CRC("RPISystem", 0xf2add773));
  101. required.push_back(AZ_CRC("SceneSystemComponentService", 0xd8975435));
  102. }
  103. void BootstrapSystemComponent::GetDependentServices(ComponentDescriptor::DependencyArrayType& dependent)
  104. {
  105. dependent.push_back(AZ_CRC("ImGuiSystemComponent", 0x2f08b9a7));
  106. dependent.push_back(AZ_CRC("PrimitiveSystemComponent", 0xc860fa59));
  107. dependent.push_back(AZ_CRC("MeshSystemComponent", 0x21e5bbb6));
  108. dependent.push_back(AZ_CRC("CoreLightsService", 0x91932ef6));
  109. dependent.push_back(AZ_CRC("DynamicDrawService", 0x023c1673));
  110. dependent.push_back(AZ_CRC("CommonService", 0x6398eec4));
  111. dependent.push_back(AZ_CRC_CE("HairService"));
  112. }
  113. void BootstrapSystemComponent::GetIncompatibleServices(ComponentDescriptor::DependencyArrayType& incompatible)
  114. {
  115. incompatible.push_back(AZ_CRC("BootstrapSystemComponent", 0xb8f32711));
  116. }
  117. BootstrapSystemComponent::BootstrapSystemComponent()
  118. {
  119. }
  120. BootstrapSystemComponent::~BootstrapSystemComponent()
  121. {
  122. m_viewportContext.reset();
  123. }
  124. //! Helper function that parses the command line arguments
  125. //! looking for r_width, r_height and r_fullscreen.
  126. //! It is important to call this before using r_width, r_height or r_fullscreen
  127. //! because at the moment this system component initializes before Legacy System.cpp gets to parse
  128. //! command line arguments into cvars.
  129. static void UpdateCVarsFromCommandLine()
  130. {
  131. AZ::CommandLine* pCmdLine = nullptr;
  132. ComponentApplicationBus::BroadcastResult(pCmdLine, &AZ::ComponentApplicationBus::Events::GetAzCommandLine);
  133. if (!pCmdLine)
  134. {
  135. return;
  136. }
  137. const AZStd::string fullscreenCvarName("r_fullscreen");
  138. if (pCmdLine->HasSwitch(fullscreenCvarName))
  139. {
  140. auto numValues = pCmdLine->GetNumSwitchValues(fullscreenCvarName);
  141. if (numValues > 0)
  142. {
  143. auto valueStr = pCmdLine->GetSwitchValue(fullscreenCvarName);
  144. if (AZ::StringFunc::LooksLikeBool(valueStr.c_str()))
  145. {
  146. r_fullscreen = AZ::StringFunc::ToBool(valueStr.c_str());
  147. }
  148. }
  149. }
  150. const AZStd::string widthCvarName("r_width");
  151. if (pCmdLine->HasSwitch(widthCvarName))
  152. {
  153. auto numValues = pCmdLine->GetNumSwitchValues(widthCvarName);
  154. if (numValues > 0)
  155. {
  156. auto valueStr = pCmdLine->GetSwitchValue(widthCvarName);
  157. if (AZ::StringFunc::LooksLikeInt(valueStr.c_str()))
  158. {
  159. auto width = AZ::StringFunc::ToInt(valueStr.c_str());
  160. if (width > 0)
  161. {
  162. r_width = width;
  163. }
  164. }
  165. }
  166. }
  167. const AZStd::string heightCvarName("r_height");
  168. if (pCmdLine->HasSwitch(heightCvarName))
  169. {
  170. auto numValues = pCmdLine->GetNumSwitchValues(heightCvarName);
  171. if (numValues > 0)
  172. {
  173. auto valueStr = pCmdLine->GetSwitchValue(heightCvarName);
  174. if (AZ::StringFunc::LooksLikeInt(valueStr.c_str()))
  175. {
  176. auto height = AZ::StringFunc::ToInt(valueStr.c_str());
  177. if (height > 0)
  178. {
  179. r_height = height;
  180. }
  181. }
  182. }
  183. }
  184. const AZStd::string resolutionModeCvarName("r_resolutionMode");
  185. if (pCmdLine->HasSwitch(resolutionModeCvarName))
  186. {
  187. auto numValues = pCmdLine->GetNumSwitchValues(resolutionModeCvarName);
  188. if (numValues > 0)
  189. {
  190. auto valueStr = pCmdLine->GetSwitchValue(resolutionModeCvarName);
  191. if (AZ::StringFunc::LooksLikeInt(valueStr.c_str()))
  192. {
  193. auto resolutionMode = AZ::StringFunc::ToInt(valueStr.c_str());
  194. if (resolutionMode >= 0)
  195. {
  196. r_resolutionMode = resolutionMode;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. void BootstrapSystemComponent::Activate()
  203. {
  204. // Create a native window only if it's a launcher (or standalone)
  205. // LY editor create its own window which we can get its handle through AzFramework::WindowSystemNotificationBus::Handler's OnWindowCreated() function
  206. AZ::ApplicationTypeQuery appType;
  207. ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  208. if (!appType.IsValid() || appType.IsGame())
  209. {
  210. // GFX TODO - investigate window creation being part of the GameApplication.
  211. auto projectTitle = AZ::Utils::GetProjectDisplayName();
  212. // It is important to call this before using r_width, r_height or r_fullscreen
  213. // because at the moment this system component initializes before Legacy System.cpp gets to parse
  214. // command line arguments into cvars.
  215. UpdateCVarsFromCommandLine();
  216. m_nativeWindow = AZStd::make_unique<AzFramework::NativeWindow>(projectTitle.c_str(), AzFramework::WindowGeometry(0, 0, r_width, r_height));
  217. AZ_Assert(m_nativeWindow, "Failed to create the game window\n");
  218. m_nativeWindow->Activate();
  219. m_windowHandle = m_nativeWindow->GetWindowHandle();
  220. }
  221. else
  222. {
  223. // Disable default scene creation for non-games projects
  224. // This can be manually overridden via the DefaultWindowBus.
  225. m_createDefaultScene = false;
  226. }
  227. TickBus::Handler::BusConnect();
  228. // Listen for window system requests (e.g. requests for default window handle)
  229. AzFramework::WindowSystemRequestBus::Handler::BusConnect();
  230. // Listen for window system notifications (e.g. window being created by Editor)
  231. AzFramework::WindowSystemNotificationBus::Handler::BusConnect();
  232. Render::Bootstrap::DefaultWindowBus::Handler::BusConnect();
  233. Render::Bootstrap::RequestBus::Handler::BusConnect();
  234. // Listen for application's window creation/destruction (e.g. window is created/destroyed on Android when suspending the app)
  235. AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusConnect();
  236. // delay one frame for Initialize which asset system is ready by then
  237. AZ::TickBus::QueueFunction(
  238. [this]()
  239. {
  240. Initialize();
  241. if (m_nativeWindow)
  242. {
  243. // wait until swapchain has been created before setting fullscreen state
  244. if (r_resolutionMode > 0u)
  245. {
  246. m_nativeWindow->SetEnableCustomizedResolution(true);
  247. m_nativeWindow->SetRenderResolution(AzFramework::WindowSize(r_width, r_height));
  248. }
  249. else
  250. {
  251. m_nativeWindow->SetEnableCustomizedResolution(false);
  252. }
  253. m_nativeWindow->SetFullScreenState(r_fullscreen);
  254. }
  255. });
  256. }
  257. void BootstrapSystemComponent::Deactivate()
  258. {
  259. AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect();
  260. Render::Bootstrap::RequestBus::Handler::BusDisconnect();
  261. Render::Bootstrap::DefaultWindowBus::Handler::BusDisconnect();
  262. AzFramework::WindowSystemRequestBus::Handler::BusDisconnect();
  263. AzFramework::WindowSystemNotificationBus::Handler::BusDisconnect();
  264. TickBus::Handler::BusDisconnect();
  265. m_brdfTexture = nullptr;
  266. RemoveRenderPipeline();
  267. DestroyDefaultScene();
  268. m_viewportContext.reset();
  269. m_nativeWindow = nullptr;
  270. m_windowHandle = nullptr;
  271. }
  272. void BootstrapSystemComponent::Initialize()
  273. {
  274. if (m_isInitialized)
  275. {
  276. return;
  277. }
  278. m_isInitialized = true;
  279. if (!RPI::RPISystemInterface::Get()->IsInitialized())
  280. {
  281. AZ::OSString msgBoxMessage;
  282. msgBoxMessage.append("RPI System could not initialize correctly. Check log for detail.");
  283. AZ::NativeUI::NativeUIRequestBus::Broadcast(
  284. &AZ::NativeUI::NativeUIRequestBus::Events::DisplayOkDialog, "O3DE Fatal Error", msgBoxMessage.c_str(), false);
  285. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  286. return;
  287. }
  288. // In the case of the game we want to call create and register the scene as a soon as we can
  289. // because a level could be loaded in autoexec.cfg and that will assert if there is no scene registered
  290. // to get the feature processors for the components. So we can't wait until the tick (whereas the Editor wants to wait)
  291. if (m_createDefaultScene)
  292. {
  293. CreateDefaultScene();
  294. }
  295. if (m_windowHandle)
  296. {
  297. CreateViewportContext();
  298. if (m_createDefaultScene)
  299. {
  300. CreateDefaultRenderPipeline();
  301. }
  302. }
  303. }
  304. void BootstrapSystemComponent::OnWindowCreated(AzFramework::NativeWindowHandle windowHandle)
  305. {
  306. // only handle the first window (default) created
  307. if (m_windowHandle == nullptr)
  308. {
  309. m_windowHandle = windowHandle;
  310. if (m_isInitialized)
  311. {
  312. CreateViewportContext();
  313. if (m_createDefaultScene)
  314. {
  315. CreateDefaultRenderPipeline();
  316. }
  317. }
  318. }
  319. }
  320. void BootstrapSystemComponent::OnApplicationWindowCreated()
  321. {
  322. if (!m_nativeWindow)
  323. {
  324. auto projectTitle = AZ::Utils::GetProjectDisplayName();
  325. m_nativeWindow = AZStd::make_unique<AzFramework::NativeWindow>(projectTitle.c_str(), AzFramework::WindowGeometry(0, 0, r_width, r_height));
  326. AZ_Assert(m_nativeWindow, "Failed to create the game window\n");
  327. m_nativeWindow->Activate();
  328. OnWindowCreated(m_nativeWindow->GetWindowHandle());
  329. }
  330. }
  331. void BootstrapSystemComponent::OnApplicationWindowDestroy()
  332. {
  333. m_nativeWindow = nullptr;
  334. }
  335. void BootstrapSystemComponent::CreateViewportContext()
  336. {
  337. RHI::Device* device = RHI::RHISystemInterface::Get()->GetDevice();
  338. RPI::ViewportContextRequestsInterface::CreationParameters params;
  339. params.device = device;
  340. params.windowHandle = m_windowHandle;
  341. params.renderScene = m_defaultScene;
  342. // Setting the default ViewportContextID to an arbitrary and otherwise invalid (negative) value to ensure its uniqueness
  343. params.id = -10;
  344. auto viewContextManager = AZ::Interface<RPI::ViewportContextRequestsInterface>::Get();
  345. m_viewportContext = viewContextManager->CreateViewportContext(
  346. viewContextManager->GetDefaultViewportContextName(), params);
  347. DefaultWindowNotificationBus::Broadcast(&DefaultWindowNotificationBus::Events::DefaultWindowCreated);
  348. // Listen to window notification so we can request exit application when window closes
  349. AzFramework::WindowNotificationBus::Handler::BusConnect(GetDefaultWindowHandle());
  350. }
  351. AZ::RPI::ScenePtr BootstrapSystemComponent::GetOrCreateAtomSceneFromAzScene(AzFramework::Scene* scene)
  352. {
  353. // Get or create a weak pointer to our scene
  354. // If it's valid, we're done, if not we need to create an Atom scene and update our scene map
  355. auto& atomSceneHandle = m_azSceneToAtomSceneMap[scene];
  356. if (!atomSceneHandle.expired())
  357. {
  358. return atomSceneHandle.lock();
  359. }
  360. // Create and register a scene with all available feature processors
  361. RPI::SceneDescriptor sceneDesc;
  362. sceneDesc.m_nameId = AZ::Name("Main");
  363. AZ::RPI::ScenePtr atomScene = RPI::Scene::CreateScene(sceneDesc);
  364. atomScene->EnableAllFeatureProcessors();
  365. atomScene->Activate();
  366. // Register scene to RPI system so it will be processed/rendered per tick
  367. RPI::RPISystemInterface::Get()->RegisterScene(atomScene);
  368. scene->SetSubsystem(atomScene);
  369. atomSceneHandle = atomScene;
  370. return atomScene;
  371. }
  372. void BootstrapSystemComponent::CreateDefaultScene()
  373. {
  374. // Bind atomScene to the GameEntityContext's AzFramework::Scene
  375. m_defaultFrameworkScene = AzFramework::SceneSystemInterface::Get()->GetScene(AzFramework::Scene::MainSceneName);
  376. // This should never happen unless scene creation has changed.
  377. AZ_Assert(m_defaultFrameworkScene, "Error: Scenes missing during system component initialization");
  378. m_sceneRemovalHandler = AzFramework::Scene::RemovalEvent::Handler(
  379. [this](AzFramework::Scene&, AzFramework::Scene::RemovalEventType eventType)
  380. {
  381. if (eventType == AzFramework::Scene::RemovalEventType::Zombified)
  382. {
  383. m_defaultFrameworkScene.reset();
  384. }
  385. });
  386. m_defaultFrameworkScene->ConnectToEvents(m_sceneRemovalHandler);
  387. m_defaultScene = GetOrCreateAtomSceneFromAzScene(m_defaultFrameworkScene.get());
  388. }
  389. bool BootstrapSystemComponent::EnsureDefaultRenderPipelineInstalledForScene(AZ::RPI::ScenePtr scene, AZ::RPI::ViewportContextPtr viewportContext)
  390. {
  391. AZ::RPI::XRRenderingInterface* xrSystem = AZ::RPI::RPISystemInterface::Get()->GetXRSystem();
  392. const bool loadDefaultRenderPipeline = !xrSystem || xrSystem->GetRHIXRRenderingInterface()->IsDefaultRenderPipelineNeeded();
  393. AZ::RHI::MultisampleState multisampleState;
  394. // Load the main default pipeline if applicable
  395. if (loadDefaultRenderPipeline)
  396. {
  397. AZ::CVarFixedString pipelineName = static_cast<AZ::CVarFixedString>(r_renderPipelinePath);
  398. if (xrSystem)
  399. {
  400. // When running launcher on PC having an XR system present then the default render pipeline is suppose to reflect
  401. // what's being rendered into XR device. XR render pipeline uses multiview render pipeline.
  402. AZ::ApplicationTypeQuery appType;
  403. ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  404. if (appType.IsGame())
  405. {
  406. pipelineName = r_default_openxr_pipeline_name;
  407. }
  408. }
  409. if (!LoadPipeline(scene, viewportContext, pipelineName, AZ::RPI::ViewType::Default, multisampleState))
  410. {
  411. return false;
  412. }
  413. // As part of our initialization we need to create the BRDF texture generation pipeline
  414. AZ::RPI::RenderPipelineDescriptor pipelineDesc;
  415. pipelineDesc.m_mainViewTagName = "MainCamera";
  416. pipelineDesc.m_name = AZStd::string::format("BRDFTexturePipeline_%i", viewportContext->GetId());
  417. pipelineDesc.m_rootPassTemplate = "BRDFTexturePipeline";
  418. pipelineDesc.m_executeOnce = true;
  419. // Save a reference to the generated BRDF texture so it doesn't get deleted if all the passes refering to it get deleted
  420. // and it's ref count goes to zero
  421. if (!m_brdfTexture)
  422. {
  423. const AZStd::shared_ptr<const RPI::PassTemplate> brdfTextureTemplate =
  424. RPI::PassSystemInterface::Get()->GetPassTemplate(Name("BRDFTextureTemplate"));
  425. Data::Asset<RPI::AttachmentImageAsset> brdfImageAsset = RPI::AssetUtils::LoadAssetById<RPI::AttachmentImageAsset>(
  426. brdfTextureTemplate->m_imageAttachments[0].m_assetRef.m_assetId, RPI::AssetUtils::TraceLevel::Error);
  427. if (brdfImageAsset.IsReady())
  428. {
  429. m_brdfTexture = RPI::AttachmentImage::FindOrCreate(brdfImageAsset);
  430. }
  431. }
  432. if (!scene->GetRenderPipeline(AZ::Name(pipelineDesc.m_name)))
  433. {
  434. RPI::RenderPipelinePtr brdfTexturePipeline = AZ::RPI::RenderPipeline::CreateRenderPipeline(pipelineDesc);
  435. scene->AddRenderPipeline(brdfTexturePipeline);
  436. }
  437. }
  438. // Load XR pipelines if applicable
  439. if (xrSystem)
  440. {
  441. for (AZ::u32 i = 0; i < xrSystem->GetNumViews(); i++)
  442. {
  443. const AZ::RPI::ViewType viewType = (i == 0)
  444. ? AZ::RPI::ViewType::XrLeft
  445. : AZ::RPI::ViewType::XrRight;
  446. const AZStd::string_view xrPipelineAssetName = (viewType == AZ::RPI::ViewType::XrLeft)
  447. ? static_cast<AZ::CVarFixedString>(r_default_openxr_left_pipeline_name)
  448. : static_cast<AZ::CVarFixedString>(r_default_openxr_right_pipeline_name);
  449. if (!LoadPipeline(scene, viewportContext, xrPipelineAssetName, viewType, multisampleState))
  450. {
  451. return false;
  452. }
  453. }
  454. }
  455. // Apply MSAA state to all the render pipelines.
  456. // It's important to do this after all the pipelines have
  457. // been created so the same values are applied to all.
  458. // As it cannot be applied MSAA values per pipeline,
  459. // it's setting the MSAA state from the last pipeline loaded.
  460. AZ::RPI::RPISystemInterface::Get()->SetApplicationMultisampleState(multisampleState);
  461. // Send notification when the scene and its pipeline are ready.
  462. // Use the first created pipeline's scene as our default scene for now to allow
  463. // consumers waiting on scene availability to initialize.
  464. if (!m_defaultSceneReady)
  465. {
  466. m_defaultScene = scene;
  467. Render::Bootstrap::NotificationBus::Broadcast(
  468. &Render::Bootstrap::NotificationBus::Handler::OnBootstrapSceneReady, m_defaultScene.get());
  469. m_defaultSceneReady = true;
  470. }
  471. return true;
  472. }
  473. void BootstrapSystemComponent::SwitchRenderPipeline(const AZ::RPI::RenderPipelineDescriptor& newRenderPipelineDesc, AZ::RPI::ViewportContextPtr viewportContext)
  474. {
  475. AZ::RPI::RenderPipelineDescriptor pipelineDescriptor = newRenderPipelineDesc;
  476. pipelineDescriptor.m_name =
  477. AZStd::string::format("%s_%i", pipelineDescriptor.m_name.c_str(), viewportContext->GetId());
  478. if (pipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositionsCount &&
  479. !RHI::RHISystemInterface::Get()->GetDevice()->GetFeatures().m_customSamplePositions)
  480. {
  481. // Disable custom sample positions because they are not supported
  482. AZ_Warning(
  483. "BootstrapSystemComponent",
  484. false,
  485. "Disabling custom sample positions for pipeline %s because they are not supported on this device",
  486. pipelineDescriptor.m_name.c_str());
  487. pipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositions = {};
  488. pipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositionsCount = 0;
  489. }
  490. // Create new render pipeline
  491. auto oldRenderPipeline = viewportContext->GetRenderScene()->GetDefaultRenderPipeline();
  492. RPI::RenderPipelinePtr newRenderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(
  493. pipelineDescriptor, *viewportContext->GetWindowContext().get(), AZ::RPI::ViewType::Default);
  494. // Switch render pipeline
  495. viewportContext->GetRenderScene()->RemoveRenderPipeline(oldRenderPipeline->GetId());
  496. viewportContext->GetRenderScene()->AddRenderPipeline(newRenderPipeline);
  497. newRenderPipeline->SetDefaultView(oldRenderPipeline->GetDefaultView());
  498. AZ::RPI::RPISystemInterface::Get()->SetApplicationMultisampleState(newRenderPipeline->GetRenderSettings().m_multisampleState);
  499. }
  500. RPI::RenderPipelinePtr BootstrapSystemComponent::LoadPipeline( AZ::RPI::ScenePtr scene, AZ::RPI::ViewportContextPtr viewportContext,
  501. AZStd::string_view pipelineName, AZ::RPI::ViewType viewType, AZ::RHI::MultisampleState& multisampleState)
  502. {
  503. // Create a render pipeline from the specified asset for the window context and add the pipeline to the scene.
  504. // When running with an Asset Processor, this will attempt to compile the asset before loading it.
  505. Data::Asset<RPI::AnyAsset> pipelineAsset =
  506. RPI::AssetUtils::LoadCriticalAsset<RPI::AnyAsset>(pipelineName.data(), RPI::AssetUtils::TraceLevel::Error);
  507. if (pipelineAsset)
  508. {
  509. RPI::RenderPipelineDescriptor renderPipelineDescriptor =
  510. *RPI::GetDataFromAnyAsset<RPI::RenderPipelineDescriptor>(pipelineAsset); // Copy descriptor from asset
  511. pipelineAsset.Release();
  512. renderPipelineDescriptor.m_name =
  513. AZStd::string::format("%s_%i", renderPipelineDescriptor.m_name.c_str(), viewportContext->GetId());
  514. if (renderPipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositionsCount &&
  515. !RHI::RHISystemInterface::Get()->GetDevice()->GetFeatures().m_customSamplePositions)
  516. {
  517. // Disable custom sample positions because they are not supported
  518. AZ_Warning(
  519. "BootstrapSystemComponent",
  520. false,
  521. "Disabling custom sample positions for pipeline %s because they are not supported on this device",
  522. pipelineName.data());
  523. renderPipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositions = {};
  524. renderPipelineDescriptor.m_renderSettings.m_multisampleState.m_customPositionsCount = 0;
  525. }
  526. multisampleState = renderPipelineDescriptor.m_renderSettings.m_multisampleState;
  527. // Create and add render pipeline to the scene (when not added already)
  528. RPI::RenderPipelinePtr renderPipeline = scene->GetRenderPipeline(AZ::Name(renderPipelineDescriptor.m_name));
  529. if (!renderPipeline)
  530. {
  531. renderPipeline = RPI::RenderPipeline::CreateRenderPipelineForWindow(
  532. renderPipelineDescriptor, *viewportContext->GetWindowContext().get(), viewType);
  533. scene->AddRenderPipeline(renderPipeline);
  534. }
  535. return renderPipeline;
  536. }
  537. else
  538. {
  539. AZ_Error("AtomBootstrap", false, "Pipeline file failed to load from path: %s.", pipelineName.data());
  540. return nullptr;
  541. }
  542. }
  543. void BootstrapSystemComponent::CreateDefaultRenderPipeline()
  544. {
  545. EnsureDefaultRenderPipelineInstalledForScene(m_defaultScene, m_viewportContext);
  546. const auto pipeline = m_defaultScene->FindRenderPipelineForWindow(m_viewportContext->GetWindowHandle());
  547. if (pipeline)
  548. {
  549. m_renderPipelineId = pipeline->GetId();
  550. }
  551. }
  552. void BootstrapSystemComponent::DestroyDefaultScene()
  553. {
  554. if (m_defaultScene)
  555. {
  556. RPI::RPISystemInterface::Get()->UnregisterScene(m_defaultScene);
  557. // Unbind m_defaultScene to the GameEntityContext's AzFramework::Scene
  558. if (m_defaultFrameworkScene)
  559. {
  560. m_defaultFrameworkScene->UnsetSubsystem(m_defaultScene);
  561. }
  562. m_defaultScene = nullptr;
  563. m_defaultFrameworkScene = nullptr;
  564. }
  565. }
  566. void BootstrapSystemComponent::RemoveRenderPipeline()
  567. {
  568. if (m_defaultScene && m_defaultScene->GetRenderPipeline(m_renderPipelineId))
  569. {
  570. m_defaultScene->RemoveRenderPipeline(m_renderPipelineId);
  571. }
  572. m_renderPipelineId = "";
  573. }
  574. void BootstrapSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time)
  575. {
  576. // Temp: When running in the launcher without the legacy renderer
  577. // we need to call RenderTick on the viewport context each frame.
  578. if (m_viewportContext)
  579. {
  580. AZ::ApplicationTypeQuery appType;
  581. ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType);
  582. if (appType.IsGame())
  583. {
  584. m_viewportContext->RenderTick();
  585. }
  586. }
  587. }
  588. int BootstrapSystemComponent::GetTickOrder()
  589. {
  590. return TICK_LAST;
  591. }
  592. void BootstrapSystemComponent::OnWindowClosed()
  593. {
  594. m_windowHandle = nullptr;
  595. m_viewportContext.reset();
  596. // On some platforms (e.g. Android) the main window is destroyed when the app is suspended
  597. // but this doesn't mean that we need to exit the app. The window will be recreated when the app
  598. // is resumed.
  599. #if AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_EXIT_ON_WINDOW_CLOSE
  600. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  601. #endif
  602. AzFramework::WindowNotificationBus::Handler::BusDisconnect();
  603. }
  604. AzFramework::NativeWindowHandle BootstrapSystemComponent::GetDefaultWindowHandle()
  605. {
  606. return m_windowHandle;
  607. }
  608. AZStd::shared_ptr<RPI::WindowContext> BootstrapSystemComponent::GetDefaultWindowContext()
  609. {
  610. return m_viewportContext ? m_viewportContext->GetWindowContext() : nullptr;
  611. }
  612. void BootstrapSystemComponent::SetCreateDefaultScene(bool create)
  613. {
  614. m_createDefaultScene = create;
  615. }
  616. } // namespace Bootstrap
  617. } // namespace Render
  618. } // namespace AZ