MaterialConverterSystemComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 "MaterialConverterSystemComponent.h"
  9. #include <AssetBuilderSDK/AssetBuilderSDK.h>
  10. #include <AzCore/Math/Color.h>
  11. #include <AzCore/Serialization/EditContext.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <AzCore/Settings/SettingsRegistry.h>
  14. #include <AzToolsFramework/API/EditorAssetSystemAPI.h>
  15. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  16. #include <Atom/RPI.Edit/Material/MaterialUtils.h>
  17. namespace AZ
  18. {
  19. namespace Render
  20. {
  21. void MaterialConverterSettings::Reflect(AZ::ReflectContext* context)
  22. {
  23. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  24. {
  25. serializeContext->Class<MaterialConverterSettings>()
  26. // If new settings are added here, be sure to update MaterialConverterSystemComponent::GetFingerprintInfo() as well.
  27. ->Version(2)
  28. ->Field("Enable", &MaterialConverterSettings::m_enable)
  29. ->Field("DefaultMaterial", &MaterialConverterSettings::m_defaultMaterial);
  30. }
  31. }
  32. void MaterialConverterSystemComponent::Reflect(AZ::ReflectContext* context)
  33. {
  34. if (auto* serialize = azrtti_cast<SerializeContext*>(context))
  35. {
  36. serialize->Class<MaterialConverterSystemComponent, Component>()
  37. // If changes are made to the material conversion process, update the version number in
  38. // MaterialConverterSystemComponent::GetFingerprintInfo(), not this one.
  39. ->Version(3)
  40. ->Attribute(Edit::Attributes::SystemComponentTags, AZStd::vector<Crc32>({ AssetBuilderSDK::ComponentTags::AssetBuilder }));
  41. }
  42. MaterialConverterSettings::Reflect(context);
  43. }
  44. void MaterialConverterSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  45. {
  46. services.emplace_back(AZ_CRC_CE("FingerprintModification"));
  47. }
  48. void MaterialConverterSystemComponent::Activate()
  49. {
  50. if (auto* settingsRegistry = AZ::SettingsRegistry::Get())
  51. {
  52. settingsRegistry->GetObject(m_settings, "/O3DE/SceneAPI/MaterialConverter");
  53. }
  54. RPI::MaterialConverterBus::Handler::BusConnect();
  55. }
  56. void MaterialConverterSystemComponent::Deactivate()
  57. {
  58. RPI::MaterialConverterBus::Handler::BusDisconnect();
  59. }
  60. bool MaterialConverterSystemComponent::IsEnabled() const
  61. {
  62. return m_settings.m_enable;
  63. }
  64. AZStd::string MaterialConverterSystemComponent::GetFingerprintInfo() const
  65. {
  66. static constexpr int Version = 2; // Bump this version whenever changes are made to the material conversion code to force the AP to reprocess scene files
  67. AZStd::string fingerprintInfo = AZStd::string::format("[MaterialConverter version=%d enabled=%d", Version, IsEnabled());
  68. if (!IsEnabled())
  69. {
  70. fingerprintInfo += AZStd::string::format(" defaultMaterial=%s", GetDefaultMaterialPath().c_str());
  71. }
  72. fingerprintInfo += "]";
  73. return fingerprintInfo;
  74. }
  75. bool MaterialConverterSystemComponent::ConvertMaterial(
  76. const AZ::SceneAPI::DataTypes::IMaterialData& materialData, RPI::MaterialSourceData& sourceData)
  77. {
  78. using namespace AZ::RPI;
  79. if (!m_settings.m_enable)
  80. {
  81. return false;
  82. }
  83. // The source data for generating material asset
  84. sourceData.m_materialType = GetMaterialTypePath();
  85. auto handleTexture = [&materialData, &sourceData](const char* propertyTextureGroup, const char* propertyTextureName, SceneAPI::DataTypes::IMaterialData::TextureMapType textureType)
  86. {
  87. const AZStd::string& texturePath = materialData.GetTexture(textureType);
  88. // Check to see if the image asset exists. If not, skip this texture map and just disable it.
  89. bool assetFound = false;
  90. if (!texturePath.empty())
  91. {
  92. using namespace AzToolsFramework;
  93. AZ::Data::AssetInfo sourceInfo;
  94. AZStd::string watchFolder;
  95. AssetSystemRequestBus::BroadcastResult(
  96. assetFound, &AssetSystem::AssetSystemRequest::GetSourceInfoBySourcePath, texturePath.c_str(), sourceInfo,
  97. watchFolder);
  98. }
  99. if (assetFound)
  100. {
  101. sourceData.SetPropertyValue(MaterialPropertyId{propertyTextureGroup, propertyTextureName}, texturePath);
  102. }
  103. else if (!texturePath.empty())
  104. {
  105. AZ_Warning("AtomFeatureCommon", false, "Could not find asset '%s' for '%s'", texturePath.c_str(), propertyTextureGroup);
  106. }
  107. };
  108. // If PBR material properties aren't in use, fall back to legacy properties. Don't do that if some PBR material properties are set, though.
  109. bool anyPBRInUse = false;
  110. handleTexture("specularF0", "textureMap", SceneAPI::DataTypes::IMaterialData::TextureMapType::Specular);
  111. handleTexture("normal", "textureMap", SceneAPI::DataTypes::IMaterialData::TextureMapType::Normal);
  112. AZStd::optional<bool> useColorMap = materialData.GetUseColorMap();
  113. // If the useColorMap property exists, this is a PBR material and the color should be set to baseColor.
  114. if (useColorMap.has_value())
  115. {
  116. anyPBRInUse = true;
  117. handleTexture("baseColor", "textureMap", SceneAPI::DataTypes::IMaterialData::TextureMapType::BaseColor);
  118. sourceData.SetPropertyValue(Name{"baseColor.textureBlendMode"}, AZStd::string("Lerp"));
  119. }
  120. else
  121. {
  122. // If it doesn't have the useColorMap property, then it's a non-PBR material and the baseColor
  123. // texture needs to be set to the diffuse texture.
  124. handleTexture("baseColor", "textureMap", SceneAPI::DataTypes::IMaterialData::TextureMapType::Diffuse);
  125. }
  126. auto toColor = [](const AZ::Vector3& v) { return AZ::Color::CreateFromVector3AndFloat(v, 1.0f); };
  127. AZStd::optional<AZ::Vector3> baseColor = materialData.GetBaseColor();
  128. if (baseColor.has_value())
  129. {
  130. anyPBRInUse = true;
  131. sourceData.SetPropertyValue(Name{"baseColor.color"}, toColor(baseColor.value()));
  132. }
  133. sourceData.SetPropertyValue(Name{"opacity.factor"}, materialData.GetOpacity());
  134. if (1.0f - materialData.GetOpacity() > AZ::Constants::FloatEpsilon)
  135. {
  136. sourceData.SetPropertyValue(Name{ "opacity.mode" }, AZStd::string("Blended"));
  137. }
  138. auto applyOptionalPropertiesFunc = [&sourceData, &anyPBRInUse](const auto& propertyGroup, const auto& propertyName, const auto& propertyOptional)
  139. {
  140. // Only set PBR settings if they were specifically set in the scene's data.
  141. // Otherwise, leave them unset so the data driven default properties are used.
  142. if (propertyOptional.has_value())
  143. {
  144. anyPBRInUse = true;
  145. sourceData.SetPropertyValue(MaterialPropertyId{propertyGroup, propertyName}, propertyOptional.value());
  146. }
  147. };
  148. handleTexture("metallic", "textureMap", SceneAPI::DataTypes::IMaterialData::TextureMapType::Metallic);
  149. applyOptionalPropertiesFunc("metallic", "factor", materialData.GetMetallicFactor());
  150. applyOptionalPropertiesFunc("metallic", "useTexture", materialData.GetUseMetallicMap());
  151. handleTexture("roughness", "textureMap", SceneAPI::DataTypes::IMaterialData::TextureMapType::Roughness);
  152. applyOptionalPropertiesFunc("roughness", "useTexture", materialData.GetUseRoughnessMap());
  153. // Both PBR material and non-PBR material can have the RoughnessFactor property
  154. AZStd::optional<float> roughness = materialData.GetRoughnessFactor();
  155. if (roughness.has_value())
  156. {
  157. sourceData.SetPropertyValue(Name{"roughness.factor"}, roughness.value());
  158. }
  159. else if (materialData.GetShininess() > AZ::Constants::FloatEpsilon)
  160. {
  161. // When the MaterialData provides Shininess instead of Roughness, it is necessary to convert Shininess to Roughness.
  162. // Normalized Blinn-Phong: D_p(m)=((alpha_p+2)/(2*PI))dot(n, m)^alpha_p, Usually use formula: alpha_p=2*alpha^-2 - 2,
  163. // alpha = roughness^2
  164. sourceData.SetPropertyValue(
  165. Name{ "roughness.factor" }, aznumeric_cast<float>(pow(2.0f / (materialData.GetShininess() + 2.0f), 0.25)));
  166. }
  167. handleTexture("emissive", "textureMap", SceneAPI::DataTypes::IMaterialData::TextureMapType::Emissive);
  168. sourceData.SetPropertyValue(Name{"emissive.color"}, toColor(materialData.GetEmissiveColor()));
  169. applyOptionalPropertiesFunc("emissive", "intensity", materialData.GetEmissiveIntensity());
  170. applyOptionalPropertiesFunc("emissive", "useTexture", materialData.GetUseEmissiveMap());
  171. handleTexture("occlusion", "diffuseTextureMap", SceneAPI::DataTypes::IMaterialData::TextureMapType::AmbientOcclusion);
  172. applyOptionalPropertiesFunc("occlusion", "diffuseUseTexture", materialData.GetUseAOMap());
  173. if (!anyPBRInUse)
  174. {
  175. // If it doesn't have the useColorMap property, then it's a non-PBR material and the baseColor
  176. // texture needs to be set to the diffuse color.
  177. sourceData.SetPropertyValue(Name{"baseColor.color"}, toColor(materialData.GetDiffuseColor()));
  178. }
  179. return true;
  180. }
  181. AZStd::string MaterialConverterSystemComponent::GetMaterialTypePath() const
  182. {
  183. return AZ::RPI::MaterialUtils::PredictIntermediateMaterialTypeSourcePath("Materials/Types/StandardPBR.materialtype");
  184. }
  185. AZStd::string MaterialConverterSystemComponent::GetDefaultMaterialPath() const
  186. {
  187. if (m_settings.m_defaultMaterial.empty())
  188. {
  189. AZ_Error("MaterialConverterSystemComponent", m_settings.m_enable,
  190. "Material conversion is disabled but a default material not specified in registry /O3DE/SceneAPI/MaterialConverter/DefaultMaterial");
  191. }
  192. return m_settings.m_defaultMaterial;
  193. }
  194. }
  195. }