DynamicMaterialTestComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /*
  2. * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
  3. * its licensors.
  4. *
  5. * For complete copyright and license terms please see the LICENSE at the root of this
  6. * distribution (the "License"). All use of this software is governed by the License,
  7. * or, if provided, by the license below or the license accompanying this file. Do not
  8. * remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
  9. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. *
  11. */
  12. #include <DynamicMaterialTestComponent.h>
  13. #include <SampleComponentManager.h>
  14. #include <SampleComponentConfig.h>
  15. #include <Automation/ScriptableImGui.h>
  16. #include <Automation/ScriptRunnerBus.h>
  17. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  18. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  19. #include <Atom/RPI.Reflect/Material/MaterialPropertiesLayout.h>
  20. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  21. #include <AzCore/Component/Entity.h>
  22. #include <AzCore/Debug/EventTrace.h>
  23. #include <AzCore/Math/Random.h>
  24. #include <RHI/BasicRHIComponent.h>
  25. namespace AtomSampleViewer
  26. {
  27. using namespace AZ;
  28. using namespace RPI;
  29. void DynamicMaterialTestComponent::Reflect(ReflectContext* context)
  30. {
  31. if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context))
  32. {
  33. serializeContext->Class<DynamicMaterialTestComponent, EntityLatticeTestComponent>()
  34. ->Version(0)
  35. ;
  36. }
  37. }
  38. DynamicMaterialTestComponent::DynamicMaterialTestComponent()
  39. : m_imguiSidebar("@user@/DynamicMaterialTestComponent/sidebar.xml")
  40. , m_compileTimer(CompileTimerQueueSize, CompileTimerQueueSize)
  41. {
  42. }
  43. void DynamicMaterialTestComponent::Activate()
  44. {
  45. TickBus::Handler::BusConnect();
  46. m_imguiSidebar.Activate();
  47. InitMaterialConfigs();
  48. Base::Activate();
  49. m_currentTime = 0.0f;
  50. }
  51. void DynamicMaterialTestComponent::Deactivate()
  52. {
  53. TickBus::Handler::BusDisconnect();
  54. m_imguiSidebar.Deactivate();
  55. Base::Deactivate();
  56. }
  57. void DynamicMaterialTestComponent::PrepareCreateLatticeInstances(uint32_t instanceCount)
  58. {
  59. const char* modelPath = "objects/shaderball_simple.azmodel";
  60. Data::AssetId modelAssetId;
  61. Data::AssetCatalogRequestBus::BroadcastResult(
  62. modelAssetId, &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath,
  63. modelPath, azrtti_typeid<ModelAsset>(), false);
  64. AZ_Assert(modelAssetId.IsValid(), "Failed to get model asset id: %s", modelPath);
  65. m_modelAsset.Create(modelAssetId);
  66. m_meshHandles.reserve(instanceCount);
  67. m_materials.reserve(instanceCount);
  68. // Give the models time to load before continuing scripts
  69. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  70. m_waitingForMeshes = true;
  71. }
  72. void DynamicMaterialTestComponent::CreateLatticeInstance(const Transform& transform)
  73. {
  74. AZ::Data::Asset<AZ::RPI::MaterialAsset>& materialAsset = m_materialConfigs[m_currentMaterialConfig].m_materialAsset;
  75. AZ::Data::Instance<AZ::RPI::Material> material = Material::Create(materialAsset);
  76. Render::MaterialAssignmentMap materialMap;
  77. Render::MaterialAssignment& defaultMaterial = materialMap[Render::DefaultMaterialAssignmentId];
  78. defaultMaterial.m_materialAsset = materialAsset;
  79. defaultMaterial.m_materialInstance = material;
  80. auto meshHandle = GetMeshFeatureProcessor()->AcquireMesh(m_modelAsset, materialMap, false, false);
  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& meshHandle = m_meshHandles[i];
  144. auto& material = m_materials[i];
  145. static const float CylesPerSecond = 0.5f;
  146. const float t = aznumeric_cast<float>(sin(m_currentTime * CylesPerSecond * AZ::Constants::TwoPi) * 0.5f + 0.5f);
  147. const int colorIndexA = random.GetRandom() % AZ_ARRAY_SIZE(colorOptions);
  148. int colorIndexB = colorIndexA;
  149. while (colorIndexA == colorIndexB)
  150. {
  151. colorIndexB = random.GetRandom() % AZ_ARRAY_SIZE(colorOptions);
  152. }
  153. const Color color = colorOptions[colorIndexA] * t + colorOptions[colorIndexB] * (1.0f - t);
  154. MaterialPropertyIndex colorProperty = material->FindPropertyIndex(AZ::Name{"baseColor.color"});
  155. material->SetPropertyValue(colorProperty, color);
  156. }
  157. }
  158. void DynamicMaterialTestComponent::UpdateEmissiveMaterialIntensity()
  159. {
  160. for (int i = 0; i < m_meshHandles.size(); ++i)
  161. {
  162. auto& meshHandle = m_meshHandles[i];
  163. auto& material = m_materials[i];
  164. const float distance = GetMeshFeatureProcessor()->GetTransform(meshHandle).GetTranslation().GetLengthEstimate();
  165. static const float DistanceScale = 0.02f;
  166. static const float CylesPerSecond = 0.5f;
  167. const float t = aznumeric_cast<float>(sin((DistanceScale * distance + m_currentTime * CylesPerSecond) * AZ::Constants::TwoPi) * 0.5f + 0.5f);
  168. static const float MinIntensity = 1.0f;
  169. static const float MaxIntensity = 4.0f;
  170. const float intensity = AZ::Lerp(MinIntensity, MaxIntensity, t);
  171. MaterialPropertyIndex intensityProperty = material->FindPropertyIndex(AZ::Name{"emissive.intensity"});
  172. material->SetPropertyValue(intensityProperty, intensity);
  173. }
  174. }
  175. void DynamicMaterialTestComponent::CompileMaterials()
  176. {
  177. AZ::Debug::Timer timer;
  178. timer.Stamp();
  179. for (auto& material : m_materials)
  180. {
  181. material->Compile();
  182. }
  183. m_compileTimer.PushValue(timer.GetDeltaTimeInSeconds() * 1'000'000);
  184. }
  185. void DynamicMaterialTestComponent::OnTick(float deltaTime, ScriptTimePoint /*scriptTime*/)
  186. {
  187. AZ_TRACE_METHOD();
  188. if (m_waitingForMeshes)
  189. {
  190. if(m_loadedMeshCounter == m_meshHandles.size())
  191. {
  192. m_waitingForMeshes = false;
  193. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  194. // Reset the clock so we get consistent animation for scripts
  195. m_currentTime = 0;
  196. }
  197. }
  198. AZ_Assert(m_loadedMeshCounter <= m_meshHandles.size(), "Mesh load handlers were called multiple times?");
  199. bool updateMaterials = false;
  200. if (!m_pause)
  201. {
  202. m_currentTime += deltaTime;
  203. updateMaterials = true;
  204. }
  205. if (m_imguiSidebar.Begin())
  206. {
  207. RenderImGuiLatticeControls();
  208. ImGui::Separator();
  209. bool configChanged = false;
  210. for (int i = 0; i < m_materialConfigs.size(); ++i)
  211. {
  212. configChanged = configChanged || ScriptableImGui::RadioButton(m_materialConfigs[i].m_name.c_str(), &m_currentMaterialConfig, i);
  213. }
  214. if (configChanged)
  215. {
  216. RebuildLattice();
  217. }
  218. ImGui::Separator();
  219. ScriptableImGui::Checkbox("Pause", &m_pause);
  220. if (ScriptableImGui::Button("Reset Clock"))
  221. {
  222. m_currentTime = 0;
  223. updateMaterials = true;
  224. }
  225. ImGui::Separator();
  226. ImGui::Text("%d unique objects", aznumeric_cast<int32_t>(m_meshHandles.size()));
  227. ImGui::Text("Total Material Compile Time:");
  228. ImGuiHistogramQueue::WidgetSettings settings;
  229. settings.m_units = "microseconds";
  230. m_compileTimer.Tick(deltaTime, settings);
  231. ImGui::Text("Average per Material: %4.2f", m_compileTimer.GetDisplayedAverage() / m_materials.size());
  232. ImGui::Separator();
  233. m_imguiSidebar.End();
  234. }
  235. if (updateMaterials)
  236. {
  237. m_materialConfigs[m_currentMaterialConfig].m_updateLatticeMaterials();
  238. CompileMaterials();
  239. }
  240. }
  241. } // namespace AtomSampleViewer