DynamicMaterialTestComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 <DynamicMaterialTestComponent.h>
  9. #include <SampleComponentManager.h>
  10. #include <SampleComponentConfig.h>
  11. #include <Automation/ScriptableImGui.h>
  12. #include <Automation/ScriptRunnerBus.h>
  13. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  14. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  15. #include <Atom/RPI.Reflect/Material/MaterialPropertiesLayout.h>
  16. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  17. #include <AzCore/Component/Entity.h>
  18. #include <AzCore/Debug/Timer.h>
  19. #include <AzCore/Math/Random.h>
  20. #include <RHI/BasicRHIComponent.h>
  21. AZ_DECLARE_BUDGET(AtomSampleViewer);
  22. namespace AtomSampleViewer
  23. {
  24. using namespace AZ;
  25. using namespace RPI;
  26. void DynamicMaterialTestComponent::Reflect(ReflectContext* context)
  27. {
  28. if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context))
  29. {
  30. serializeContext->Class<DynamicMaterialTestComponent, EntityLatticeTestComponent>()
  31. ->Version(0)
  32. ;
  33. }
  34. }
  35. DynamicMaterialTestComponent::DynamicMaterialTestComponent()
  36. : m_imguiSidebar("@user@/DynamicMaterialTestComponent/sidebar.xml")
  37. , m_compileTimer(CompileTimerQueueSize, CompileTimerQueueSize)
  38. {
  39. }
  40. void DynamicMaterialTestComponent::Activate()
  41. {
  42. TickBus::Handler::BusConnect();
  43. m_imguiSidebar.Activate();
  44. InitMaterialConfigs();
  45. Base::Activate();
  46. m_currentTime = 0.0f;
  47. }
  48. void DynamicMaterialTestComponent::Deactivate()
  49. {
  50. TickBus::Handler::BusDisconnect();
  51. m_imguiSidebar.Deactivate();
  52. Base::Deactivate();
  53. }
  54. void DynamicMaterialTestComponent::PrepareCreateLatticeInstances(uint32_t instanceCount)
  55. {
  56. const char* modelPath = "objects/shaderball_simple.azmodel";
  57. Data::AssetId modelAssetId;
  58. Data::AssetCatalogRequestBus::BroadcastResult(
  59. modelAssetId, &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath,
  60. modelPath, azrtti_typeid<ModelAsset>(), false);
  61. AZ_Assert(modelAssetId.IsValid(), "Failed to get model asset id: %s", modelPath);
  62. m_modelAsset.Create(modelAssetId);
  63. m_meshHandles.reserve(instanceCount);
  64. m_materials.reserve(instanceCount);
  65. // Give the models time to load before continuing scripts
  66. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  67. m_waitingForMeshes = true;
  68. }
  69. void DynamicMaterialTestComponent::CreateLatticeInstance(const Transform& transform)
  70. {
  71. AZ::Data::Asset<AZ::RPI::MaterialAsset>& materialAsset = m_materialConfigs[m_currentMaterialConfig].m_materialAsset;
  72. AZ::Data::Instance<AZ::RPI::Material> material = Material::Create(materialAsset);
  73. Render::MaterialAssignmentMap materialMap;
  74. Render::MaterialAssignment& defaultMaterial = materialMap[Render::DefaultMaterialAssignmentId];
  75. defaultMaterial.m_materialAsset = materialAsset;
  76. defaultMaterial.m_materialInstance = material;
  77. Render::MeshHandleDescriptor meshDescriptor;
  78. meshDescriptor.m_modelAsset = m_modelAsset;
  79. meshDescriptor.m_isRayTracingEnabled = false;
  80. auto meshHandle = GetMeshFeatureProcessor()->AcquireMesh(meshDescriptor, materialMap);
  81. GetMeshFeatureProcessor()->SetTransform(meshHandle, transform);
  82. Data::Instance<RPI::Model> model = GetMeshFeatureProcessor()->GetModel(meshHandle);
  83. if (model)
  84. {
  85. m_loadedMeshCounter++;
  86. }
  87. else
  88. {
  89. m_meshLoadEventHandlers.push_back(AZ::Render::MeshFeatureProcessorInterface::ModelChangedEvent::Handler
  90. {
  91. [this](AZ::Data::Instance<AZ::RPI::Model> model) { m_loadedMeshCounter++; }
  92. });
  93. GetMeshFeatureProcessor()->ConnectModelChangeEventHandler(meshHandle, m_meshLoadEventHandlers.back());
  94. }
  95. m_meshHandles.push_back(AZStd::move(meshHandle));
  96. m_materials.push_back(material);
  97. }
  98. void DynamicMaterialTestComponent::DestroyLatticeInstances()
  99. {
  100. for (auto& meshHandle : m_meshHandles)
  101. {
  102. GetMeshFeatureProcessor()->ReleaseMesh(meshHandle);
  103. }
  104. m_meshHandles.clear();
  105. m_materials.clear();
  106. m_loadedMeshCounter = 0;
  107. m_waitingForMeshes = false;
  108. m_meshLoadEventHandlers.clear();
  109. }
  110. void DynamicMaterialTestComponent::InitMaterialConfigs()
  111. {
  112. using namespace AZ::RPI;
  113. MaterialConfig config;
  114. config.m_name = "Default StandardPBR Material";
  115. config.m_materialAsset = AssetUtils::GetAssetByProductPath<MaterialAsset>(DefaultPbrMaterialPath, AssetUtils::TraceLevel::Assert);
  116. config.m_updateLatticeMaterials = [this]() { UpdateStandardPbrColors(); };
  117. m_materialConfigs.push_back(config);
  118. config.m_name = "C++ Functor Test Material";
  119. config.m_materialAsset = AssetUtils::GetAssetByProductPath<MaterialAsset>("materials/dynamicmaterialtest/emissivewithcppfunctors.azmaterial", AssetUtils::TraceLevel::Assert);
  120. config.m_updateLatticeMaterials = [this]() { UpdateEmissiveMaterialIntensity(); };
  121. m_materialConfigs.push_back(config);
  122. config.m_name = "Lua Functor Test Material";
  123. config.m_materialAsset = AssetUtils::GetAssetByProductPath<MaterialAsset>("materials/dynamicmaterialtest/emissivewithluafunctors.azmaterial", AssetUtils::TraceLevel::Assert);
  124. config.m_updateLatticeMaterials = [this]() { UpdateEmissiveMaterialIntensity(); };
  125. m_materialConfigs.push_back(config);
  126. m_currentMaterialConfig = 0;
  127. }
  128. void DynamicMaterialTestComponent::UpdateStandardPbrColors()
  129. {
  130. static const Color colorOptions[] =
  131. {
  132. Color(1.0f, 0.0f, 0.0f, 1.0f),
  133. Color(0.0f, 1.0f, 0.0f, 1.0f),
  134. Color(0.0f, 0.0f, 1.0f, 1.0f),
  135. Color(1.0f, 1.0f, 0.0f, 1.0f),
  136. Color(0.0f, 1.0f, 1.0f, 1.0f),
  137. Color(1.0f, 0.0f, 1.0f, 1.0f),
  138. };
  139. // Create a new SimpleLcgRandom every time to keep a consistent seed and consistent color selection.
  140. SimpleLcgRandom random;
  141. for (int i = 0; i < m_meshHandles.size(); ++i)
  142. {
  143. auto& material = m_materials[i];
  144. static const float CylesPerSecond = 0.5f;
  145. const float t = aznumeric_cast<float>(sin(m_currentTime * CylesPerSecond * AZ::Constants::TwoPi) * 0.5f + 0.5f);
  146. const int colorIndexA = random.GetRandom() % AZ_ARRAY_SIZE(colorOptions);
  147. int colorIndexB = colorIndexA;
  148. while (colorIndexA == colorIndexB)
  149. {
  150. colorIndexB = random.GetRandom() % AZ_ARRAY_SIZE(colorOptions);
  151. }
  152. const Color color = colorOptions[colorIndexA] * t + colorOptions[colorIndexB] * (1.0f - t);
  153. MaterialPropertyIndex colorProperty = material->FindPropertyIndex(AZ::Name{"baseColor.color"});
  154. material->SetPropertyValue(colorProperty, color);
  155. }
  156. }
  157. void DynamicMaterialTestComponent::UpdateEmissiveMaterialIntensity()
  158. {
  159. for (int i = 0; i < m_meshHandles.size(); ++i)
  160. {
  161. auto& meshHandle = m_meshHandles[i];
  162. auto& material = m_materials[i];
  163. const float distance = GetMeshFeatureProcessor()->GetTransform(meshHandle).GetTranslation().GetLengthEstimate();
  164. static const float DistanceScale = 0.02f;
  165. static const float CylesPerSecond = 0.5f;
  166. const float t = aznumeric_cast<float>(sin((DistanceScale * distance + m_currentTime * CylesPerSecond) * AZ::Constants::TwoPi) * 0.5f + 0.5f);
  167. static const float MinIntensity = 1.0f;
  168. static const float MaxIntensity = 4.0f;
  169. const float intensity = AZ::Lerp(MinIntensity, MaxIntensity, t);
  170. MaterialPropertyIndex intensityProperty = material->FindPropertyIndex(AZ::Name{"emissive.intensity"});
  171. material->SetPropertyValue(intensityProperty, intensity);
  172. }
  173. }
  174. void DynamicMaterialTestComponent::CompileMaterials()
  175. {
  176. AZ::Debug::Timer timer;
  177. timer.Stamp();
  178. for (auto& material : m_materials)
  179. {
  180. material->Compile();
  181. }
  182. m_compileTimer.PushValue(timer.GetDeltaTimeInSeconds() * 1'000'000);
  183. }
  184. void DynamicMaterialTestComponent::OnTick(float deltaTime, ScriptTimePoint /*scriptTime*/)
  185. {
  186. AZ_PROFILE_FUNCTION(AtomSampleViewer);
  187. if (m_waitingForMeshes)
  188. {
  189. if(m_loadedMeshCounter == m_meshHandles.size())
  190. {
  191. m_waitingForMeshes = false;
  192. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  193. // Reset the clock so we get consistent animation for scripts
  194. m_currentTime = 0;
  195. }
  196. }
  197. AZ_Assert(m_loadedMeshCounter <= m_meshHandles.size(), "Mesh load handlers were called multiple times?");
  198. bool updateMaterials = false;
  199. if (!m_pause)
  200. {
  201. m_currentTime += deltaTime;
  202. updateMaterials = true;
  203. }
  204. if (m_imguiSidebar.Begin())
  205. {
  206. RenderImGuiLatticeControls();
  207. ImGui::Separator();
  208. bool configChanged = false;
  209. for (int i = 0; i < m_materialConfigs.size(); ++i)
  210. {
  211. configChanged = configChanged || ScriptableImGui::RadioButton(m_materialConfigs[i].m_name.c_str(), &m_currentMaterialConfig, i);
  212. }
  213. if (configChanged)
  214. {
  215. RebuildLattice();
  216. }
  217. ImGui::Separator();
  218. ScriptableImGui::Checkbox("Pause", &m_pause);
  219. if (ScriptableImGui::Button("Reset Clock"))
  220. {
  221. m_currentTime = 0;
  222. updateMaterials = true;
  223. }
  224. ImGui::Separator();
  225. ImGui::Text("%d unique objects", aznumeric_cast<int32_t>(m_meshHandles.size()));
  226. ImGui::Text("Total Material Compile Time:");
  227. ImGuiHistogramQueue::WidgetSettings settings;
  228. settings.m_units = "microseconds";
  229. m_compileTimer.Tick(deltaTime, settings);
  230. ImGui::Text("Average per Material: %4.2f", m_compileTimer.GetDisplayedAverage() / m_materials.size());
  231. ImGui::Separator();
  232. m_imguiSidebar.End();
  233. }
  234. if (updateMaterials)
  235. {
  236. m_materialConfigs[m_currentMaterialConfig].m_updateLatticeMaterials();
  237. CompileMaterials();
  238. }
  239. }
  240. } // namespace AtomSampleViewer