MaterialAsset.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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.Reflect/Material/MaterialAsset.h>
  9. #include <Atom/RPI.Reflect/Material/MaterialPropertiesLayout.h>
  10. #include <Atom/RPI.Reflect/Material/MaterialFunctor.h>
  11. #include <Atom/RPI.Reflect/Material/MaterialVersionUpdate.h>
  12. #include <Atom/RPI.Reflect/Asset/AssetHandler.h>
  13. #include <Atom/RPI.Public/Shader/ShaderReloadDebugTracker.h>
  14. #include <AzCore/Asset/AssetSerializer.h>
  15. #include <AzCore/Serialization/SerializeContext.h>
  16. #include <AzCore/RTTI/BehaviorContext.h>
  17. #include <AzCore/Component/TickBus.h>
  18. namespace AZ
  19. {
  20. namespace RPI
  21. {
  22. void MaterialAsset::Reflect(ReflectContext* context)
  23. {
  24. if (auto* serializeContext = azrtti_cast<SerializeContext*>(context))
  25. {
  26. serializeContext->Class<MaterialAsset, AZ::Data::AssetData>()
  27. ->Version(15) // Forcing materials to be fully baked by builder
  28. ->Field("materialTypeAsset", &MaterialAsset::m_materialTypeAsset)
  29. ->Field("materialTypeVersion", &MaterialAsset::m_materialTypeVersion)
  30. ->Field("propertyValues", &MaterialAsset::m_propertyValues)
  31. ;
  32. }
  33. }
  34. MaterialAsset::MaterialAsset()
  35. {
  36. }
  37. MaterialAsset::~MaterialAsset()
  38. {
  39. AssetInitBus::Handler::BusDisconnect();
  40. }
  41. bool MaterialAsset::InitializeNonSerializedData()
  42. {
  43. if (m_isNonSerializedDataInitialized)
  44. {
  45. return true;
  46. }
  47. if (!m_materialTypeAsset.IsReady())
  48. {
  49. return false;
  50. }
  51. m_isNonSerializedDataInitialized = m_materialTypeAsset->InitializeNonSerializedData();
  52. return m_isNonSerializedDataInitialized;
  53. }
  54. const Data::Asset<MaterialTypeAsset>& MaterialAsset::GetMaterialTypeAsset() const
  55. {
  56. return m_materialTypeAsset;
  57. }
  58. const ShaderCollection& MaterialAsset::GetGeneralShaderCollection() const
  59. {
  60. return m_materialTypeAsset->GetGeneralShaderCollection();
  61. }
  62. const MaterialFunctorList& MaterialAsset::GetMaterialFunctors() const
  63. {
  64. return m_materialTypeAsset->GetMaterialFunctors();
  65. }
  66. const MaterialTypeAsset::MaterialPipelineMap& MaterialAsset::GetMaterialPipelinePayloads() const
  67. {
  68. return m_materialTypeAsset->GetMaterialPipelinePayloads();
  69. }
  70. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetMaterialSrgLayout(const SupervariantIndex& supervariantIndex) const
  71. {
  72. return m_materialTypeAsset->GetMaterialSrgLayout(supervariantIndex);
  73. }
  74. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetMaterialSrgLayout(const AZ::Name& supervariantName) const
  75. {
  76. return m_materialTypeAsset->GetMaterialSrgLayout(supervariantName);
  77. }
  78. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetMaterialSrgLayout() const
  79. {
  80. return m_materialTypeAsset->GetMaterialSrgLayout();
  81. }
  82. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetObjectSrgLayout(const SupervariantIndex& supervariantIndex) const
  83. {
  84. return m_materialTypeAsset->GetObjectSrgLayout(supervariantIndex);
  85. }
  86. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetObjectSrgLayout(const AZ::Name& supervariantName) const
  87. {
  88. return m_materialTypeAsset->GetObjectSrgLayout(supervariantName);
  89. }
  90. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetObjectSrgLayout() const
  91. {
  92. return m_materialTypeAsset->GetObjectSrgLayout();
  93. }
  94. const MaterialPropertiesLayout* MaterialAsset::GetMaterialPropertiesLayout() const
  95. {
  96. return m_materialTypeAsset->GetMaterialPropertiesLayout();
  97. }
  98. void MaterialAsset::Finalize(AZStd::function<void(const char*)> reportWarning, AZStd::function<void(const char*)> reportError)
  99. {
  100. if (!reportWarning)
  101. {
  102. reportWarning = []([[maybe_unused]] const char* message)
  103. {
  104. AZ_Warning(s_debugTraceName, false, "%s", message);
  105. };
  106. }
  107. if (!reportError)
  108. {
  109. reportError = []([[maybe_unused]] const char* message)
  110. {
  111. AZ_Error(s_debugTraceName, false, "%s", message);
  112. };
  113. }
  114. // It is possible that the material type has had some properties renamed or otherwise updated. If that's the case,
  115. // and this material is still referencing the old property layout, we need to apply any auto updates to rename those
  116. // properties before using them to realign the property values.
  117. ApplyVersionUpdates(reportError);
  118. const MaterialPropertiesLayout* propertyLayout = GetMaterialPropertiesLayout();
  119. AZStd::vector<MaterialPropertyValue> finalizedPropertyValues(m_materialTypeAsset->GetDefaultPropertyValues().begin(), m_materialTypeAsset->GetDefaultPropertyValues().end());
  120. for (const auto& [name, value] : m_rawPropertyValues)
  121. {
  122. const MaterialPropertyIndex propertyIndex = propertyLayout->FindPropertyIndex(name);
  123. if (propertyIndex.IsValid())
  124. {
  125. const MaterialPropertyDescriptor* propertyDescriptor = propertyLayout->GetPropertyDescriptor(propertyIndex);
  126. if (value.Is<AZStd::string>() && propertyDescriptor->GetDataType() == MaterialPropertyDataType::Enum)
  127. {
  128. AZ::Name enumName = AZ::Name(value.GetValue<AZStd::string>());
  129. uint32_t enumValue = propertyDescriptor->GetEnumValue(enumName);
  130. if (enumValue == MaterialPropertyDescriptor::InvalidEnumValue)
  131. {
  132. reportWarning(AZStd::string::format("Material property name \"%s\" has invalid enum value \"%s\".", name.GetCStr(), enumName.GetCStr()).c_str());
  133. }
  134. else
  135. {
  136. finalizedPropertyValues[propertyIndex.GetIndex()] = enumValue;
  137. }
  138. }
  139. else if (value.Is<AZStd::string>() && propertyDescriptor->GetDataType() == MaterialPropertyDataType::Image)
  140. {
  141. // Here we assume that the material asset builder resolved any image source file paths to an ImageAsset reference.
  142. // So the only way a string could be present is if it's an empty image path reference, meaning no image should be bound.
  143. AZ_Assert(value.GetValue<AZStd::string>().empty(), "Material property '%s' references in image '%s'. Image file paths must be resolved by the material asset builder.");
  144. finalizedPropertyValues[propertyIndex.GetIndex()] = Data::Asset<ImageAsset>{};
  145. }
  146. else
  147. {
  148. // The material asset could be finalized sometime after the original JSON is loaded, and the material type might not have been available
  149. // at that time, so the data type would not be known for each property. So each raw property's type was based on what appeared in the JSON
  150. // and here we have the first opportunity to resolve that value with the actual type. For example, a float property could have been specified in
  151. // the JSON as 7 instead of 7.0, which is valid. Similarly, a Color and a Vector3 can both be specified as "[0.0,0.0,0.0]" in the JSON file.
  152. MaterialPropertyValue finalValue = value.CastToType(propertyDescriptor->GetStorageDataTypeId());
  153. if (ValidateMaterialPropertyDataType(finalValue.GetTypeId(), propertyDescriptor, reportError))
  154. {
  155. finalizedPropertyValues[propertyIndex.GetIndex()] = finalValue;
  156. }
  157. }
  158. }
  159. else
  160. {
  161. reportWarning(AZStd::string::format("Material property name \"%s\" is not found in the material properties layout and will not be used.", name.GetCStr()).c_str());
  162. }
  163. }
  164. m_propertyValues.swap(finalizedPropertyValues);
  165. }
  166. const AZStd::vector<MaterialPropertyValue>& MaterialAsset::GetPropertyValues() const
  167. {
  168. AZ_Assert(GetMaterialPropertiesLayout() && m_propertyValues.size() == GetMaterialPropertiesLayout()->GetPropertyCount(), "MaterialAsset should be finalized but does not have the right number of property values.");
  169. return m_propertyValues;
  170. }
  171. void MaterialAsset::SetReady()
  172. {
  173. m_status = AssetStatus::Ready;
  174. PostLoadInit();
  175. }
  176. bool MaterialAsset::PostLoadInit()
  177. {
  178. AssetInitBus::Handler::BusDisconnect();
  179. // Any MaterialAsset with invalid MaterialTypeAsset is not a successfully-loaded asset.
  180. return m_materialTypeAsset.IsReady();
  181. }
  182. void MaterialAsset::ApplyVersionUpdates(AZStd::function<void(const char*)> reportError)
  183. {
  184. if (m_materialTypeVersion == m_materialTypeAsset->GetVersion())
  185. {
  186. return;
  187. }
  188. [[maybe_unused]] const uint32_t originalVersion = m_materialTypeVersion;
  189. [[maybe_unused]] bool changesWereApplied =
  190. m_materialTypeAsset->GetMaterialVersionUpdates().ApplyVersionUpdates(*this, reportError);
  191. #if AZ_ENABLE_TRACING
  192. if (changesWereApplied)
  193. {
  194. const AZStd::string versionString = (originalVersion == UnspecifiedMaterialTypeVersion) ?
  195. "<Unspecified>" : AZStd::string::format("'%u'", originalVersion);
  196. AZStd::string assetString = GetId().ToString<AZStd::string>().c_str();
  197. AZ::Data::AssetInfo assetInfo;
  198. AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetInfo,
  199. &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, GetId());
  200. if (assetInfo.m_assetId.IsValid())
  201. {
  202. assetString += " (" + assetInfo.m_relativePath + ")";
  203. }
  204. AZ_Warning(
  205. "MaterialAsset", false,
  206. "This material is based on version %s of %s, and the material type is now at version '%u'. "
  207. "Automatic updates have been applied. Consider updating the .material source file for %s.",
  208. versionString.c_str(), m_materialTypeAsset.ToString<AZStd::string>().c_str(),
  209. m_materialTypeAsset->GetVersion(), assetString.c_str());
  210. }
  211. #endif
  212. m_materialTypeVersion = m_materialTypeAsset->GetVersion();
  213. }
  214. Data::AssetHandler::LoadResult MaterialAssetHandler::LoadAssetData(
  215. const AZ::Data::Asset<AZ::Data::AssetData>& asset,
  216. AZStd::shared_ptr<AZ::Data::AssetDataStream> stream,
  217. const AZ::Data::AssetFilterCB& assetLoadFilterCB)
  218. {
  219. if (Base::LoadAssetData(asset, stream, assetLoadFilterCB) == Data::AssetHandler::LoadResult::LoadComplete)
  220. {
  221. asset.GetAs<MaterialAsset>()->AssetInitBus::Handler::BusConnect();
  222. return Data::AssetHandler::LoadResult::LoadComplete;
  223. }
  224. return Data::AssetHandler::LoadResult::Error;
  225. }
  226. } // namespace RPI
  227. } // namespace AZ