3
0

RPISystem.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. m_rhiSystem.InitDevices(AzFramework::StringFunc::Equal(RHI::GetCommandLineValue("enableMultipleDevices").c_str(), "enable") ? RHI::InitDevicesFlags::MultiDevice : RHI::InitDevicesFlags::SingleDevice);
  70. // Gather asset handlers from sub-systems.
  71. ImageSystem::GetAssetHandlers(m_assetHandlers);
  72. BufferSystem::GetAssetHandlers(m_assetHandlers);
  73. MaterialSystem::GetAssetHandlers(m_assetHandlers);
  74. ModelSystem::GetAssetHandlers(m_assetHandlers);
  75. PassSystem::GetAssetHandlers(m_assetHandlers);
  76. ShaderSystem::GetAssetHandlers(m_assetHandlers);
  77. m_assetHandlers.emplace_back(MakeAssetHandler<ResourcePoolAssetHandler>());
  78. m_assetHandlers.emplace_back(MakeAssetHandler<AnyAssetHandler>());
  79. m_materialSystem.Init();
  80. m_modelSystem.Init();
  81. m_shaderSystem.Init();
  82. m_passSystem.Init();
  83. m_featureProcessorFactory.Init();
  84. m_querySystem.Init(m_descriptor.m_gpuQuerySystemDescriptor);
  85. InitXRSystem();
  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. ScenePtr RPISystem::GetDefaultScene() const
  180. {
  181. for (const auto& scene : m_scenes)
  182. {
  183. if (scene->GetName() == AZ::Name("Main"))
  184. {
  185. return scene;
  186. }
  187. }
  188. return nullptr;
  189. }
  190. RenderPipelinePtr RPISystem::GetRenderPipelineForWindow(AzFramework::NativeWindowHandle windowHandle)
  191. {
  192. RenderPipelinePtr renderPipeline;
  193. for (auto& scene : m_scenes)
  194. {
  195. renderPipeline = scene->FindRenderPipelineForWindow(windowHandle);
  196. if (renderPipeline)
  197. {
  198. return renderPipeline;
  199. }
  200. }
  201. return nullptr;
  202. }
  203. Data::Asset<ShaderAsset> RPISystem::GetCommonShaderAssetForSrgs() const
  204. {
  205. AZ_Assert(m_systemAssetsInitialized, "InitializeSystemAssets() should be called once when asset catalog loaded'");
  206. return m_commonShaderAssetForSrgs;
  207. }
  208. RHI::Ptr<RHI::ShaderResourceGroupLayout> RPISystem::GetSceneSrgLayout() const
  209. {
  210. AZ_Assert(m_systemAssetsInitialized, "InitializeSystemAssets() should be called once when asset catalog loaded'");
  211. return m_sceneSrgLayout;
  212. }
  213. RHI::Ptr<RHI::ShaderResourceGroupLayout> RPISystem::GetViewSrgLayout() const
  214. {
  215. AZ_Assert(m_systemAssetsInitialized, "InitializeSystemAssets() should be called once when asset catalog loaded'");
  216. return m_viewSrgLayout;
  217. }
  218. void RPISystem::OnSystemTick()
  219. {
  220. AZ_PROFILE_SCOPE(RPI, "RPISystem: OnSystemTick");
  221. // Image system update is using system tick but not game tick so it can stream images in background even game is pausing
  222. m_imageSystem.Update();
  223. }
  224. void RPISystem::SimulationTick()
  225. {
  226. if (!m_systemAssetsInitialized || IsNullRenderer())
  227. {
  228. return;
  229. }
  230. AZ_PROFILE_SCOPE(RPI, "RPISystem: SimulationTick");
  231. AssetInitBus::Broadcast(&AssetInitBus::Events::PostLoadInit);
  232. m_currentSimulationTime = GetCurrentTime();
  233. for (auto& scene : m_scenes)
  234. {
  235. scene->Simulate(m_simulationJobPolicy, m_currentSimulationTime);
  236. }
  237. }
  238. float RPISystem::GetCurrentTime() const
  239. {
  240. const AZ::TimeUs currentSimulationTimeUs = AZ::GetRealElapsedTimeUs();
  241. return AZ::TimeUsToSeconds(currentSimulationTimeUs);
  242. }
  243. void RPISystem::InitXRSystem()
  244. {
  245. if (!m_xrSystem)
  246. {
  247. return;
  248. }
  249. auto xrRender = m_xrSystem->GetRHIXRRenderingInterface();
  250. if (!xrRender)
  251. {
  252. return;
  253. }
  254. RHI::Ptr<RHI::XRDeviceDescriptor> xrDescriptor = m_rhiSystem.GetDevice()->BuildXRDescriptor();
  255. [[maybe_unused]] auto result = xrRender->CreateDevice(xrDescriptor.get());
  256. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR device");
  257. AZ::RHI::XRSessionDescriptor sessionDescriptor;
  258. result = xrRender->CreateSession(&sessionDescriptor);
  259. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR session");
  260. result = xrRender->CreateSwapChain();
  261. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR swapchain");
  262. }
  263. void RPISystem::RenderTick()
  264. {
  265. if (!m_systemAssetsInitialized || IsNullRenderer())
  266. {
  267. m_dynamicDraw.FrameEnd();
  268. return;
  269. }
  270. AZ_PROFILE_SCOPE(RPI, "RPISystem: RenderTick");
  271. // Query system update is to increment the frame count
  272. m_querySystem.Update();
  273. // Collect draw packets for each scene and prepare RPI system SRGs
  274. // [GFX TODO] We may parallel scenes' prepare render.
  275. for (auto& scenePtr : m_scenes)
  276. {
  277. scenePtr->PrepareRender(m_prepareRenderJobPolicy, m_currentSimulationTime);
  278. }
  279. //Collect all the active pipelines running in this frame.
  280. uint16_t numActiveRenderPipelines = 0;
  281. for (auto& scenePtr : m_scenes)
  282. {
  283. numActiveRenderPipelines += scenePtr->GetActiveRenderPipelines();
  284. }
  285. m_rhiSystem.SetNumActiveRenderPipelines(numActiveRenderPipelines);
  286. m_rhiSystem.FrameUpdate(
  287. [this](RHI::FrameGraphBuilder& frameGraphBuilder)
  288. {
  289. // Pass system's frame update, which includes the logic of adding scope producers, has to be added here since the
  290. // scope producers only can be added to the frame when frame started which cleans up previous scope producers.
  291. m_passSystem.FrameUpdate(frameGraphBuilder);
  292. // Update Scene and View Srgs
  293. for (auto& scenePtr : m_scenes)
  294. {
  295. scenePtr->UpdateSrgs();
  296. }
  297. });
  298. {
  299. AZ_PROFILE_SCOPE(RPI, "RPISystem: FrameEnd");
  300. m_dynamicDraw.FrameEnd();
  301. m_passSystem.FrameEnd();
  302. for (auto& scenePtr : m_scenes)
  303. {
  304. scenePtr->OnFrameEnd();
  305. }
  306. }
  307. m_renderTick++;
  308. }
  309. void RPISystem::SetSimulationJobPolicy(RHI::JobPolicy jobPolicy)
  310. {
  311. m_simulationJobPolicy = jobPolicy;
  312. }
  313. RHI::JobPolicy RPISystem::GetSimulationJobPolicy() const
  314. {
  315. return m_simulationJobPolicy;
  316. }
  317. void RPISystem::SetRenderPrepareJobPolicy(RHI::JobPolicy jobPolicy)
  318. {
  319. m_prepareRenderJobPolicy = jobPolicy;
  320. }
  321. RHI::JobPolicy RPISystem::GetRenderPrepareJobPolicy() const
  322. {
  323. return m_prepareRenderJobPolicy;
  324. }
  325. const RPISystemDescriptor& RPISystem::GetDescriptor() const
  326. {
  327. return m_descriptor;
  328. }
  329. Name RPISystem::GetRenderApiName() const
  330. {
  331. return RHI::Factory::Get().GetName();
  332. }
  333. void RPISystem::InitializeSystemAssets()
  334. {
  335. if (m_systemAssetsInitialized)
  336. {
  337. return;
  338. }
  339. m_commonShaderAssetForSrgs = AssetUtils::LoadCriticalAsset<ShaderAsset>( m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  340. if (!m_commonShaderAssetForSrgs.IsReady())
  341. {
  342. AZ_Error("RPI system", false, "Failed to load RPI system asset %s", m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  343. return;
  344. }
  345. m_sceneSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::Scene);
  346. if (!m_sceneSrgLayout)
  347. {
  348. AZ_Error("RPISystem", false, "Failed to find SceneSrg by slot=<%u> from shader asset at path <%s>", SrgBindingSlot::Scene,
  349. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  350. return;
  351. }
  352. m_viewSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::View);
  353. if (!m_viewSrgLayout)
  354. {
  355. AZ_Error("RPISystem", false, "Failed to find ViewSrg by slot=<%u> from shader asset at path <%s>", SrgBindingSlot::View,
  356. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  357. return;
  358. }
  359. RHI::Ptr<RHI::ShaderResourceGroupLayout> bindlessSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::Bindless);
  360. if (!bindlessSrgLayout)
  361. {
  362. AZ_Error(
  363. "RPISystem",
  364. false,
  365. "Failed to find BindlessSrg by slot=<%u> from shader asset at path <%s>",
  366. SrgBindingSlot::Bindless,
  367. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  368. return;
  369. }
  370. m_rhiSystem.Init(bindlessSrgLayout);
  371. m_imageSystem.Init(m_descriptor.m_imageSystemDescriptor);
  372. m_bufferSystem.Init();
  373. m_dynamicDraw.Init(m_descriptor.m_dynamicDrawSystemDescriptor);
  374. m_passSystem.InitPassTemplates();
  375. m_systemAssetsInitialized = true;
  376. AZ_TracePrintf("RPI system", "System assets initialized\n");
  377. }
  378. bool RPISystem::IsInitialized() const
  379. {
  380. return m_systemAssetsInitialized;
  381. }
  382. bool RPISystem::IsNullRenderer() const
  383. {
  384. return m_descriptor.m_isNullRenderer;
  385. }
  386. void RPISystem::InitializeSystemAssetsForTests()
  387. {
  388. if (m_systemAssetsInitialized)
  389. {
  390. AZ_Warning("RPISystem", false, "InitializeSystemAssets should only be called once'");
  391. return;
  392. }
  393. //Init rhi/image/buffer systems to match InitializeSystemAssets
  394. m_rhiSystem.Init();
  395. m_imageSystem.Init(m_descriptor.m_imageSystemDescriptor);
  396. m_bufferSystem.Init();
  397. // Assets aren't actually available or needed for tests, but the m_systemAssetsInitialized flag still needs to be flipped.
  398. m_systemAssetsInitialized = true;
  399. return;
  400. }
  401. bool RPISystem::OnPreAssert([[maybe_unused]] const char* fileName, [[maybe_unused]] int line, [[maybe_unused]] const char* func, [[maybe_unused]] const char* message)
  402. {
  403. #if AZ_RPI_PRINT_GLOBAL_STATE_ON_ASSERT
  404. AZ_Printf("RPI System", "\n--- Assert hit! Dumping RPI state ---\n\n");
  405. m_passSystem.DebugPrintPassHierarchy();
  406. #endif
  407. return false;
  408. }
  409. uint64_t RPISystem::GetCurrentTick() const
  410. {
  411. return m_renderTick;
  412. }
  413. void RPISystem::SetApplicationMultisampleState(const RHI::MultisampleState& multisampleState)
  414. {
  415. m_multisampleState = multisampleState;
  416. bool isNonMsaaPipeline = (m_multisampleState.m_samples == 1);
  417. const char* supervariantName = isNonMsaaPipeline ? AZ::RPI::NoMsaaSupervariantName : "";
  418. AZ::RPI::ShaderSystemInterface::Get()->SetSupervariantName(AZ::Name(supervariantName));
  419. // reinitialize pipelines for all scenes
  420. for (auto& scene : m_scenes)
  421. {
  422. for (auto& renderPipeline : scene->GetRenderPipelines())
  423. {
  424. // MSAA state set to the render pipeline at creation time from its data might be different
  425. // from the one set to the application. So it can arrive here having the same new
  426. // target state, but still needs to be marked as its MSAA state has changed so its passes
  427. // are recreated using the new supervariant name coming from MSAA at application level just set above.
  428. // In conclusion, it's not safe to skip here setting MSAA state to the render pipeline when it's the
  429. // same as the target.
  430. renderPipeline->GetRenderSettings().m_multisampleState = multisampleState;
  431. renderPipeline->MarkPipelinePassChanges(PipelinePassChanges::MultisampleStateChanged);
  432. }
  433. }
  434. }
  435. const RHI::MultisampleState& RPISystem::GetApplicationMultisampleState() const
  436. {
  437. return m_multisampleState;
  438. }
  439. void RPISystem::RegisterXRSystem(XRRenderingInterface* xrSystemInterface)
  440. {
  441. AZ_Assert(!m_xrSystem, "XR System is already registered");
  442. if (m_rhiSystem.RegisterXRSystem(xrSystemInterface->GetRHIXRRenderingInterface()))
  443. {
  444. m_xrSystem = xrSystemInterface;
  445. }
  446. }
  447. void RPISystem::UnregisterXRSystem()
  448. {
  449. AZ_Assert(m_xrSystem, "XR System is not registered");
  450. if (m_xrSystem)
  451. {
  452. m_rhiSystem.UnregisterXRSystem();
  453. m_xrSystem = nullptr;
  454. }
  455. }
  456. XRRenderingInterface* RPISystem::GetXRSystem() const
  457. {
  458. return m_xrSystem;
  459. }
  460. } //namespace RPI
  461. } //namespace AZ