3
0

RPISystem.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. 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. // The creation of an XR Session requires an asset that defines
  246. // the action bindings for the application. This means the asset catalog
  247. // must be available before creating the XR Session.
  248. AZ_Assert(m_systemAssetsInitialized, "IntXRSystem should not be called before the asset system is ready.");
  249. if (!m_xrSystem)
  250. {
  251. return;
  252. }
  253. auto xrRender = m_xrSystem->GetRHIXRRenderingInterface();
  254. if (!xrRender)
  255. {
  256. return;
  257. }
  258. RHI::Ptr<RHI::XRDeviceDescriptor> xrDescriptor = m_rhiSystem.GetDevice()->BuildXRDescriptor();
  259. [[maybe_unused]] auto result = xrRender->CreateDevice(xrDescriptor.get());
  260. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR device");
  261. AZ::RHI::XRSessionDescriptor sessionDescriptor;
  262. result = xrRender->CreateSession(&sessionDescriptor);
  263. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR session");
  264. result = xrRender->CreateSwapChain();
  265. AZ_Error("RPISystem", result == RHI::ResultCode::Success, "Failed to initialize XR swapchain");
  266. }
  267. void RPISystem::RenderTick()
  268. {
  269. if (!m_systemAssetsInitialized || IsNullRenderer())
  270. {
  271. m_dynamicDraw.FrameEnd();
  272. return;
  273. }
  274. AZ_PROFILE_SCOPE(RPI, "RPISystem: RenderTick");
  275. // Query system update is to increment the frame count
  276. m_querySystem.Update();
  277. // Collect draw packets for each scene and prepare RPI system SRGs
  278. // [GFX TODO] We may parallel scenes' prepare render.
  279. for (auto& scenePtr : m_scenes)
  280. {
  281. scenePtr->PrepareRender(m_prepareRenderJobPolicy, m_currentSimulationTime);
  282. }
  283. //Collect all the active pipelines running in this frame.
  284. uint16_t numActiveRenderPipelines = 0;
  285. for (auto& scenePtr : m_scenes)
  286. {
  287. numActiveRenderPipelines += scenePtr->GetActiveRenderPipelines();
  288. }
  289. m_rhiSystem.SetNumActiveRenderPipelines(numActiveRenderPipelines);
  290. m_rhiSystem.FrameUpdate(
  291. [this](RHI::FrameGraphBuilder& frameGraphBuilder)
  292. {
  293. // Pass system's frame update, which includes the logic of adding scope producers, has to be added here since the
  294. // scope producers only can be added to the frame when frame started which cleans up previous scope producers.
  295. m_passSystem.FrameUpdate(frameGraphBuilder);
  296. // Update Scene and View Srgs
  297. for (auto& scenePtr : m_scenes)
  298. {
  299. scenePtr->UpdateSrgs();
  300. }
  301. });
  302. {
  303. AZ_PROFILE_SCOPE(RPI, "RPISystem: FrameEnd");
  304. m_dynamicDraw.FrameEnd();
  305. m_passSystem.FrameEnd();
  306. for (auto& scenePtr : m_scenes)
  307. {
  308. scenePtr->OnFrameEnd();
  309. }
  310. }
  311. m_renderTick++;
  312. }
  313. void RPISystem::SetSimulationJobPolicy(RHI::JobPolicy jobPolicy)
  314. {
  315. m_simulationJobPolicy = jobPolicy;
  316. }
  317. RHI::JobPolicy RPISystem::GetSimulationJobPolicy() const
  318. {
  319. return m_simulationJobPolicy;
  320. }
  321. void RPISystem::SetRenderPrepareJobPolicy(RHI::JobPolicy jobPolicy)
  322. {
  323. m_prepareRenderJobPolicy = jobPolicy;
  324. }
  325. RHI::JobPolicy RPISystem::GetRenderPrepareJobPolicy() const
  326. {
  327. return m_prepareRenderJobPolicy;
  328. }
  329. const RPISystemDescriptor& RPISystem::GetDescriptor() const
  330. {
  331. return m_descriptor;
  332. }
  333. Name RPISystem::GetRenderApiName() const
  334. {
  335. return RHI::Factory::Get().GetName();
  336. }
  337. void RPISystem::InitializeSystemAssets()
  338. {
  339. if (m_systemAssetsInitialized)
  340. {
  341. return;
  342. }
  343. m_commonShaderAssetForSrgs = AssetUtils::LoadCriticalAsset<ShaderAsset>( m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  344. if (!m_commonShaderAssetForSrgs.IsReady())
  345. {
  346. AZ_Error("RPI system", false, "Failed to load RPI system asset %s", m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  347. return;
  348. }
  349. m_sceneSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::Scene);
  350. if (!m_sceneSrgLayout)
  351. {
  352. AZ_Error("RPISystem", false, "Failed to find SceneSrg by slot=<%u> from shader asset at path <%s>", SrgBindingSlot::Scene,
  353. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  354. return;
  355. }
  356. m_viewSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::View);
  357. if (!m_viewSrgLayout)
  358. {
  359. AZ_Error("RPISystem", false, "Failed to find ViewSrg by slot=<%u> from shader asset at path <%s>", SrgBindingSlot::View,
  360. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  361. return;
  362. }
  363. RHI::Ptr<RHI::ShaderResourceGroupLayout> bindlessSrgLayout = m_commonShaderAssetForSrgs->FindShaderResourceGroupLayout(SrgBindingSlot::Bindless);
  364. if (!bindlessSrgLayout)
  365. {
  366. AZ_Error(
  367. "RPISystem",
  368. false,
  369. "Failed to find BindlessSrg by slot=<%u> from shader asset at path <%s>",
  370. SrgBindingSlot::Bindless,
  371. m_descriptor.m_commonSrgsShaderAssetPath.c_str());
  372. return;
  373. }
  374. m_rhiSystem.Init(bindlessSrgLayout);
  375. m_imageSystem.Init(m_descriptor.m_imageSystemDescriptor);
  376. m_bufferSystem.Init();
  377. m_dynamicDraw.Init(m_descriptor.m_dynamicDrawSystemDescriptor);
  378. m_passSystem.InitPassTemplates();
  379. m_systemAssetsInitialized = true;
  380. AZ_TracePrintf("RPI system", "System assets initialized\n");
  381. // Now that the asset system is up and running, we can safely initialize
  382. // the XR System and the XR Session.
  383. InitXRSystem();
  384. }
  385. bool RPISystem::IsInitialized() const
  386. {
  387. return m_systemAssetsInitialized;
  388. }
  389. bool RPISystem::IsNullRenderer() const
  390. {
  391. return m_descriptor.m_isNullRenderer;
  392. }
  393. void RPISystem::InitializeSystemAssetsForTests()
  394. {
  395. if (m_systemAssetsInitialized)
  396. {
  397. AZ_Warning("RPISystem", false, "InitializeSystemAssets should only be called once'");
  398. return;
  399. }
  400. //Init rhi/image/buffer systems to match InitializeSystemAssets
  401. m_rhiSystem.Init();
  402. m_imageSystem.Init(m_descriptor.m_imageSystemDescriptor);
  403. m_bufferSystem.Init();
  404. // Assets aren't actually available or needed for tests, but the m_systemAssetsInitialized flag still needs to be flipped.
  405. m_systemAssetsInitialized = true;
  406. return;
  407. }
  408. bool RPISystem::OnPreAssert([[maybe_unused]] const char* fileName, [[maybe_unused]] int line, [[maybe_unused]] const char* func, [[maybe_unused]] const char* message)
  409. {
  410. #if AZ_RPI_PRINT_GLOBAL_STATE_ON_ASSERT
  411. AZ_Printf("RPI System", "\n--- Assert hit! Dumping RPI state ---\n\n");
  412. m_passSystem.DebugPrintPassHierarchy();
  413. #endif
  414. return false;
  415. }
  416. uint64_t RPISystem::GetCurrentTick() const
  417. {
  418. return m_renderTick;
  419. }
  420. void RPISystem::SetApplicationMultisampleState(const RHI::MultisampleState& multisampleState)
  421. {
  422. m_multisampleState = multisampleState;
  423. bool isNonMsaaPipeline = (m_multisampleState.m_samples == 1);
  424. const char* supervariantName = isNonMsaaPipeline ? AZ::RPI::NoMsaaSupervariantName : "";
  425. AZ::RPI::ShaderSystemInterface::Get()->SetSupervariantName(AZ::Name(supervariantName));
  426. // reinitialize pipelines for all scenes
  427. for (auto& scene : m_scenes)
  428. {
  429. for (auto& renderPipeline : scene->GetRenderPipelines())
  430. {
  431. // MSAA state set to the render pipeline at creation time from its data might be different
  432. // from the one set to the application. So it can arrive here having the same new
  433. // target state, but still needs to be marked as its MSAA state has changed so its passes
  434. // are recreated using the new supervariant name coming from MSAA at application level just set above.
  435. // In conclusion, it's not safe to skip here setting MSAA state to the render pipeline when it's the
  436. // same as the target.
  437. renderPipeline->GetRenderSettings().m_multisampleState = multisampleState;
  438. renderPipeline->MarkPipelinePassChanges(PipelinePassChanges::MultisampleStateChanged);
  439. }
  440. }
  441. }
  442. const RHI::MultisampleState& RPISystem::GetApplicationMultisampleState() const
  443. {
  444. return m_multisampleState;
  445. }
  446. void RPISystem::RegisterXRSystem(XRRenderingInterface* xrSystemInterface)
  447. {
  448. AZ_Assert(!m_xrSystem, "XR System is already registered");
  449. if (m_rhiSystem.RegisterXRSystem(xrSystemInterface->GetRHIXRRenderingInterface()))
  450. {
  451. m_xrSystem = xrSystemInterface;
  452. }
  453. }
  454. void RPISystem::UnregisterXRSystem()
  455. {
  456. AZ_Assert(m_xrSystem, "XR System is not registered");
  457. if (m_xrSystem)
  458. {
  459. m_rhiSystem.UnregisterXRSystem();
  460. m_xrSystem = nullptr;
  461. }
  462. }
  463. XRRenderingInterface* RPISystem::GetXRSystem() const
  464. {
  465. return m_xrSystem;
  466. }
  467. } //namespace RPI
  468. } //namespace AZ