CommonSampleComponentBase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 <CommonSampleComponentBase.h>
  9. #include <SampleComponentManager.h>
  10. #include <SampleComponentConfig.h>
  11. #include <Automation/ScriptableImGui.h>
  12. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  13. #include <Atom/RPI.Public/Image/StreamingImage.h>
  14. #include <RHI/BasicRHIComponent.h>
  15. #include <EntityUtilityFunctions.h>
  16. namespace AtomSampleViewer
  17. {
  18. using namespace AZ;
  19. using namespace RPI;
  20. void CommonSampleComponentBase::Reflect(ReflectContext* context)
  21. {
  22. if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context))
  23. {
  24. serializeContext->Class<CommonSampleComponentBase, Component>()
  25. ->Version(0)
  26. ;
  27. }
  28. }
  29. bool CommonSampleComponentBase::ReadInConfig(const ComponentConfig* baseConfig)
  30. {
  31. m_scene = RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("RPI"));
  32. auto config = azrtti_cast<const SampleComponentConfig*>(baseConfig);
  33. if (config && config->IsValid())
  34. {
  35. m_cameraEntityId = config->m_cameraEntityId;
  36. m_entityContextId = config->m_entityContextId;
  37. return true;
  38. }
  39. else
  40. {
  41. AZ_Assert(false, "SampleComponentConfig required for sample component configuration.");
  42. return false;
  43. }
  44. }
  45. AzFramework::EntityContextId CommonSampleComponentBase::GetEntityContextId() const
  46. {
  47. return m_entityContextId;
  48. }
  49. AZ::EntityId CommonSampleComponentBase::GetCameraEntityId() const
  50. {
  51. return m_cameraEntityId;
  52. }
  53. AZ::Render::MeshFeatureProcessorInterface* CommonSampleComponentBase::GetMeshFeatureProcessor() const
  54. {
  55. if (!m_meshFeatureProcessor)
  56. {
  57. m_meshFeatureProcessor = Scene::GetFeatureProcessorForEntityContextId<Render::MeshFeatureProcessorInterface>(m_entityContextId);
  58. AZ_Assert(m_meshFeatureProcessor, "MeshFeatureProcessor not available.");
  59. }
  60. return m_meshFeatureProcessor;
  61. }
  62. void CommonSampleComponentBase::InitLightingPresets(bool loadDefaultLightingPresets)
  63. {
  64. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(GetEntityContextId());
  65. AZ_Assert(skyboxFeatureProcessor, "Unable to find SkyBoxFeatureProcessorInterface.");
  66. skyboxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap);
  67. skyboxFeatureProcessor->Enable(true);
  68. // We don't necessarily need an entity but PostProcessFeatureProcessorInterface needs an ID to retrieve ExposureControlSettingsInterface.
  69. AzFramework::EntityContextRequestBus::EventResult(m_postProcessEntity, m_entityContextId, &AzFramework::EntityContextRequestBus::Events::CreateEntity, "postProcessEntity");
  70. AZ_Assert(m_postProcessEntity != nullptr, "Failed to create post process entity.");
  71. m_postProcessEntity->Activate();
  72. if (loadDefaultLightingPresets)
  73. {
  74. AZStd::list<AZ::Data::AssetInfo> lightingAssetInfoList;
  75. AZ::Data::AssetCatalogRequests::AssetEnumerationCB enumerateCB = [&lightingAssetInfoList]([[maybe_unused]] const AZ::Data::AssetId id, const AZ::Data::AssetInfo& info)
  76. {
  77. if (AzFramework::StringFunc::EndsWith(info.m_relativePath.c_str(), ".lightingpreset.azasset"))
  78. {
  79. lightingAssetInfoList.push_front(info);
  80. }
  81. };
  82. AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::EnumerateAssets, nullptr, enumerateCB, nullptr);
  83. for (const auto& info : lightingAssetInfoList)
  84. {
  85. AppendLightingPresetsFromAsset(info.m_relativePath);
  86. }
  87. }
  88. // set the initial lighting preset
  89. static const char* InitialLightingPresetName = "Palermo Sidewalk";
  90. for (uint32_t index = 0; index < m_lightingPresets.size(); ++index)
  91. {
  92. if (AZ::StringFunc::Contains(m_lightingPresets[index].m_displayName, InitialLightingPresetName))
  93. {
  94. m_currentLightingPresetIndex = index;
  95. OnLightingPresetSelected(m_lightingPresets[m_currentLightingPresetIndex].m_preset, m_useAlternateSkybox);
  96. break;
  97. }
  98. }
  99. AZ::TransformNotificationBus::MultiHandler::BusConnect(m_cameraEntityId);
  100. AZ::EntityBus::MultiHandler::BusConnect(m_postProcessEntity->GetId());
  101. }
  102. void CommonSampleComponentBase::ShutdownLightingPresets()
  103. {
  104. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  105. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  106. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::ImageBasedLightFeatureProcessorInterface>(m_entityContextId);
  107. for (AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  108. {
  109. directionalLightFeatureProcessor->ReleaseLight(handle);
  110. }
  111. m_lightHandles.clear();
  112. ClearLightingPresets();
  113. if (m_postProcessEntity)
  114. {
  115. DestroyEntity(m_postProcessEntity, GetEntityContextId());
  116. }
  117. skyboxFeatureProcessor->Enable(false);
  118. iblFeatureProcessor->Reset();
  119. AZ::TransformNotificationBus::MultiHandler::BusDisconnect();
  120. AZ::EntityBus::MultiHandler::BusDisconnect();
  121. }
  122. void CommonSampleComponentBase::LoadLightingPresetsFromAsset(const AZStd::string& assetPath)
  123. {
  124. ClearLightingPresets();
  125. AppendLightingPresetsFromAsset(assetPath);
  126. }
  127. void CommonSampleComponentBase::AppendLightingPresetsFromAsset(const AZStd::string& assetPath)
  128. {
  129. Data::Asset<AnyAsset> asset = AssetUtils::LoadAssetByProductPath<AnyAsset>(assetPath.c_str(), AssetUtils::TraceLevel::Error);
  130. if (asset)
  131. {
  132. const AZ::Render::LightingPreset* preset = asset->GetDataAs<AZ::Render::LightingPreset>();
  133. if (preset)
  134. {
  135. AZStd::string displayName;
  136. AZ::StringFunc::Path::GetFullFileName(assetPath.c_str(), displayName);
  137. AZ::StringFunc::Replace(displayName, ".lightingpreset.azasset", "");
  138. AZStd::vector<AZStd::string> displayNameParts;
  139. AZ::StringFunc::Tokenize(displayName, displayNameParts, "\\/, ()_-");
  140. for (auto& displayNamePart : displayNameParts)
  141. {
  142. displayNamePart[0] = aznumeric_cast<char>(toupper(displayNamePart[0]));
  143. }
  144. displayName.clear();
  145. AZ::StringFunc::Join(displayName, displayNameParts, ' ');
  146. m_lightingPresets.push_back({ displayName, *preset });
  147. }
  148. m_lightingPresetsDirty = true;
  149. if (!m_lightingPresets.empty() && m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  150. {
  151. m_currentLightingPresetIndex = 0;
  152. OnLightingPresetSelected(m_lightingPresets[0].m_preset, m_useAlternateSkybox);
  153. }
  154. }
  155. else
  156. {
  157. AZ_Error("Lighting Preset", false, "Lighting preset file failed to load from path: %s.", assetPath.c_str());
  158. }
  159. }
  160. void CommonSampleComponentBase::ClearLightingPresets()
  161. {
  162. m_currentLightingPresetIndex = InvalidLightingPresetIndex;
  163. m_useAlternateSkybox = false;
  164. m_lightingPresets.clear();
  165. m_lightingPresetsDirty = true;
  166. }
  167. void CommonSampleComponentBase::ImGuiLightingPreset()
  168. {
  169. AZ_Assert((m_currentLightingPresetIndex == InvalidLightingPresetIndex) == m_lightingPresets.empty(),
  170. "m_currentLightingPresetIndex should be invalid if and only if no lighting presets are loaded.");
  171. if (m_currentLightingPresetIndex == InvalidLightingPresetIndex)
  172. {
  173. AZ_Warning("Lighting Preset", false, "Lighting presets must be loaded before calling ImGui.");
  174. return;
  175. }
  176. AZStd::string selectedPresetLabel = m_lightingPresets[m_currentLightingPresetIndex].m_displayName;
  177. if (m_useAlternateSkybox)
  178. {
  179. selectedPresetLabel += " (Alt)";
  180. }
  181. // Note that before we were using ScriptableImGui::Combo but there were issues (at least on some systems) when the number of items
  182. // exceeded the max visible item count (which defaults to 8 in ImGui). In this case you'd expect to see a scroll bar in the combo box,
  183. // but the combo box just never popped up. This only happened in profile, not debug builds. It seems to be a bug in ImGui. So by using
  184. // BeginCombo with ImGuiComboFlags_HeightLargest, we just make sure the combo box is always big enough for all the items.
  185. if (ScriptableImGui::BeginCombo("Lighting Preset##SampleBase", selectedPresetLabel.c_str(), ImGuiComboFlags_HeightLargest))
  186. {
  187. for (uint32_t i = 0; i < m_lightingPresets.size(); ++i)
  188. {
  189. AZStd::string& name = m_lightingPresets[i].m_displayName;
  190. AZStd::string nameForAlternateSkybox = name + " (Alt)";
  191. // Each LightingPreset can have an alternate skybox (usually a blurred version of the primary skybox), so we expose both here as separate items in the UI.
  192. bool useThisPresetWithNormalSkybox = (static_cast<int32_t>(i) == m_currentLightingPresetIndex) && !m_useAlternateSkybox;
  193. bool useThisPresetWithAlternateSkybox = (static_cast<int32_t>(i) == m_currentLightingPresetIndex) && m_useAlternateSkybox;
  194. useThisPresetWithNormalSkybox = ScriptableImGui::Selectable(name.c_str(), useThisPresetWithNormalSkybox);
  195. useThisPresetWithAlternateSkybox = ScriptableImGui::Selectable(nameForAlternateSkybox.c_str(), useThisPresetWithAlternateSkybox);
  196. if (useThisPresetWithNormalSkybox || useThisPresetWithAlternateSkybox)
  197. {
  198. m_currentLightingPresetIndex = i;
  199. m_useAlternateSkybox = useThisPresetWithAlternateSkybox;
  200. OnLightingPresetSelected(m_lightingPresets[i].m_preset, m_useAlternateSkybox);
  201. }
  202. }
  203. ScriptableImGui::EndCombo();
  204. }
  205. }
  206. void CommonSampleComponentBase::OnLightingPresetSelected(const AZ::Render::LightingPreset& preset, bool useAlternateSkybox)
  207. {
  208. AZ::Render::SkyBoxFeatureProcessorInterface* skyboxFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::SkyBoxFeatureProcessorInterface>(m_entityContextId);
  209. AZ::Render::PostProcessFeatureProcessorInterface* postProcessFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::PostProcessFeatureProcessorInterface>(m_entityContextId);
  210. AZ::Render::ImageBasedLightFeatureProcessorInterface* iblFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::ImageBasedLightFeatureProcessorInterface>(m_entityContextId);
  211. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  212. AZ::Render::ExposureControlSettingsInterface* exposureControlSettingInterface = postProcessFeatureProcessor->GetOrCreateSettingsInterface(m_postProcessEntity->GetId())->GetOrCreateExposureControlSettingsInterface();
  213. Camera::Configuration cameraConfig;
  214. Camera::CameraRequestBus::EventResult(cameraConfig, m_cameraEntityId, &Camera::CameraRequestBus::Events::GetCameraConfiguration);
  215. preset.ApplyLightingPreset(
  216. iblFeatureProcessor,
  217. skyboxFeatureProcessor,
  218. exposureControlSettingInterface,
  219. directionalLightFeatureProcessor,
  220. cameraConfig,
  221. m_lightHandles,
  222. useAlternateSkybox);
  223. }
  224. void CommonSampleComponentBase::OnTransformChanged(const AZ::Transform&, const AZ::Transform&)
  225. {
  226. const AZ::EntityId* currentBusId = AZ::TransformNotificationBus::GetCurrentBusId();
  227. AZ::Render::DirectionalLightFeatureProcessorInterface* directionalLightFeatureProcessor = AZ::RPI::Scene::GetFeatureProcessorForEntityContextId<AZ::Render::DirectionalLightFeatureProcessorInterface>(m_entityContextId);
  228. if (currentBusId && *currentBusId == m_cameraEntityId && directionalLightFeatureProcessor)
  229. {
  230. auto transform = AZ::Transform::CreateIdentity();
  231. AZ::TransformBus::EventResult(
  232. transform,
  233. m_cameraEntityId,
  234. &AZ::TransformBus::Events::GetWorldTM);
  235. for (const AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle& handle : m_lightHandles)
  236. {
  237. directionalLightFeatureProcessor->SetCameraTransform(handle, transform);
  238. }
  239. }
  240. }
  241. void CommonSampleComponentBase::OnLightingPresetEntityShutdown(const AZ::EntityId& entityId)
  242. {
  243. if (m_postProcessEntity && m_postProcessEntity->GetId() == entityId)
  244. {
  245. m_postProcessEntity = nullptr;
  246. }
  247. }
  248. void CommonSampleComponentBase::PreloadAssets(const AZStd::vector<AssetCollectionAsyncLoader::AssetToLoadInfo>& assetList)
  249. {
  250. m_isAllAssetsReady = false;
  251. // Configure the imgui progress list widget.
  252. auto onUserCancelledAction = [&]()
  253. {
  254. AZ_TracePrintf(m_sampleName.c_str() , "Cancelled by user.\n");
  255. m_assetLoadManager.Cancel();
  256. SampleComponentManagerRequestBus::Broadcast(&SampleComponentManagerRequests::Reset);
  257. };
  258. m_imguiProgressList.OpenPopup("Waiting For Assets...", "Assets pending for processing:", {}, onUserCancelledAction, true /*automaticallyCloseOnAction*/, "Cancel");
  259. AZStd::for_each(assetList.begin(), assetList.end(),
  260. [&](const AssetCollectionAsyncLoader::AssetToLoadInfo& item) { m_imguiProgressList.AddItem(item.m_assetPath); });
  261. m_assetLoadManager.LoadAssetsAsync(assetList, [&](AZStd::string_view assetName, [[maybe_unused]] bool success, size_t pendingAssetCount)
  262. {
  263. AZ_Error(m_sampleName.c_str(), success, "Error loading asset %s, a crash will occur when OnAllAssetsReadyActivate() is called!", assetName.data());
  264. AZ_TracePrintf(m_sampleName.c_str(), "Asset %s loaded %s. Wait for %zu more assets before full activation\n", assetName.data(), success ? "successfully" : "UNSUCCESSFULLY", pendingAssetCount);
  265. m_imguiProgressList.RemoveItem(assetName);
  266. if (!pendingAssetCount && !m_isAllAssetsReady)
  267. {
  268. m_isAllAssetsReady = true;
  269. OnAllAssetsReadyActivate();
  270. }
  271. });
  272. }
  273. void CommonSampleComponentBase::ResetScene()
  274. {
  275. m_meshFeatureProcessor = nullptr;
  276. }
  277. } // namespace AtomSampleViewer