RPISystem.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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 <Atom/RPI.Public/RPISystem.h>
  9. #include <Atom/RPI.Public/RPIUtils.h>
  10. #include <Atom/RPI.Reflect/Asset/AssetReference.h>
  11. #include <Atom/RPI.Reflect/Asset/AssetHandler.h>
  12. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  13. #include <Atom/RPI.Reflect/ResourcePoolAsset.h>
  14. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  15. #include <Atom/RPI.Reflect/System/AnyAsset.h>
  16. #include <Atom/RPI.Reflect/System/AssetAliases.h>
  17. #include <Atom/RPI.Reflect/System/PipelineRenderSettings.h>
  18. #include <Atom/RPI.Reflect/System/RenderPipelineDescriptor.h>
  19. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  20. #include <Atom/RPI.Public/AssetInitBus.h>
  21. #include <Atom/RPI.Public/FeatureProcessor.h>
  22. #include <Atom/RPI.Public/GpuQuery/GpuQueryTypes.h>
  23. #include <Atom/RPI.Public/Scene.h>
  24. #include <Atom/RPI.Public/RenderPipeline.h>
  25. #include <Atom/RPI.Public/View.h>
  26. #include <Atom/RPI.Public/Pass/PassFactory.h>
  27. #include <Atom/RHI/Factory.h>
  28. #include <Atom/RHI/Device.h>
  29. #include <Atom/RHI.Reflect/PlatformLimitsDescriptor.h>
  30. #include <Atom/RHI/RHIUtils.h>
  31. #include <Atom/RHI/XRRenderingInterface.h>
  32. #include <AzCore/Interface/Interface.h>
  33. #include <AzCore/Time/ITime.h>
  34. #include <AzFramework/Asset/AssetSystemBus.h>
  35. AZ_DEFINE_BUDGET(AzRender);
  36. AZ_DEFINE_BUDGET(RPI);
  37. // This will cause the RPI System to print out global state (like the current pass hierarchy) when an assert is hit
  38. // This is useful for rendering engineers debugging a crash in the RPI/RHI layers
  39. #define AZ_RPI_PRINT_GLOBAL_STATE_ON_ASSERT 0
  40. namespace AZ
  41. {
  42. namespace RPI
  43. {
  44. RPISystemInterface* RPISystemInterface::Get()
  45. {
  46. return Interface<RPISystemInterface>::Get();
  47. }
  48. void RPISystem::Reflect(ReflectContext* context)
  49. {
  50. AssetReference::Reflect(context);
  51. BufferSystem::Reflect(context);
  52. ImageSystem::Reflect(context);
  53. MaterialSystem::Reflect(context);
  54. ModelSystem::Reflect(context);
  55. ShaderSystem::Reflect(context);
  56. PassSystem::Reflect(context);
  57. ResourcePoolAsset::Reflect(context);
  58. SceneDescriptor::Reflect(context);
  59. PipelineRenderSettings::Reflect(context);
  60. RenderPipelineDescriptor::Reflect(context);
  61. AssetAliases::Reflect(context);
  62. RPISystemDescriptor::Reflect(context);
  63. GpuQuerySystemDescriptor::Reflect(context);
  64. PipelineStatisticsResult::Reflect(context);
  65. }
  66. void RPISystem::Initialize(const RPISystemDescriptor& rpiSystemDescriptor)
  67. {
  68. // Init RHI device(s)
  69. auto commandLineMultipleDevicesValue{ RHI::GetCommandLineValue("device-count") };
  70. m_rhiSystem.InitDevices((commandLineMultipleDevicesValue != "") ? AZStd::stoi(commandLineMultipleDevicesValue) : 1);
  71. // Gather asset handlers from sub-systems.
  72. ImageSystem::GetAssetHandlers(m_assetHandlers);
  73. BufferSystem::GetAssetHandlers(m_assetHandlers);
  74. MaterialSystem::GetAssetHandlers(m_assetHandlers);
  75. ModelSystem::GetAssetHandlers(m_assetHandlers);
  76. PassSystem::GetAssetHandlers(m_assetHandlers);
  77. ShaderSystem::GetAssetHandlers(m_assetHandlers);
  78. m_assetHandlers.emplace_back(MakeAssetHandler<ResourcePoolAssetHandler>());
  79. m_assetHandlers.emplace_back(MakeAssetHandler<AnyAssetHandler>());
  80. m_materialSystem.Init();
  81. m_modelSystem.Init();
  82. m_shaderSystem.Init();
  83. m_passSystem.Init();
  84. m_featureProcessorFactory.Init();
  85. m_querySystem.Init(m_descriptor.m_gpuQuerySystemDescriptor);
  86. Interface<RPISystemInterface>::Register(this);
  87. SystemTickBus::Handler::BusConnect();
  88. #if AZ_RPI_PRINT_GLOBAL_STATE_ON_ASSERT
  89. Debug::TraceMessageBus::Handler::BusConnect();
  90. #endif
  91. m_descriptor = rpiSystemDescriptor;
  92. }
  93. void RPISystem::Shutdown()
  94. {
  95. m_viewportContextManager.Shutdown();
  96. m_viewSrgLayout = nullptr;
  97. m_sceneSrgLayout = nullptr;
  98. m_commonShaderAssetForSrgs.Reset();
  99. #if AZ_RPI_PRINT_GLOBAL_STATE_ON_ASSERT
  100. Debug::TraceMessageBus::Handler::BusDisconnect();
  101. #endif
  102. SystemTickBus::Handler::BusDisconnect();
  103. Interface<RPISystemInterface>::Unregister(this);
  104. m_featureProcessorFactory.Shutdown();
  105. m_passSystem.Shutdown();
  106. m_dynamicDraw.Shutdown();
  107. m_bufferSystem.Shutdown();
  108. m_materialSystem.Shutdown();
  109. m_modelSystem.Shutdown();
  110. m_shaderSystem.Shutdown();
  111. m_imageSystem.Shutdown();
  112. m_querySystem.Shutdown();
  113. m_rhiSystem.Shutdown();
  114. /**
  115. * [LY-86745] We need to pump the asset manager queue here, because
  116. * it uses AZStd::function<> with vtable pointers embedded from this DLL.
  117. * If we allow the DLL to shutdown with queued events, they will be pumped
  118. * later by the asset manager component, which will then reference garbage
  119. * vtable pointers.
  120. *
  121. * Note that it's necessary to pump before *and* after we clear the handlers,
  122. * since the handler clear could result in more events dispatched.
  123. */
  124. Data::AssetManager::Instance().DispatchEvents();
  125. m_assetHandlers.clear();
  126. Data::AssetManager::Instance().DispatchEvents();
  127. }
  128. void RPISystem::RegisterScene(ScenePtr scene)
  129. {
  130. for (auto& sceneItem : m_scenes)
  131. {
  132. if (sceneItem == scene)
  133. {
  134. AZ_Assert(false, "Scene was already registered");
  135. return;
  136. }
  137. else if (!scene->GetName().IsEmpty() && scene->GetName() == sceneItem->GetName())
  138. {
  139. // only report a warning if there is a scene with duplicated name
  140. AZ_Warning("RPISystem", false, "There is a registered scene with same name [%s]", scene->GetName().GetCStr());
  141. }
  142. }
  143. m_scenes.push_back(scene);
  144. }
  145. void RPISystem::UnregisterScene(ScenePtr scene)
  146. {
  147. for (auto itr = m_scenes.begin(); itr != m_scenes.end(); itr++)
  148. {
  149. if (*itr == scene)
  150. {
  151. m_scenes.erase(itr);
  152. return;
  153. }
  154. }
  155. AZ_Assert(false, "Can't unregister scene which wasn't registered");
  156. }
  157. Scene* RPISystem::GetScene(const SceneId& sceneId) const
  158. {
  159. for (const auto& scene : m_scenes)
  160. {
  161. if (scene->GetId() == sceneId)
  162. {
  163. return scene.get();
  164. }
  165. }
  166. return nullptr;
  167. }
  168. Scene* RPISystem::GetSceneByName(const AZ::Name& name) const
  169. {
  170. for (const auto& scene : m_scenes)
  171. {
  172. if (scene->GetName() == name)
  173. {
  174. return scene.get();
  175. }
  176. }
  177. return nullptr;
  178. }
  179. uint32_t RPISystem::GetNumScenes() const
  180. {
  181. return aznumeric_cast<uint32_t>(m_scenes.size());
  182. }
  183. ScenePtr RPISystem::GetDefaultScene() const
  184. {
  185. for (const auto& scene : m_scenes)
  186. {
  187. if (scene->GetName() == AZ::Name("Main"))
  188. {
  189. return scene;
  190. }
  191. }
  192. return nullptr;
  193. }
  194. RenderPipelinePtr RPISystem::GetRenderPipelineForWindow(AzFramework::NativeWindowHandle windowHandle)
  195. {
  196. RenderPipelinePtr renderPipeline;
  197. for (auto& scene : m_scenes)
  198. {
  199. renderPipeline = scene->FindRenderPipelineForWindow(windowHandle);
  200. if (renderPipeline)
  201. {
  202. return renderPipeline;
  203. }
  204. }
  205. return nullptr;
  206. }
  207. Data::Asset<ShaderAsset> RPISystem::GetCommonShaderAssetForSrgs() const
  208. {
  209. AZ_Assert(m_systemAssetsInitialized, "InitializeSystemAssets() should be called once when asset catalog loaded'");
  210. return m_commonShaderAssetForSrgs;
  211. }
  212. RHI::Ptr<RHI::ShaderResourceGroupLayout> RPISystem::GetSceneSrgLayout() const
  213. {
  214. AZ_Assert(m_systemAssetsInitialized, "InitializeSystemAssets() should be called once when asset catalog loaded'");
  215. return m_sceneSrgLayout;
  216. }
  217. RHI::Ptr<RHI::ShaderResourceGroupLayout> RPISystem::GetViewSrgLayout() const
  218. {
  219. AZ_Assert(m_systemAssetsInitialized, "InitializeSystemAssets() should be called once when asset catalog loaded'");
  220. return m_viewSrgLayout;
  221. }
  222. void RPISystem::OnSystemTick()
  223. {
  224. AZ_PROFILE_SCOPE(RPI, "RPISystem: OnSystemTick");
  225. // Image system update is using system tick but not game tick so it can stream images in background even game is pausing
  226. m_imageSystem.Update();
  227. }
  228. void RPISystem::SimulationTick()
  229. {
  230. if (!m_systemAssetsInitialized || IsNullRenderer())
  231. {
  232. return;
  233. }
  234. AZ_PROFILE_SCOPE(RPI, "RPISystem: SimulationTick");
  235. AssetInitBus::Broadcast(&AssetInitBus::Events::PostLoadInit);
  236. m_currentSimulationTime = GetCurrentTime();
  237. for (auto& scene : m_scenes)
  238. {
  239. scene->Simulate(m_simulationJobPolicy, m_currentSimulationTime);
  240. }
  241. }
  242. float RPISystem::GetCurrentTime() const
  243. {
  244. const AZ::TimeUs currentSimulationTimeUs = AZ::GetRealElapsedTimeUs();
  245. return AZ::TimeUsToSeconds(currentSimulationTimeUs);
  246. }
  247. void RPISystem::InitXRSystem()
  248. {
  249. // The creation of an XR Session requires an asset that defines
  250. // the action bindings for the application. This means the asset catalog
  251. // must be available before creating the XR Session.
  252. AZ_Assert(m_systemAssetsInitialized, "IntXRSystem should not be called before the asset system is ready.");
  253. if (!m_xrSystem)
  254. {
  255. return;
  256. }
  257. auto xrRender = m_xrSystem->GetRHIXRRenderingInterface();
  258. if (!xrRender)
  259. {
  260. return;
  261. }
  262. RHI::Ptr<RHI::XRDeviceDescriptor> xrDescriptor = m_rhiSystem.GetDevice()->BuildXRDescriptor();
  263. [[maybe_unused]] auto result = xrRender->CreateDevice(xrDescriptor.get());
  264. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR device");
  265. AZ::RHI::XRSessionDescriptor sessionDescriptor;
  266. result = xrRender->CreateSession(&sessionDescriptor);
  267. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR session");
  268. result = xrRender->CreateSwapChain();
  269. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR swapchain");
  270. }
  271. void RPISystem::RenderTick()
  272. {
  273. if (!m_systemAssetsInitialized || IsNullRenderer())
  274. {
  275. m_dynamicDraw.FrameEnd();
  276. return;
  277. }
  278. AZ_PROFILE_SCOPE(RPI, "RPISystem: RenderTick");
  279. // Query system update is to increment the frame count
  280. m_querySystem.Update();
  281. // Collect draw packets for each scene and prepare RPI system SRGs
  282. // [GFX TODO] We may parallel scenes' prepare render.
  283. for (auto& scenePtr : m_scenes)
  284. {
  285. scenePtr->PrepareRender(m_prepareRenderJobPolicy, m_currentSimulationTime);
  286. }
  287. //Collect all the active pipelines running in this frame.
  288. uint16_t numActiveRenderPipelines = 0;
  289. for (auto& scenePtr : m_scenes)
  290. {
  291. numActiveRenderPipelines += scenePtr->GetActiveRenderPipelines();
  292. }
  293. m_rhiSystem.SetNumActiveRenderPipelines(numActiveRenderPipelines);
  294. m_rhiSystem.FrameUpdate(
  295. [this](RHI::FrameGraphBuilder& frameGraphBuilder)
  296. {
  297. // Pass system's frame update, which includes the logic of adding scope producers, has to be added here since the
  298. // scope producers only can be added to the frame when frame started which cleans up previous scope producers.
  299. m_passSystem.FrameUpdate(frameGraphBuilder);
  300. // Update Scene and View Srgs
  301. for (auto& scenePtr : m_scenes)
  302. {
  303. scenePtr->UpdateSrgs();
  304. }
  305. });
  306. {
  307. AZ_PROFILE_SCOPE(RPI, "RPISystem: FrameEnd");
  308. m_dynamicDraw.FrameEnd();
  309. m_passSystem.FrameEnd();
  310. for (auto& scenePtr : m_scenes)
  311. {
  312. scenePtr->OnFrameEnd();
  313. }
  314. }
  315. m_renderTick++;
  316. }
  317. void RPISystem::SetSimulationJobPolicy(RHI::JobPolicy jobPolicy)
  318. {
  319. m_simulationJobPolicy = jobPolicy;
  320. }
  321. RHI::JobPolicy RPISystem::GetSimulationJobPolicy() const
  322. {
  323. return m_simulationJobPolicy;
  324. }
  325. void RPISystem::SetRenderPrepareJobPolicy(RHI::JobPolicy jobPolicy)
  326. {
  327. m_prepareRenderJobPolicy = jobPolicy;
  328. }
  329. RHI::JobPolicy RPISystem::GetRenderPrepareJobPolicy() const
  330. {
  331. return m_prepareRenderJobPolicy;
  332. }
  333. const RPISystemDescriptor& RPISystem::GetDescriptor() const
  334. {
  335. return m_descriptor;
  336. }
  337. Name RPISystem::GetRenderApiName() const
  338. {
  339. return RHI::Factory::Get().GetName();
  340. }
  341. void RPISystem::InitializeSystemAssets()
  342. {
  343. if (m_systemAssetsInitialized)
  344. {
  345. return;
  346. }
  347. m_commonShaderAssetForSrgs = AssetUtils::LoadCriticalAsset<ShaderAsset>( m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  348. if (!m_commonShaderAssetForSrgs.IsReady())
  349. {
  350. AZ_Error("RPI system", false, "Failed to load RPI system asset %s", m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  351. return;
  352. }
  353. m_sceneSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::Scene);
  354. if (!m_sceneSrgLayout)
  355. {
  356. AZ_Error("RPISystem", false, "Failed to find SceneSrg by slot=<%u> from shader asset at path <%s>", SrgBindingSlot::Scene,
  357. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  358. return;
  359. }
  360. m_viewSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::View);
  361. if (!m_viewSrgLayout)
  362. {
  363. AZ_Error("RPISystem", false, "Failed to find ViewSrg by slot=<%u> from shader asset at path <%s>", SrgBindingSlot::View,
  364. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  365. return;
  366. }
  367. RHI::Ptr<RHI::ShaderResourceGroupLayout> bindlessSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::Bindless);
  368. if (!bindlessSrgLayout)
  369. {
  370. AZ_Error(
  371. "RPISystem",
  372. false,
  373. "Failed to find BindlessSrg by slot=<%u> from shader asset at path <%s>",
  374. SrgBindingSlot::Bindless,
  375. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  376. return;
  377. }
  378. m_rhiSystem.Init(bindlessSrgLayout);
  379. m_imageSystem.Init(m_descriptor.m_imageSystemDescriptor);
  380. m_bufferSystem.Init();
  381. m_dynamicDraw.Init(m_descriptor.m_dynamicDrawSystemDescriptor);
  382. m_passSystem.InitPassTemplates();
  383. m_systemAssetsInitialized = true;
  384. AZ_TracePrintf("RPI system", "System assets initialized\n");
  385. // Now that the asset system is up and running, we can safely initialize
  386. // the XR System and the XR Session.
  387. InitXRSystem();
  388. }
  389. bool RPISystem::IsInitialized() const
  390. {
  391. return m_systemAssetsInitialized;
  392. }
  393. bool RPISystem::IsNullRenderer() const
  394. {
  395. return m_descriptor.m_isNullRenderer;
  396. }
  397. void RPISystem::InitializeSystemAssetsForTests()
  398. {
  399. if (m_systemAssetsInitialized)
  400. {
  401. AZ_Warning("RPISystem", false, "InitializeSystemAssets should only be called once'");
  402. return;
  403. }
  404. //Init rhi/image/buffer systems to match InitializeSystemAssets
  405. m_rhiSystem.Init();
  406. m_imageSystem.Init(m_descriptor.m_imageSystemDescriptor);
  407. m_bufferSystem.Init();
  408. // Assets aren't actually available or needed for tests, but the m_systemAssetsInitialized flag still needs to be flipped.
  409. m_systemAssetsInitialized = true;
  410. return;
  411. }
  412. bool RPISystem::OnPreAssert([[maybe_unused]] const char* fileName, [[maybe_unused]] int line, [[maybe_unused]] const char* func, [[maybe_unused]] const char* message)
  413. {
  414. #if AZ_RPI_PRINT_GLOBAL_STATE_ON_ASSERT
  415. AZ_Printf("RPI System", "\n--- Assert hit! Dumping RPI state ---\n\n");
  416. m_passSystem.DebugPrintPassHierarchy();
  417. #endif
  418. return false;
  419. }
  420. uint64_t RPISystem::GetCurrentTick() const
  421. {
  422. return m_renderTick;
  423. }
  424. void RPISystem::SetApplicationMultisampleState(const RHI::MultisampleState& multisampleState)
  425. {
  426. m_multisampleState = multisampleState;
  427. bool isNonMsaaPipeline = (m_multisampleState.m_samples == 1);
  428. const char* supervariantName = isNonMsaaPipeline ? AZ::RPI::NoMsaaSupervariantName : "";
  429. AZ::RPI::ShaderSystemInterface::Get()->SetSupervariantName(AZ::Name(supervariantName));
  430. // reinitialize pipelines for all scenes
  431. for (auto& scene : m_scenes)
  432. {
  433. for (auto& renderPipeline : scene->GetRenderPipelines())
  434. {
  435. // MSAA state set to the render pipeline at creation time from its data might be different
  436. // from the one set to the application. So it can arrive here having the same new
  437. // target state, but still needs to be marked as its MSAA state has changed so its passes
  438. // are recreated using the new supervariant name coming from MSAA at application level just set above.
  439. // In conclusion, it's not safe to skip here setting MSAA state to the render pipeline when it's the
  440. // same as the target.
  441. renderPipeline->GetRenderSettings().m_multisampleState = multisampleState;
  442. renderPipeline->MarkPipelinePassChanges(PipelinePassChanges::MultisampleStateChanged);
  443. }
  444. }
  445. }
  446. const RHI::MultisampleState& RPISystem::GetApplicationMultisampleState() const
  447. {
  448. return m_multisampleState;
  449. }
  450. void RPISystem::RegisterXRSystem(XRRenderingInterface* xrSystemInterface)
  451. {
  452. AZ_Assert(!m_xrSystem, "XR System is already registered");
  453. if (m_rhiSystem.RegisterXRSystem(xrSystemInterface->GetRHIXRRenderingInterface()))
  454. {
  455. m_xrSystem = xrSystemInterface;
  456. }
  457. }
  458. void RPISystem::UnregisterXRSystem()
  459. {
  460. AZ_Assert(m_xrSystem, "XR System is not registered");
  461. if (m_xrSystem)
  462. {
  463. m_rhiSystem.UnregisterXRSystem();
  464. m_xrSystem = nullptr;
  465. }
  466. }
  467. XRRenderingInterface* RPISystem::GetXRSystem() const
  468. {
  469. return m_xrSystem;
  470. }
  471. } //namespace RPI
  472. } //namespace AZ