GLTFMaterial.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Threading.Tasks;
  5. using Newtonsoft.Json;
  6. using Siccity.GLTFUtility.Converters;
  7. using UnityEngine;
  8. using UnityEngine.Rendering;
  9. using UnityEngine.Scripting;
  10. using Newtonsoft.Json.Linq;
  11. namespace Siccity.GLTFUtility {
  12. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#material
  13. [Preserve] public class GLTFMaterial {
  14. #if UNITY_EDITOR
  15. public static Material defaultMaterial { get { return _defaultMaterial != null ? _defaultMaterial : _defaultMaterial = UnityEditor.AssetDatabase.GetBuiltinExtraResource<Material>("Default-Material.mat"); } }
  16. private static Material _defaultMaterial;
  17. #else
  18. public static Material defaultMaterial { get { return null; } }
  19. #endif
  20. public string name;
  21. public PbrMetalRoughness pbrMetallicRoughness;
  22. public TextureInfo normalTexture;
  23. public TextureInfo occlusionTexture;
  24. public TextureInfo emissiveTexture;
  25. [JsonConverter(typeof(ColorRGBConverter))] public Color emissiveFactor = Color.black;
  26. [JsonConverter(typeof(EnumConverter))] public AlphaMode alphaMode = AlphaMode.OPAQUE;
  27. public float alphaCutoff = 0.5f;
  28. public bool doubleSided = false;
  29. public Extensions extensions;
  30. public JObject extras;
  31. public class ImportResult {
  32. public Material material;
  33. }
  34. public IEnumerator CreateMaterial(GLTFTexture.ImportResult[] textures, ShaderSettings shaderSettings, Action<Material> onFinish) {
  35. Material mat = null;
  36. IEnumerator en = null;
  37. // Load metallic-roughness materials
  38. if (pbrMetallicRoughness != null) {
  39. en = pbrMetallicRoughness.CreateMaterial(textures, alphaMode, shaderSettings, x => mat = x);
  40. while (en.MoveNext()) { yield return null; };
  41. }
  42. // Load specular-glossiness materials
  43. else if (extensions != null && extensions.KHR_materials_pbrSpecularGlossiness != null) {
  44. en = extensions.KHR_materials_pbrSpecularGlossiness.CreateMaterial(textures, alphaMode, shaderSettings, x => mat = x);
  45. while (en.MoveNext()) { yield return null; };
  46. }
  47. // Load fallback material
  48. else mat = new Material(Shader.Find("Standard"));
  49. // Normal texture
  50. if (normalTexture != null) {
  51. en = TryGetTexture(textures, normalTexture, true, tex => {
  52. if (tex != null) {
  53. mat.SetTexture("_BumpMap", tex);
  54. mat.EnableKeyword("_NORMALMAP");
  55. mat.SetFloat("_BumpScale", normalTexture.scale);
  56. if (normalTexture.extensions != null) {
  57. normalTexture.extensions.Apply(normalTexture, mat, "_BumpMap");
  58. }
  59. }
  60. });
  61. while (en.MoveNext()) { yield return null; };
  62. }
  63. // Occlusion texture
  64. if (occlusionTexture != null) {
  65. en = TryGetTexture(textures, occlusionTexture, true, tex => {
  66. if (tex != null) {
  67. mat.SetTexture("_OcclusionMap", tex);
  68. if (occlusionTexture.extensions != null) {
  69. occlusionTexture.extensions.Apply(occlusionTexture, mat, "_OcclusionMap");
  70. }
  71. }
  72. });
  73. while (en.MoveNext()) { yield return null; };
  74. }
  75. // Emissive factor
  76. if (emissiveFactor != Color.black) {
  77. mat.SetColor("_EmissionColor", emissiveFactor);
  78. mat.EnableKeyword("_EMISSION");
  79. }
  80. // Emissive texture
  81. if (emissiveTexture != null) {
  82. en = TryGetTexture(textures, emissiveTexture, false, tex => {
  83. if (tex != null) {
  84. mat.SetTexture("_EmissionMap", tex);
  85. mat.EnableKeyword("_EMISSION");
  86. if (emissiveTexture.extensions != null) {
  87. emissiveTexture.extensions.Apply(emissiveTexture, mat, "_EmissionMap");
  88. }
  89. }
  90. });
  91. while (en.MoveNext()) { yield return null; };
  92. }
  93. if (alphaMode == AlphaMode.MASK) {
  94. mat.SetFloat("_AlphaCutoff", alphaCutoff);
  95. }
  96. mat.name = name;
  97. onFinish(mat);
  98. }
  99. public static IEnumerator TryGetTexture(GLTFTexture.ImportResult[] textures, TextureInfo texture, bool linear, Action<Texture2D> onFinish, Action<float> onProgress = null) {
  100. if (texture == null || texture.index < 0) {
  101. if (onProgress != null) onProgress(1f);
  102. onFinish(null);
  103. }
  104. if (textures == null) {
  105. if (onProgress != null) onProgress(1f);
  106. onFinish(null);
  107. }
  108. if (textures.Length <= texture.index) {
  109. Debug.LogWarning("Attempted to get texture index " + texture.index + " when only " + textures.Length + " exist");
  110. if (onProgress != null) onProgress(1f);
  111. onFinish(null);
  112. }
  113. IEnumerator en = textures[texture.index].GetTextureCached(linear, onFinish, onProgress);
  114. while (en.MoveNext()) { yield return null; };
  115. }
  116. [Preserve] public class Extensions {
  117. public PbrSpecularGlossiness KHR_materials_pbrSpecularGlossiness = null;
  118. }
  119. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#pbrmetallicroughness
  120. [Preserve] public class PbrMetalRoughness {
  121. [JsonConverter(typeof(ColorRGBAConverter))] public Color baseColorFactor = Color.white;
  122. public TextureInfo baseColorTexture;
  123. public float metallicFactor = 1f;
  124. public float roughnessFactor = 1f;
  125. public TextureInfo metallicRoughnessTexture;
  126. public IEnumerator CreateMaterial(GLTFTexture.ImportResult[] textures, AlphaMode alphaMode, ShaderSettings shaderSettings, Action<Material> onFinish) {
  127. // Shader
  128. Shader sh = null;
  129. if (alphaMode == AlphaMode.BLEND) sh = shaderSettings.MetallicBlend;
  130. else sh = shaderSettings.Metallic;
  131. // Material
  132. Material mat = new Material(sh);
  133. mat.color = baseColorFactor;
  134. mat.SetFloat("_Metallic", metallicFactor);
  135. mat.SetFloat("_Roughness", roughnessFactor);
  136. // Assign textures
  137. if (textures != null) {
  138. // Base color texture
  139. if (baseColorTexture != null && baseColorTexture.index >= 0) {
  140. if (textures.Length <= baseColorTexture.index) {
  141. Debug.LogWarning("Attempted to get basecolor texture index " + baseColorTexture.index + " when only " + textures.Length + " exist");
  142. } else {
  143. IEnumerator en = textures[baseColorTexture.index].GetTextureCached(false, tex => {
  144. if (tex != null) {
  145. mat.SetTexture("_MainTex", tex);
  146. if (baseColorTexture.extensions != null) {
  147. baseColorTexture.extensions.Apply(baseColorTexture, mat, "_MainTex");
  148. }
  149. }
  150. });
  151. while (en.MoveNext()) { yield return null; };
  152. }
  153. }
  154. // Metallic roughness texture
  155. if (metallicRoughnessTexture != null && metallicRoughnessTexture.index >= 0) {
  156. if (textures.Length <= metallicRoughnessTexture.index) {
  157. Debug.LogWarning("Attempted to get metallicRoughness texture index " + metallicRoughnessTexture.index + " when only " + textures.Length + " exist");
  158. } else {
  159. IEnumerator en = TryGetTexture(textures, metallicRoughnessTexture, true, tex => {
  160. if (tex != null) {
  161. mat.SetTexture("_MetallicGlossMap", tex);
  162. mat.EnableKeyword("_METALLICGLOSSMAP");
  163. if (metallicRoughnessTexture.extensions != null) {
  164. metallicRoughnessTexture.extensions.Apply(metallicRoughnessTexture, mat, "_MetallicGlossMap");
  165. }
  166. }
  167. });
  168. while (en.MoveNext()) { yield return null; };
  169. }
  170. }
  171. }
  172. // After the texture and color is extracted from the glTFObject
  173. if (mat.HasProperty("_BaseMap")) mat.SetTexture("_BaseMap", mat.mainTexture);
  174. if (mat.HasProperty("_BaseColor")) mat.SetColor("_BaseColor", baseColorFactor);
  175. onFinish(mat);
  176. }
  177. }
  178. [Preserve] public class PbrSpecularGlossiness {
  179. /// <summary> The reflected diffuse factor of the material </summary>
  180. [JsonConverter(typeof(ColorRGBAConverter))] public Color diffuseFactor = Color.white;
  181. /// <summary> The diffuse texture </summary>
  182. public TextureInfo diffuseTexture;
  183. /// <summary> The reflected diffuse factor of the material </summary>
  184. [JsonConverter(typeof(ColorRGBConverter))] public Color specularFactor = Color.white;
  185. /// <summary> The glossiness or smoothness of the material </summary>
  186. public float glossinessFactor = 1f;
  187. /// <summary> The specular-glossiness texture </summary>
  188. public TextureInfo specularGlossinessTexture;
  189. public IEnumerator CreateMaterial(GLTFTexture.ImportResult[] textures, AlphaMode alphaMode, ShaderSettings shaderSettings, Action<Material> onFinish) {
  190. // Shader
  191. Shader sh = null;
  192. if (alphaMode == AlphaMode.BLEND) sh = shaderSettings.SpecularBlend;
  193. else sh = shaderSettings.Specular;
  194. // Material
  195. Material mat = new Material(sh);
  196. mat.color = diffuseFactor;
  197. mat.SetColor("_SpecColor", specularFactor);
  198. mat.SetFloat("_GlossyReflections", glossinessFactor);
  199. // Assign textures
  200. if (textures != null) {
  201. // Diffuse texture
  202. if (diffuseTexture != null) {
  203. if (textures.Length <= diffuseTexture.index) {
  204. Debug.LogWarning("Attempted to get diffuseTexture texture index " + diffuseTexture.index + " when only " + textures.Length + " exist");
  205. } else {
  206. IEnumerator en = textures[diffuseTexture.index].GetTextureCached(false, tex => {
  207. if (tex != null) {
  208. mat.SetTexture("_MainTex", tex);
  209. if (diffuseTexture.extensions != null) {
  210. diffuseTexture.extensions.Apply(diffuseTexture, mat, "_MainTex");
  211. }
  212. }
  213. });
  214. while (en.MoveNext()) { yield return null; };
  215. }
  216. }
  217. // Specular texture
  218. if (specularGlossinessTexture != null) {
  219. if (textures.Length <= specularGlossinessTexture.index) {
  220. Debug.LogWarning("Attempted to get specularGlossinessTexture texture index " + specularGlossinessTexture.index + " when only " + textures.Length + " exist");
  221. } else {
  222. mat.EnableKeyword("_SPECGLOSSMAP");
  223. IEnumerator en = textures[specularGlossinessTexture.index].GetTextureCached(false, tex => {
  224. if (tex != null) {
  225. mat.SetTexture("_SpecGlossMap", tex);
  226. mat.EnableKeyword("_SPECGLOSSMAP");
  227. if (specularGlossinessTexture.extensions != null) {
  228. specularGlossinessTexture.extensions.Apply(specularGlossinessTexture, mat, "_SpecGlossMap");
  229. }
  230. }
  231. });
  232. while (en.MoveNext()) { yield return null; };
  233. }
  234. }
  235. }
  236. onFinish(mat);
  237. }
  238. }
  239. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#normaltextureinfo
  240. [Preserve] public class TextureInfo {
  241. [JsonProperty(Required = Required.Always)] public int index;
  242. public int texCoord = 0;
  243. public float scale = 1;
  244. public Extensions extensions;
  245. [Preserve] public class Extensions {
  246. public KHR_texture_transform KHR_texture_transform;
  247. public void Apply(GLTFMaterial.TextureInfo texInfo, Material material, string textureSamplerName) {
  248. // TODO: check if GLTFObject has extensionUsed/extensionRequired for these extensions
  249. if (KHR_texture_transform != null) {
  250. KHR_texture_transform.Apply(texInfo, material, textureSamplerName);
  251. }
  252. }
  253. }
  254. public interface IExtension {
  255. void Apply(GLTFMaterial.TextureInfo texInfo, Material material, string textureSamplerName);
  256. }
  257. }
  258. public class ImportTask : Importer.ImportTask<ImportResult[]> {
  259. private List<GLTFMaterial> materials;
  260. private GLTFTexture.ImportTask textureTask;
  261. private ImportSettings importSettings;
  262. public ImportTask(List<GLTFMaterial> materials, GLTFTexture.ImportTask textureTask, ImportSettings importSettings) : base(textureTask) {
  263. this.materials = materials;
  264. this.textureTask = textureTask;
  265. this.importSettings = importSettings;
  266. task = new Task(() => {
  267. if (materials == null) return;
  268. Result = new ImportResult[materials.Count];
  269. });
  270. }
  271. public override IEnumerator OnCoroutine(Action<float> onProgress = null) {
  272. // No materials
  273. if (materials == null) {
  274. if (onProgress != null) onProgress.Invoke(1f);
  275. IsCompleted = true;
  276. yield break;
  277. }
  278. for (int i = 0; i < Result.Length; i++) {
  279. Result[i] = new ImportResult();
  280. IEnumerator en = materials[i].CreateMaterial(textureTask.Result, importSettings.shaderOverrides, x => Result[i].material = x);
  281. while (en.MoveNext()) { yield return null; };
  282. if (Result[i].material.name == null) Result[i].material.name = "material" + i;
  283. if (onProgress != null) onProgress.Invoke((float) (i + 1) / (float) Result.Length);
  284. yield return null;
  285. }
  286. IsCompleted = true;
  287. }
  288. }
  289. }
  290. }