AssetLoadTestComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 <AssetLoadTestComponent.h>
  9. #include <SampleComponentManager.h>
  10. #include <SampleComponentConfig.h>
  11. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  12. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  13. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  14. #include <Automation/ScriptRunnerBus.h>
  15. #include <AzCore/Serialization/SerializeContext.h>
  16. #include <RHI/BasicRHIComponent.h>
  17. AZ_DECLARE_BUDGET(AtomSampleViewer);
  18. namespace AtomSampleViewer
  19. {
  20. using namespace AZ;
  21. void AssetLoadTestComponent::Reflect(AZ::ReflectContext* context)
  22. {
  23. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  24. {
  25. serializeContext->Class<AssetLoadTestComponent, EntityLatticeTestComponent>()
  26. ->Version(0)
  27. ;
  28. }
  29. }
  30. AssetLoadTestComponent::AssetLoadTestComponent()
  31. : m_materialBrowser("@user@/AssetLoadTestComponent/material_browser.xml")
  32. , m_modelBrowser("@user@/AssetLoadTestComponent/model_browser.xml")
  33. , m_imguiSidebar("@user@/AssetLoadTestComponent/sidebar.xml")
  34. {
  35. m_sampleName = "AssetLoadTestComponent";
  36. m_materialBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  37. {
  38. return assetInfo.m_assetType == azrtti_typeid<AZ::RPI::MaterialAsset>();
  39. });
  40. m_modelBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  41. {
  42. return assetInfo.m_assetType == azrtti_typeid<AZ::RPI::ModelAsset>();
  43. });
  44. const AZStd::vector<AZStd::string> defaultMaterialAllowlist =
  45. {
  46. "materials/defaultpbr.azmaterial",
  47. "materials/presets/pbr/metal_aluminum_polished.azmaterial",
  48. "materials/basic_grey.azmaterial"
  49. };
  50. m_materialBrowser.SetDefaultPinnedAssets(defaultMaterialAllowlist);
  51. m_pinnedMaterialCount = static_cast<uint32_t>(m_materialBrowser.GetPinnedAssets().size());
  52. const AZStd::vector<AZStd::string> defaultModelAllowist =
  53. {
  54. "Objects/bunny.fbx.azmodel",
  55. "Objects/Shaderball_simple.fbx.azmodel",
  56. "Objects/suzanne.fbx.azmodel",
  57. };
  58. m_modelBrowser.SetDefaultPinnedAssets(defaultModelAllowist);
  59. }
  60. void AssetLoadTestComponent::Activate()
  61. {
  62. AZ::TickBus::Handler::BusConnect();
  63. m_imguiSidebar.Activate();
  64. m_materialBrowser.Activate();
  65. m_modelBrowser.Activate();
  66. if (!m_materialBrowser.IsConfigFileLoaded())
  67. {
  68. AZ_TracePrintf("AssetLoadTestComponent", "Material allow list not loaded. Defaulting to built in list.\n");
  69. m_materialBrowser.ResetPinnedAssetsToDefault();
  70. }
  71. if (!m_modelBrowser.IsConfigFileLoaded())
  72. {
  73. AZ_TracePrintf("AssetLoadTestComponent", "Model allow list not loaded. Defaulting to built in list.\n");
  74. m_modelBrowser.ResetPinnedAssetsToDefault();
  75. }
  76. // 25 was the original max before some changes that increased ENTITY_LATTEST_TEST_COMPONENT_MAX to 100.
  77. // AssetLoadTest was crashing (out of descriptors) at 50x50x42 so we put the limit back to 25^3.
  78. // Note that limiting to 40^3 will avoid the crash, but the sample doesn't work well at that scale, the UI
  79. // doesn't even show up because of a combination of low frame rate, the reload timers, and the time it takes
  80. // to load the models, and the fact that the UI is hidden while the models are loading.
  81. // So it would be good if we could work on increasing this limit.
  82. // (It would also be good if we could improve the design of this sample to make the UI persistent and more
  83. // responsive while the assets keep reloading).
  84. Base::SetLatticeMaxDimension(25);
  85. Base::Activate();
  86. }
  87. void AssetLoadTestComponent::Deactivate()
  88. {
  89. m_materialBrowser.Deactivate();
  90. m_modelBrowser.Deactivate();
  91. AZ::TickBus::Handler::BusDisconnect();
  92. m_imguiSidebar.Deactivate();
  93. Base::Deactivate();
  94. }
  95. void AssetLoadTestComponent::PrepareCreateLatticeInstances(uint32_t instanceCount)
  96. {
  97. m_modelInstanceData.reserve(instanceCount);
  98. }
  99. void AssetLoadTestComponent::CreateLatticeInstance(const AZ::Transform& transform)
  100. {
  101. m_modelInstanceData.emplace_back<ModelInstanceData>({});
  102. ModelInstanceData& data = m_modelInstanceData.back();
  103. data.m_modelAssetId = GetRandomModelId();
  104. data.m_materialAssetId = GetRandomMaterialId();
  105. data.m_transform = transform;
  106. }
  107. void AssetLoadTestComponent::FinalizeLatticeInstances()
  108. {
  109. AZStd::set<AZ::Data::AssetId> assetIds;
  110. for (ModelInstanceData& instanceData : m_modelInstanceData)
  111. {
  112. if (instanceData.m_materialAssetId.IsValid())
  113. {
  114. assetIds.insert(instanceData.m_materialAssetId);
  115. }
  116. if (instanceData.m_modelAssetId.IsValid())
  117. {
  118. assetIds.insert(instanceData.m_modelAssetId);
  119. }
  120. }
  121. AZStd::vector<AZ::AssetCollectionAsyncLoader::AssetToLoadInfo> assetList;
  122. for (auto& assetId : assetIds)
  123. {
  124. AZ::Data::AssetInfo assetInfo;
  125. AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetInfo, &AZ::Data::AssetCatalogRequests::GetAssetInfoById, assetId);
  126. if (assetInfo.m_assetId.IsValid())
  127. {
  128. AZ::AssetCollectionAsyncLoader::AssetToLoadInfo info;
  129. info.m_assetPath = assetInfo.m_relativePath;
  130. info.m_assetType = assetInfo.m_assetType;
  131. assetList.push_back(info);
  132. }
  133. }
  134. PreloadAssets(assetList);
  135. // pause script and tick until assets are ready
  136. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScriptWithTimeout, 120.0f);
  137. AZ::TickBus::Handler::BusDisconnect();
  138. }
  139. void AssetLoadTestComponent::OnAllAssetsReadyActivate()
  140. {
  141. for (ModelInstanceData& instanceData : m_modelInstanceData)
  142. {
  143. AZ::Data::Instance<AZ::RPI::Material> materialInstance;
  144. if (instanceData.m_materialAssetId.IsValid())
  145. {
  146. AZ::Data::Asset<RPI::MaterialAsset> materialAsset;
  147. materialAsset.Create(instanceData.m_materialAssetId, true);
  148. materialInstance = AZ::RPI::Material::FindOrCreate(materialAsset);
  149. // cache the material when its loaded
  150. m_cachedMaterials.insert(materialAsset);
  151. }
  152. if (instanceData.m_modelAssetId.IsValid())
  153. {
  154. AZ::Render::MeshHandleDescriptor descriptor;
  155. descriptor.m_modelAsset.Create(instanceData.m_modelAssetId, true);
  156. descriptor.m_customMaterials[AZ::Render::DefaultCustomMaterialId].m_material = materialInstance;
  157. instanceData.m_meshHandle = GetMeshFeatureProcessor()->AcquireMesh(descriptor);
  158. GetMeshFeatureProcessor()->SetTransform(instanceData.m_meshHandle, instanceData.m_transform);
  159. }
  160. }
  161. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  162. AZ::TickBus::Handler::BusConnect();
  163. }
  164. void AssetLoadTestComponent::DestroyLatticeInstances()
  165. {
  166. DestroyHandles();
  167. m_modelInstanceData.clear();
  168. }
  169. void AssetLoadTestComponent::DestroyHandles()
  170. {
  171. for (ModelInstanceData& instanceData : m_modelInstanceData)
  172. {
  173. GetMeshFeatureProcessor()->ReleaseMesh(instanceData.m_meshHandle);
  174. instanceData.m_meshHandle = {};
  175. }
  176. }
  177. AZ::Data::AssetId AssetLoadTestComponent::GetRandomModelId() const
  178. {
  179. auto& modelAllowlist = m_modelBrowser.GetPinnedAssets();
  180. if (modelAllowlist.size())
  181. {
  182. const size_t randomModelIndex = rand() % modelAllowlist.size();
  183. return modelAllowlist[randomModelIndex].m_assetId;
  184. }
  185. else
  186. {
  187. return AZ::RPI::AssetUtils::GetAssetIdForProductPath("testdata/objects/cube/cube.fbx.azmodel", AZ::RPI::AssetUtils::TraceLevel::Error);
  188. }
  189. }
  190. AZ::Data::AssetId AssetLoadTestComponent::GetRandomMaterialId() const
  191. {
  192. auto& materialAllowlist = m_materialBrowser.GetPinnedAssets();
  193. if (materialAllowlist.size())
  194. {
  195. const size_t randomMaterialIndex = rand() % materialAllowlist.size();
  196. return materialAllowlist[randomMaterialIndex].m_assetId;
  197. }
  198. else
  199. {
  200. return AZ::RPI::AssetUtils::GetAssetIdForProductPath(DefaultPbrMaterialPath, AZ::RPI::AssetUtils::TraceLevel::Error);
  201. }
  202. }
  203. void AssetLoadTestComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint scriptTime)
  204. {
  205. AZ_PROFILE_FUNCTION(AtomSampleViewer);
  206. const float timeSeconds = static_cast<float>(scriptTime.GetSeconds());
  207. if (m_lastMaterialSwitchInSeconds == 0 || m_lastModelSwitchInSeconds == 0)
  208. {
  209. m_lastMaterialSwitchInSeconds = timeSeconds;
  210. m_lastModelSwitchInSeconds = timeSeconds;
  211. return;
  212. }
  213. bool materialSwitchRequested = m_materialSwitchEnabled && timeSeconds - m_lastMaterialSwitchInSeconds >= m_materialSwitchTimeInSeconds;
  214. bool modelSwitchRequested = m_modelSwitchEnabled && timeSeconds - m_lastModelSwitchInSeconds >= m_modelSwitchTimeInSeconds;
  215. if (m_updateTransformEnabled)
  216. {
  217. float radians = static_cast<float>(fmod(scriptTime.GetSeconds(), AZ::Constants::TwoPi));
  218. AZ::Vector3 rotation(radians, radians, radians);
  219. AZ::Transform rotationTransform;
  220. rotationTransform.SetFromEulerRadians(rotation);
  221. for (ModelInstanceData& instanceData : m_modelInstanceData)
  222. {
  223. GetMeshFeatureProcessor()->SetTransform(instanceData.m_meshHandle, instanceData.m_transform * rotationTransform);
  224. }
  225. }
  226. bool materialsChanged = false;
  227. bool modelsChanged = false;
  228. if (m_imguiSidebar.Begin())
  229. {
  230. ImGui::Checkbox("Switch Materials Every N Seconds", &m_materialSwitchEnabled);
  231. ImGui::SliderFloat("##MaterialSwitchTime", &m_materialSwitchTimeInSeconds, 0.1f, 10.0f);
  232. ImGui::Spacing();
  233. ImGui::Checkbox("Switch Models Every N Seconds", &m_modelSwitchEnabled);
  234. ImGui::SliderFloat("##ModelSwitchTime", &m_modelSwitchTimeInSeconds, 0.1f, 10.0f);
  235. ImGui::Spacing();
  236. ImGui::Checkbox("Update Transforms Every Frame", &m_updateTransformEnabled);
  237. ImGui::Spacing();
  238. ImGui::Separator();
  239. ImGui::Spacing();
  240. RenderImGuiLatticeControls();
  241. ImGui::Spacing();
  242. ImGui::Separator();
  243. ImGui::Spacing();
  244. ImGuiAssetBrowser::WidgetSettings assetBrowserSettings;
  245. assetBrowserSettings.m_labels.m_pinnedAssetList = "Allow List";
  246. assetBrowserSettings.m_labels.m_pinButton = "Add To Allow List";
  247. assetBrowserSettings.m_labels.m_unpinButton = "Remove From Allow List";
  248. assetBrowserSettings.m_labels.m_root = "Materials";
  249. m_materialBrowser.Tick(assetBrowserSettings);
  250. auto& pinnedMaterials = m_materialBrowser.GetPinnedAssets();
  251. materialsChanged = pinnedMaterials.size() != m_pinnedMaterialCount;
  252. if (materialsChanged)
  253. {
  254. m_pinnedMaterialCount = static_cast<uint32_t>(pinnedMaterials.size());
  255. // Keep the current m_cachedMaterials to avoid release-load the same material
  256. MaterialAssetSet newCache;
  257. // clean up cached material which refcount is 1
  258. for (auto& pinnedMaterial : pinnedMaterials)
  259. {
  260. AZ::Data::AssetId materialAssetid = pinnedMaterial.m_assetId;
  261. // Cache the asset if it's loaded
  262. AZ::Data::Asset<AZ::RPI::MaterialAsset> asset = AZ::Data::AssetManager::Instance().FindAsset<AZ::RPI::MaterialAsset>(materialAssetid, AZ::Data::AssetLoadBehavior::PreLoad);
  263. if (asset.IsReady())
  264. {
  265. newCache.insert(asset);
  266. }
  267. }
  268. m_cachedMaterials = newCache;
  269. }
  270. ImGui::Spacing();
  271. ImGui::Separator();
  272. ImGui::Spacing();
  273. assetBrowserSettings.m_labels.m_root = "Models";
  274. m_modelBrowser.Tick(assetBrowserSettings);
  275. modelsChanged = m_lastPinnedModelCount != m_modelBrowser.GetPinnedAssets().size();
  276. m_imguiSidebar.End();
  277. }
  278. if (materialSwitchRequested || materialsChanged)
  279. {
  280. for (ModelInstanceData& instanceData : m_modelInstanceData)
  281. {
  282. instanceData.m_materialAssetId = GetRandomMaterialId();
  283. }
  284. m_lastMaterialSwitchInSeconds = timeSeconds;
  285. }
  286. if (modelSwitchRequested || modelsChanged)
  287. {
  288. m_lastPinnedModelCount = m_modelBrowser.GetPinnedAssets().size();
  289. for (ModelInstanceData& instanceData : m_modelInstanceData)
  290. {
  291. instanceData.m_modelAssetId = GetRandomModelId();
  292. }
  293. m_lastModelSwitchInSeconds = timeSeconds;
  294. }
  295. if (materialSwitchRequested || materialsChanged || modelSwitchRequested || modelsChanged)
  296. {
  297. DestroyHandles();
  298. FinalizeLatticeInstances();
  299. }
  300. }
  301. } // namespace AtomSampleViewer