BootstrapSystemComponent.cpp 37 KB

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