From 2edee1e7b5ea99c76491feef359d0d8cfa645999 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Wed, 10 Feb 2021 21:24:10 +0900 Subject: [PATCH 01/16] MaterialFactory.Dispose --- Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs | 9 +++++++-- .../Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs | 10 ++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index 12622452e..647601e35 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -939,9 +939,14 @@ namespace UniGLTF if (Root != null) GameObject.Destroy(Root); // Remove resources. materials, textures meshes etc... - foreach (var o in ObjectsForSubAsset()) + MaterialFactory.Dispose(); + foreach (var x in Meshes) { - UnityEngine.Object.DestroyImmediate(o, true); + UnityEngine.Object.DestroyImmediate(x.Mesh, true); + } + foreach (var x in AnimationClips) + { + UnityEngine.Object.DestroyImmediate(x, true); } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 22cd4788a..c6d6687c8 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; @@ -11,7 +12,7 @@ namespace UniGLTF public delegate MaterialItemBase MaterialImporter(int i, glTFMaterial x, bool hasVertexColor); - public class MaterialFactory + public class MaterialFactory : IDisposable { MaterialImporter m_materialImporter; public MaterialImporter MaterialImporter @@ -189,5 +190,10 @@ namespace UniGLTF return new PBRMaterialItem(i, x); } + + public void Dispose() + { + throw new NotImplementedException(); + } } } From d2fd56ef51e29ba9b83fefcc1d91830080bd4038 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Wed, 10 Feb 2021 21:59:52 +0900 Subject: [PATCH 02/16] =?UTF-8?q?TextureLoader.cs=20=E3=82=92=20class=20?= =?UTF-8?q?=E5=88=A5=E3=81=AB=E5=88=86=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MaterialFacotry/MaterialFactory.cs | 2 +- .../MaterialFacotry/TextureLoader.meta | 8 + .../TextureLoader/AssetTextureLoader.cs | 77 +++++++++ .../TextureLoader/AssetTextureLoader.cs.meta | 11 ++ .../TextureLoader/GltfTextureLoader.cs | 70 ++++++++ .../TextureLoader/GltfTextureLoader.cs.meta | 11 ++ .../TextureLoader/ITextureLoader.cs | 35 ++++ .../TextureLoader/ITextureLoader.cs.meta} | 0 .../UnityWebRequestTextureLoader.cs} | 160 ------------------ .../UnityWebRequestTextureLoader.cs.meta | 11 ++ 10 files changed, 224 insertions(+), 161 deletions(-) create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs.meta create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs.meta create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs rename Assets/UniGLTF/Runtime/UniGLTF/{IO/TextureLoader.cs.meta => MaterialFacotry/TextureLoader/ITextureLoader.cs.meta} (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{IO/TextureLoader.cs => MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs} (55%) create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index c6d6687c8..6a2d46291 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -76,7 +76,7 @@ namespace UniGLTF #if UNIGLTF_USE_WEBREQUEST_TEXTURELOADER return new UnityWebRequestTextureLoader(index); #else - return new TextureLoader(index); + return new GltfTextureLoader(index); #endif } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta new file mode 100644 index 000000000..84d4a147d --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 54a405d31cce94643be8f76f805da8c8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs new file mode 100644 index 000000000..f1d1fe62d --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs @@ -0,0 +1,77 @@ +using System.Collections; +using UnityEngine; + +namespace UniGLTF +{ +#if UNITY_EDITOR + public class AssetTextureLoader : ITextureLoader + { + public Texture2D Texture + { + private set; + get; + } + + UnityPath m_assetPath; + + public AssetTextureLoader(UnityPath assetPath, string _) + { + m_assetPath = assetPath; + } + + public void Dispose() + { + } + + public void ProcessOnAnyThread(glTF gltf, IStorage storage) + { + } + + public IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler) + { + // + // texture from assets + // + m_assetPath.ImportAsset(); + var importer = m_assetPath.GetImporter(); + if (importer == null) + { + Debug.LogWarningFormat("fail to get TextureImporter: {0}", m_assetPath); + } + importer.maxTextureSize = 8192; + importer.sRGBTexture = !isLinear; + + importer.SaveAndReimport(); + + Texture = m_assetPath.LoadAsset(); + + //Texture.name = m_textureName; + if (Texture == null) + { + Debug.LogWarningFormat("fail to Load Texture2D: {0}", m_assetPath); + } + + else + { + var maxSize = Mathf.Max(Texture.width, Texture.height); + + importer.maxTextureSize + = maxSize > 4096 ? 8192 : + maxSize > 2048 ? 4096 : + maxSize > 1024 ? 2048 : + maxSize > 512 ? 1024 : + 512; + + importer.SaveAndReimport(); + } + + if (sampler != null) + { + TextureSamplerUtil.SetSampler(Texture, sampler); + } + + yield break; + } + } +#endif +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs.meta new file mode 100644 index 000000000..c32ca741a --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 748452d292d79304da4c271f584ab985 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs new file mode 100644 index 000000000..b512d93ad --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections; +using UnityEngine; + +namespace UniGLTF +{ + public class GltfTextureLoader : ITextureLoader + { + int m_textureIndex; + public GltfTextureLoader(int textureIndex) + { + m_textureIndex = textureIndex; + } + + public Texture2D Texture + { + private set; + get; + } + + public void Dispose() + { + } + + static Byte[] ToArray(ArraySegment bytes) + { + if (bytes.Array == null) + { + return new byte[] { }; + } + else if (bytes.Offset == 0 && bytes.Count == bytes.Array.Length) + { + return bytes.Array; + } + else + { + Byte[] result = new byte[bytes.Count]; + Buffer.BlockCopy(bytes.Array, bytes.Offset, result, 0, result.Length); + return result; + } + } + + Byte[] m_imageBytes; + string m_textureName; + public void ProcessOnAnyThread(glTF gltf, IStorage storage) + { + var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); + var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); + m_imageBytes = ToArray(segments); + } + + public IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler) + { + // + // texture from image(png etc) bytes + // + Texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, isLinear); + Texture.name = m_textureName; + if (m_imageBytes != null) + { + Texture.LoadImage(m_imageBytes); + } + if (sampler != null) + { + TextureSamplerUtil.SetSampler(Texture, sampler); + } + yield break; + } + } +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs.meta new file mode 100644 index 000000000..28ea0287a --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c541795ac7ae51d468dfff535e5333cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs new file mode 100644 index 000000000..1a8152779 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections; +using System.IO; +using UnityEngine; +using UnityEngine.Networking; +#if UNITY_EDITOR +using UnityEditor; +#endif + + +namespace UniGLTF +{ + public interface ITextureLoader : IDisposable + { + Texture2D Texture { get; } + + /// + /// Call from any thread + /// + /// + /// + void ProcessOnAnyThread(glTF gltf, IStorage storage); + + /// + /// Call from unity main thread + /// + /// + /// + /// + IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler); + } + + + +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs similarity index 55% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader.cs rename to Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs index ee4ecf663..75128cb3f 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs @@ -3,169 +3,9 @@ using System.Collections; using System.IO; using UnityEngine; using UnityEngine.Networking; -#if UNITY_EDITOR -using UnityEditor; -#endif - namespace UniGLTF { - public interface ITextureLoader : IDisposable - { - Texture2D Texture { get; } - - /// - /// Call from any thread - /// - /// - /// - void ProcessOnAnyThread(glTF gltf, IStorage storage); - - /// - /// Call from unity main thread - /// - /// - /// - /// - IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler); - } - -#if UNITY_EDITOR - public class AssetTextureLoader : ITextureLoader - { - public Texture2D Texture - { - private set; - get; - } - - UnityPath m_assetPath; - - public AssetTextureLoader(UnityPath assetPath, string _) - { - m_assetPath = assetPath; - } - - public void Dispose() - { - } - - public void ProcessOnAnyThread(glTF gltf, IStorage storage) - { - } - - public IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler) - { - // - // texture from assets - // - m_assetPath.ImportAsset(); - var importer = m_assetPath.GetImporter(); - if (importer == null) - { - Debug.LogWarningFormat("fail to get TextureImporter: {0}", m_assetPath); - } - importer.maxTextureSize = 8192; - importer.sRGBTexture = !isLinear; - - importer.SaveAndReimport(); - - Texture = m_assetPath.LoadAsset(); - - //Texture.name = m_textureName; - if (Texture == null) - { - Debug.LogWarningFormat("fail to Load Texture2D: {0}", m_assetPath); - } - - else - { - var maxSize = Mathf.Max(Texture.width, Texture.height); - - importer.maxTextureSize - = maxSize > 4096 ? 8192 : - maxSize > 2048 ? 4096 : - maxSize > 1024 ? 2048 : - maxSize > 512 ? 1024 : - 512; - - importer.SaveAndReimport(); - } - - if (sampler != null) - { - TextureSamplerUtil.SetSampler(Texture, sampler); - } - - yield break; - } - } -#endif - - public class TextureLoader : ITextureLoader - { - int m_textureIndex; - public TextureLoader(int textureIndex) - { - m_textureIndex = textureIndex; - } - - public Texture2D Texture - { - private set; - get; - } - - public void Dispose() - { - } - - static Byte[] ToArray(ArraySegment bytes) - { - if (bytes.Array == null) - { - return new byte[] { }; - } - else if (bytes.Offset == 0 && bytes.Count == bytes.Array.Length) - { - return bytes.Array; - } - else - { - Byte[] result = new byte[bytes.Count]; - Buffer.BlockCopy(bytes.Array, bytes.Offset, result, 0, result.Length); - return result; - } - } - - Byte[] m_imageBytes; - string m_textureName; - public void ProcessOnAnyThread(glTF gltf, IStorage storage) - { - var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); - var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); - m_imageBytes = ToArray(segments); - } - - public IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler) - { - // - // texture from image(png etc) bytes - // - Texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, isLinear); - Texture.name = m_textureName; - if (m_imageBytes != null) - { - Texture.LoadImage(m_imageBytes); - } - if (sampler != null) - { - TextureSamplerUtil.SetSampler(Texture, sampler); - } - yield break; - } - } - public class UnityWebRequestTextureLoader : ITextureLoader { public Texture2D Texture diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs.meta new file mode 100644 index 000000000..d3369dfbc --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b91b7b42ddfd6284a9303a0901fccaa3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 92138a80ffd3dc42a4c662748dce13c7cf24869b Mon Sep 17 00:00:00 2001 From: ousttrue Date: Wed, 10 Feb 2021 22:08:35 +0900 Subject: [PATCH 03/16] new AssetTextureLoader --- .../UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs | 19 ++----------------- .../MaterialFacotry/MaterialFactory.cs | 5 ++++- 2 files changed, 6 insertions(+), 18 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs index cc03b6cb5..e96402d3c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs @@ -87,7 +87,7 @@ namespace UniGLTF public bool IsAsset { - private set; + set; get; } @@ -115,27 +115,12 @@ namespace UniGLTF m_textureIndex = index; m_textureLoader = textureLoader; - if(m_textureLoader == null) + if (m_textureLoader == null) { throw new Exception("ITextureLoader is null."); } } -#if UNITY_EDITOR - /// - /// Texture from asset - /// - /// - /// - /// - public TextureItem(int index, UnityPath assetPath, string textureName) - { - m_textureIndex = index; - IsAsset = true; - m_textureLoader = new AssetTextureLoader(assetPath, textureName); - } -#endif - #region Process ITextureLoader m_textureLoader; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 6a2d46291..659f620e4 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -121,7 +121,10 @@ namespace UniGLTF /// var assetPath = imageBaseDir.Child(image.uri); var textureName = !string.IsNullOrEmpty(image.name) ? image.name : Path.GetFileNameWithoutExtension(image.uri); - item = new TextureItem(i, assetPath, textureName); + item = new TextureItem(i, new AssetTextureLoader(assetPath, textureName)) + { + IsAsset = true + }; } else #endif From c26ea50e6a514f0bb2b47ff04967434793104d73 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Fri, 12 Feb 2021 17:17:13 +0900 Subject: [PATCH 04/16] remove ITextureLoader.ProcessOnAnyThread --- .../IEnumeratorExtensions.cs | 3 +- .../Runtime/UniGLTF/IO/ImporterContext.cs | 3 +- .../UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs | 24 ++--- .../MaterialFacotry/MaterialFactory.cs | 16 +--- .../TextureLoader/AssetTextureLoader.cs | 6 +- .../TextureLoader/GltfTextureLoader.cs | 26 ++++-- .../TextureLoader/ITextureLoader.cs | 14 +-- .../UnityWebRequestTextureLoader.cs | 91 +++---------------- Assets/VRM/Runtime/IO/VRMImporterContext.cs | 3 +- 9 files changed, 45 insertions(+), 141 deletions(-) diff --git a/Assets/UniGLTF/Runtime/DepthFirstScheduler/IEnumeratorExtensions.cs b/Assets/UniGLTF/Runtime/DepthFirstScheduler/IEnumeratorExtensions.cs index 30bd9f66d..cb89c4c9b 100644 --- a/Assets/UniGLTF/Runtime/DepthFirstScheduler/IEnumeratorExtensions.cs +++ b/Assets/UniGLTF/Runtime/DepthFirstScheduler/IEnumeratorExtensions.cs @@ -3,8 +3,7 @@ using System.Collections; using System.Collections.Generic; -namespace - DepthFirstScheduler +namespace DepthFirstScheduler { public static class IEnumeratorExtensions { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index 647601e35..3445e005c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -503,8 +503,7 @@ namespace UniGLTF { m_materialFactory.Prepare(GLTF); }) - .ContinueWithCoroutine(Scheduler.ThreadPool, () => m_materialFactory.TexturesProcessOnAnyThread(GLTF, Storage)) - .ContinueWithCoroutine(Scheduler.MainThread, () => m_materialFactory.TexturesProcessOnMainThread(GLTF)) + .ContinueWithCoroutine(Scheduler.MainThread, () => m_materialFactory.TexturesProcessOnMainThread(GLTF, Storage)) .ContinueWithCoroutine(Scheduler.MainThread, () => m_materialFactory.LoadMaterials(GLTF)) .OnExecute(Scheduler.ThreadPool, parent => { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs index e96402d3c..6a0477461 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs @@ -124,31 +124,19 @@ namespace UniGLTF #region Process ITextureLoader m_textureLoader; - public void Process(glTF gltf, IStorage storage) - { - ProcessOnAnyThread(gltf, storage); - ProcessOnMainThreadCoroutine(gltf).CoroutineToEnd(); - } + // public void Process(glTF gltf, IStorage storage) + // { + // ProcessOnMainThreadCoroutine(gltf, storage).CoroutineToEnd(); + // } - public IEnumerator ProcessCoroutine(glTF gltf, IStorage storage) - { - ProcessOnAnyThread(gltf, storage); - yield return ProcessOnMainThreadCoroutine(gltf); - } - - public void ProcessOnAnyThread(glTF gltf, IStorage storage) - { - m_textureLoader.ProcessOnAnyThread(gltf, storage); - } - - public IEnumerator ProcessOnMainThreadCoroutine(glTF gltf) + public IEnumerator ProcessOnMainThreadCoroutine(glTF gltf, IStorage storage) { using (m_textureLoader) { var textureType = TextureIO.GetglTFTextureType(gltf, m_textureIndex); var colorSpace = TextureIO.GetColorSpace(textureType); var isLinear = colorSpace == RenderTextureReadWrite.Linear; - yield return m_textureLoader.ProcessOnMainThread(isLinear, gltf.GetSamplerFromTextureIndex(m_textureIndex)); + yield return m_textureLoader.ProcessOnMainThread(gltf, storage, isLinear, gltf.GetSamplerFromTextureIndex(m_textureIndex)); } } #endregion diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 659f620e4..14901128f 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -136,25 +136,13 @@ namespace UniGLTF } } - public IEnumerator TexturesProcessOnAnyThread(glTF gltf, IStorage storage) - { - // using (MeasureTime("TexturesProcessOnAnyThread")) - { - foreach (var x in GetTextures()) - { - x.ProcessOnAnyThread(gltf, storage); - yield return null; - } - } - } - - public IEnumerator TexturesProcessOnMainThread(glTF gltf) + public IEnumerator TexturesProcessOnMainThread(glTF gltf, IStorage storage) { // using (MeasureTime("TexturesProcessOnMainThread")) { foreach (var x in GetTextures()) { - yield return x.ProcessOnMainThreadCoroutine(gltf); + yield return x.ProcessOnMainThreadCoroutine(gltf, storage); } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs index f1d1fe62d..9c92a7a02 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs @@ -23,11 +23,7 @@ namespace UniGLTF { } - public void ProcessOnAnyThread(glTF gltf, IStorage storage) - { - } - - public IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler) + public IEnumerator ProcessOnMainThread(glTF gltf, IStorage storage, bool isLinear, glTFTextureSampler sampler) { // // texture from assets diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs index b512d93ad..17028c1cc 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Threading.Tasks; using UnityEngine; namespace UniGLTF @@ -40,25 +41,30 @@ namespace UniGLTF } } - Byte[] m_imageBytes; string m_textureName; - public void ProcessOnAnyThread(glTF gltf, IStorage storage) - { - var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); - var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); - m_imageBytes = ToArray(segments); - } - public IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler) + public IEnumerator ProcessOnMainThread(glTF gltf, IStorage storage, bool isLinear, glTFTextureSampler sampler) { + Byte[] imageBytes = default; + var task = Task.Run(() => + { + var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); + var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); + var m_imageBytes = ToArray(segments); + }); + while (!task.IsCompleted) + { + yield break; + } + // // texture from image(png etc) bytes // Texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, isLinear); Texture.name = m_textureName; - if (m_imageBytes != null) + if (imageBytes != null) { - Texture.LoadImage(m_imageBytes); + Texture.LoadImage(imageBytes); } if (sampler != null) { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs index 1a8152779..a0381ab87 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs @@ -1,8 +1,6 @@ using System; using System.Collections; -using System.IO; using UnityEngine; -using UnityEngine.Networking; #if UNITY_EDITOR using UnityEditor; #endif @@ -14,22 +12,12 @@ namespace UniGLTF { Texture2D Texture { get; } - /// - /// Call from any thread - /// - /// - /// - void ProcessOnAnyThread(glTF gltf, IStorage storage); - /// /// Call from unity main thread /// /// /// /// - IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler); + IEnumerator ProcessOnMainThread(glTF gltf, IStorage storage, bool isLinear, glTFTextureSampler sampler); } - - - } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs index 75128cb3f..775f71375 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.IO; +using System.Threading.Tasks; using UnityEngine; using UnityEngine.Networking; @@ -31,84 +32,11 @@ namespace UniGLTF } } - ArraySegment m_segments; string m_textureName; - public void ProcessOnAnyThread(glTF gltf, IStorage storage) + public void ProcessOnAnyThread() { - var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); - m_segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); } -#if false - HttpHost m_http; - class HttpHost : IDisposable - { - TcpListener m_listener; - Socket m_connection; - - public HttpHost(int port) - { - m_listener = new TcpListener(IPAddress.Loopback, port); - m_listener.Start(); - m_listener.BeginAcceptSocket(OnAccepted, m_listener); - } - - void OnAccepted(IAsyncResult ar) - { - var l = ar.AsyncState as TcpListener; - if (l == null) return; - m_connection = l.EndAcceptSocket(ar); - // 次の接続受付はしない - - BeginRead(m_connection, new byte[8192]); - } - - void BeginRead(Socket c, byte[] buffer) - { - AsyncCallback callback = ar => - { - var s = ar.AsyncState as Socket; - if (s == null) return; - var size = s.EndReceive(ar); - if (size > 0) - { - OnRead(buffer, size); - } - BeginRead(s, buffer); - }; - m_connection.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, callback, m_connection); - } - - List m_buffer = new List(); - void OnRead(byte[] buffer, int len) - { - m_buffer.AddRange(buffer.Take(len)); - } - - public string Url - { - get - { - - } - } - - public void Dispose() - { - if (m_connection != null) - { - m_connection.Dispose(); - m_connection = null; - } - if(m_listener != null) - { - m_listener.Stop(); - m_listener = null; - } - } - } -#endif - class Deleter : IDisposable { string m_path; @@ -125,13 +53,24 @@ namespace UniGLTF } } - public IEnumerator ProcessOnMainThread(bool isLinear, glTFTextureSampler sampler) + public IEnumerator ProcessOnMainThread(glTF gltf, IStorage storage, bool isLinear, glTFTextureSampler sampler) { + ArraySegment bytes = default; + var task = Task.Run(() => + { + var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); + bytes = gltf.GetImageBytes(storage, imageIndex, out m_textureName); + }); + while (!task.IsCompleted) + { + yield return null; + } + // tmp file var tmp = Path.GetTempFileName(); using (var f = new FileStream(tmp, FileMode.Create)) { - f.Write(m_segments.Array, m_segments.Offset, m_segments.Count); + f.Write(bytes.Array, bytes.Offset, bytes.Count); } using (var d = new Deleter(tmp)) diff --git a/Assets/VRM/Runtime/IO/VRMImporterContext.cs b/Assets/VRM/Runtime/IO/VRMImporterContext.cs index 50d6ff0d2..fc0c19780 100644 --- a/Assets/VRM/Runtime/IO/VRMImporterContext.cs +++ b/Assets/VRM/Runtime/IO/VRMImporterContext.cs @@ -6,6 +6,7 @@ using UnityEngine; using System.IO; using System.Collections; using UniJSON; +using DepthFirstScheduler; namespace VRM { @@ -317,7 +318,7 @@ namespace VRM if (gltfMeta.texture >= 0 && gltfMeta.texture < GLTF.textures.Count) { var t = new TextureItem(gltfMeta.texture, MaterialFactory.CreateTextureLoader(gltfMeta.texture)); - t.Process(GLTF, Storage); + t.ProcessOnMainThreadCoroutine(GLTF, Storage).CoroutineToEnd(); meta.Thumbnail = t.Texture; } } From 153ec536e64167ffafc003c0cf897461bcafebeb Mon Sep 17 00:00:00 2001 From: ousttrue Date: Fri, 12 Feb 2021 20:32:05 +0900 Subject: [PATCH 05/16] TextureItem to MaterialFactory.GetTextureAsync --- .../Runtime/UniGLTF/IO/ImporterContext.cs | 28 +- .../Runtime/UniGLTF/IO/MeshImporter.cs | 6 +- .../UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs | 133 +--------- .../MaterialFacotry/MaterialFactory.cs | 241 +++++++++++------- .../MaterialFacotry/MaterialItemBase.cs | 8 +- .../MaterialFacotry/PBRMaterialItem.cs | 36 ++- .../TextureLoader/AssetTextureLoader.cs | 28 +- .../TextureLoader/GltfTextureLoader.cs | 50 ++-- .../TextureLoader/ITextureLoader.cs | 23 -- .../TextureLoader/ITextureLoader.cs.meta | 12 - .../UnityWebRequestTextureLoader.cs | 2 +- .../MaterialFacotry/UnlitMaterialItem.cs | 13 +- Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs | 24 +- .../VRM.Samples/Scripts/VRMRuntimeExporter.cs | 4 +- .../VRM.Samples/Scripts/VRMRuntimeLoader.cs | 4 +- Assets/VRM.Samples/Scripts/ViewerUI.cs | 13 +- Assets/VRM/Runtime/IO/VRMImporterContext.cs | 37 +-- Assets/VRM/Runtime/IO/VRMMaterialImporter.cs | 17 +- 18 files changed, 257 insertions(+), 422 deletions(-) delete mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs delete mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index 3445e005c..b6bbcbbc8 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -105,14 +105,9 @@ namespace UniGLTF #endregion - MaterialFactory m_materialFactory = new MaterialFactory(); + MaterialFactory m_materialFactory; public MaterialFactory MaterialFactory => m_materialFactory; - public ImporterContext(MaterialImporter materialImporter) - { - m_materialFactory.MaterialImporter = materialImporter; - } - public ImporterContext() { } @@ -267,12 +262,13 @@ namespace UniGLTF Json = json; Storage = storage; GLTF = GltfDeserializer.Deserialize(json.ParseAsJson()); - if (GLTF.asset.version != "2.0") { throw new UniGLTFException("unknown gltf version {0}", GLTF.asset.version); } + m_materialFactory = new MaterialFactory(GLTF, Storage); + // Version Compatibility RestoreOlderVersionValues(); @@ -501,10 +497,9 @@ namespace UniGLTF Schedulable.Create() .AddTask(Scheduler.ThreadPool, () => { - m_materialFactory.Prepare(GLTF); + // root task. do nothing }) - .ContinueWithCoroutine(Scheduler.MainThread, () => m_materialFactory.TexturesProcessOnMainThread(GLTF, Storage)) - .ContinueWithCoroutine(Scheduler.MainThread, () => m_materialFactory.LoadMaterials(GLTF)) + .ContinueWithCoroutine(Scheduler.MainThread, () => m_materialFactory.LoadMaterials()) .OnExecute(Scheduler.ThreadPool, parent => { // UniGLTF does not support draco @@ -695,16 +690,10 @@ namespace UniGLTF protected virtual IEnumerable ObjectsForSubAsset() { - HashSet textures = new HashSet(); - foreach (var x in MaterialFactory.GetTextures().SelectMany(y => y.GetTexturesForSaveAssets())) + foreach (var x in MaterialFactory.ObjectsForSubAsset()) { - if (!textures.Contains(x)) - { - textures.Add(x); - } + yield return x; } - foreach (var x in textures) { yield return x; } - foreach (var x in MaterialFactory.GetMaterials()) { yield return x.GetOrCreate(MaterialFactory.GetTexture); } foreach (var x in Meshes) { yield return x.Mesh; } foreach (var x in AnimationClips) { yield return x; } } @@ -895,7 +884,8 @@ namespace UniGLTF AssetDatabase.Refresh(); } - m_materialFactory.CreateTextureItems(GLTF, prefabParentDir); + // texture will load from assets + m_materialFactory.ImageBaseDir = prefabParentDir; } #endregion #endif diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs index 305a47bdc..c4346a974 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs @@ -634,10 +634,11 @@ namespace UniGLTF mesh.RecalculateTangents(); } + // 先にすべてのマテリアルを作成済みなのでテクスチャーは生成済み。Resultを使ってよい var result = new MeshWithMaterials { Mesh = mesh, - Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x).GetOrCreate(ctx.GetTexture)).ToArray() + Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x).GetOrCreateAsync(ctx.GetTextureAsync).Result).ToArray() }; if (meshContext.BlendShapes.Count > 0) @@ -662,10 +663,11 @@ namespace UniGLTF yield return null; } + // 先にすべてのマテリアルを作成済みなのでテクスチャーは生成済み。Resultを使ってよい var result = new MeshWithMaterials { Mesh = mesh, - Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x).GetOrCreate(ctx.GetTexture)).ToArray() + Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x).GetOrCreateAsync(ctx.GetTextureAsync).Result).ToArray() }; yield return null; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs index 6a0477461..320e23cb5 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs @@ -1,10 +1,6 @@ using UnityEngine; -using System.Linq; -using System.Collections.Generic; -using System.Collections; using System.IO; using System; -using DepthFirstScheduler; #if UNITY_EDITOR using UnityEditor; #endif @@ -12,135 +8,8 @@ using UnityEditor; namespace UniGLTF { - public class TextureItem + public static class TextureItem { - private int m_textureIndex; - public Texture2D Texture - { - get - { - return m_textureLoader.Texture; - } - } - - #region Texture converter - private Dictionary m_converts = new Dictionary(); - public Dictionary Converts - { - get { return m_converts; } - } - - /// - /// - /// - /// - /// used only when converting MetallicRoughness maps - /// - public Texture2D ConvertTexture(string prop, float smoothnessOrRoughness = 1.0f) - { - var convertedTexture = Converts.FirstOrDefault(x => x.Key == prop); - if (convertedTexture.Value != null) - return convertedTexture.Value; - - if (prop == "_BumpMap") - { - if (Application.isPlaying) - { - var converted = new NormalConverter().GetImportTexture(Texture); - m_converts.Add(prop, converted); - return converted; - } - else - { -#if UNITY_EDITOR - var textureAssetPath = AssetDatabase.GetAssetPath(Texture); - if (!string.IsNullOrEmpty(textureAssetPath)) - { - TextureIO.MarkTextureAssetAsNormalMap(textureAssetPath); - } - else - { - Debug.LogWarningFormat("no asset for {0}", Texture); - } -#endif - return Texture; - } - } - - if (prop == "_MetallicGlossMap") - { - var converted = new MetallicRoughnessConverter(smoothnessOrRoughness).GetImportTexture(Texture); - m_converts.Add(prop, converted); - return converted; - } - - if (prop == "_OcclusionMap") - { - var converted = new OcclusionConverter().GetImportTexture(Texture); - m_converts.Add(prop, converted); - return converted; - } - - return null; - } - #endregion - - public bool IsAsset - { - set; - get; - } - - public IEnumerable GetTexturesForSaveAssets() - { - if (!IsAsset) - { - yield return Texture; - } - if (m_converts.Any()) - { - foreach (var texture in m_converts) - { - yield return texture.Value; - } - } - } - - /// - /// Texture from buffer - /// - /// - public TextureItem(int index, ITextureLoader textureLoader) - { - m_textureIndex = index; - m_textureLoader = textureLoader; - - if (m_textureLoader == null) - { - throw new Exception("ITextureLoader is null."); - } - } - - #region Process - ITextureLoader m_textureLoader; - - // public void Process(glTF gltf, IStorage storage) - // { - // ProcessOnMainThreadCoroutine(gltf, storage).CoroutineToEnd(); - // } - - public IEnumerator ProcessOnMainThreadCoroutine(glTF gltf, IStorage storage) - { - using (m_textureLoader) - { - var textureType = TextureIO.GetglTFTextureType(gltf, m_textureIndex); - var colorSpace = TextureIO.GetColorSpace(textureType); - var isLinear = colorSpace == RenderTextureReadWrite.Linear; - yield return m_textureLoader.ProcessOnMainThread(gltf, storage, isLinear, gltf.GetSamplerFromTextureIndex(m_textureIndex)); - } - } - #endregion - struct ColorSpaceScope : IDisposable { bool m_sRGBWrite; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 14901128f..5c21c8d9c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -1,19 +1,80 @@ using System; using System.Collections; using System.Collections.Generic; -using System.IO; using System.Linq; +using System.Threading.Tasks; using UnityEngine; +#if UNITY_EDITOR +using UnityEditor; +#endif namespace UniGLTF { - public delegate TextureItem GetTextureItemFunc(int i); + public struct GetTextureParam + { + public const string NORMAL_PROP = "_BumpMap"; + public const string METALLIC_GLOSS_PROP = "_MetallicGlossMap"; + public const string OCCLUSION_PROP = "_OcclusionMap"; + + public readonly string TextureType; + public readonly float MetallicFactor; + public readonly ushort? Index0; + public readonly ushort? Index1; + public readonly ushort? Index2; + public readonly ushort? Index3; + public readonly ushort? Index4; + public readonly ushort? Index5; + + public GetTextureParam(string textureType, float metallicFactor, int i0, int i1, int i2, int i3, int i4, int i5) + { + TextureType = textureType; + MetallicFactor = metallicFactor; + Index0 = (ushort)i0; + Index1 = (ushort)i1; + Index2 = (ushort)i2; + Index3 = (ushort)i3; + Index4 = (ushort)i4; + Index5 = (ushort)i5; + } + + public static GetTextureParam Create(int index) + { + return new GetTextureParam(default, default, index, default, default, default, default, default); + } + + public static GetTextureParam CreateNormal(int index) + { + return new GetTextureParam(NORMAL_PROP, default, index, default, default, default, default, default); + } + + public static GetTextureParam CreateMetallic(int index, float metallicFactor) + { + return new GetTextureParam(METALLIC_GLOSS_PROP, metallicFactor, index, default, default, default, default, default); + } + + public static GetTextureParam CreateOcclusion(int index) + { + return new GetTextureParam(OCCLUSION_PROP, default, index, default, default, default, default, default); + } + } + + public delegate Task GetTextureAsyncFunc(GetTextureParam param); public delegate Shader GetShaderFunc(); public delegate MaterialItemBase MaterialImporter(int i, glTFMaterial x, bool hasVertexColor); public class MaterialFactory : IDisposable { + glTF m_gltf; + IStorage m_storage; + public MaterialFactory(glTF gltf, IStorage storage) + { + m_gltf = gltf; + m_storage = storage; + } + + public UnityPath ImageBaseDir { get; set; } + MaterialImporter m_materialImporter; public MaterialImporter MaterialImporter { @@ -31,22 +92,74 @@ namespace UniGLTF } } - List m_textures = new List(); - public IList GetTextures() + List m_textuers = new List(); + Dictionary m_textureCache = new Dictionary(); + + /// + /// テクスチャーをロード、必要であれば変換して返す。 + /// 同じものはキャッシュを返す + /// + /// 変換の有無を判断する: METALLIC_GLOSS_PROP + /// METALLIC_GLOSS_PROPの追加パラメーター + /// gltf の texture index + /// + public async Task GetTextureAsync(GetTextureParam param) { - return m_textures; - } - public TextureItem GetTexture(int i) - { - if (i < 0 || i >= m_textures.Count) + if (m_textureCache.TryGetValue(param, out Texture2D texture)) { - return null; + return texture; } - return m_textures[i]; - } - public void AddTexture(TextureItem item) - { - m_textures.Add(item); + + texture = await LoadTextureAsync(param.Index0.Value); + m_textureCache.Add(GetTextureParam.Create(param.Index0.Value), texture); + switch (param.TextureType) + { + case GetTextureParam.NORMAL_PROP: + { + if (Application.isPlaying) + { + var converted = new NormalConverter().GetImportTexture(texture); + m_textureCache.Add(param, converted); + return converted; + } + else + { +#if UNITY_EDITOR + var textureAssetPath = AssetDatabase.GetAssetPath(texture); + if (!string.IsNullOrEmpty(textureAssetPath)) + { + TextureIO.MarkTextureAssetAsNormalMap(textureAssetPath); + } + else + { + Debug.LogWarningFormat("no asset for {0}", texture); + } +#endif + m_textureCache.Add(param, texture); + return texture; + } + } + + case GetTextureParam.METALLIC_GLOSS_PROP: + { + // Bake roughnessFactor values into a texture. + var converted = new MetallicRoughnessConverter(param.MetallicFactor).GetImportTexture(texture); + m_textureCache.Add(param, converted); + return converted; + } + + case GetTextureParam.OCCLUSION_PROP: + { + var converted = new OcclusionConverter().GetImportTexture(texture); + m_textureCache.Add(param, converted); + return converted; + } + + default: + return texture; + } + + throw new NotImplementedException(); } List m_materials = new List(); @@ -71,95 +184,28 @@ namespace UniGLTF return m_materials[index]; } - public virtual ITextureLoader CreateTextureLoader(int index) + public virtual Task LoadTextureAsync(int index) { #if UNIGLTF_USE_WEBREQUEST_TEXTURELOADER - return new UnityWebRequestTextureLoader(index); + return UnityWebRequestTextureLoader.LoadTextureAsync(index); #else - return new GltfTextureLoader(index); + return GltfTextureLoader.LoadTextureAsync(m_gltf, m_storage, index); #endif } - public void Prepare(UniGLTF.glTF gltf, UnityPath imageBaseDir = default(UnityPath)) - { - if (m_textures.Count == 0) - { - // - // runtime - // - CreateTextureItems(gltf, imageBaseDir); - } - else - { - // - // already CreateTextures(by assetPostProcessor or editor menu) - // - } - - } - - public void CreateTextureItems(UniGLTF.glTF gltf, UnityPath imageBaseDir) - { - if (m_textures.Any()) - { - return; - } - - for (int i = 0; i < gltf.textures.Count; ++i) - { - - TextureItem item = null; -#if UNITY_EDITOR - var image = gltf.GetImageFromTextureIndex(i); - if (imageBaseDir.IsUnderAssetsFolder - && !string.IsNullOrEmpty(image.uri) - && !image.uri.FastStartsWith("data:") - ) - { - /// - /// required SaveTexturesAsPng or SetTextureBaseDir - /// - var assetPath = imageBaseDir.Child(image.uri); - var textureName = !string.IsNullOrEmpty(image.name) ? image.name : Path.GetFileNameWithoutExtension(image.uri); - item = new TextureItem(i, new AssetTextureLoader(assetPath, textureName)) - { - IsAsset = true - }; - } - else -#endif - { - item = new TextureItem(i, CreateTextureLoader(i)); - } - - AddTexture(item); - } - } - - public IEnumerator TexturesProcessOnMainThread(glTF gltf, IStorage storage) - { - // using (MeasureTime("TexturesProcessOnMainThread")) - { - foreach (var x in GetTextures()) - { - yield return x.ProcessOnMainThreadCoroutine(gltf, storage); - } - } - } - - public IEnumerator LoadMaterials(glTF gltf) + public IEnumerator LoadMaterials() { // using (MeasureTime("LoadMaterials")) { - if (gltf.materials == null || !gltf.materials.Any()) + if (m_gltf.materials == null || !m_gltf.materials.Any()) { AddMaterial(MaterialImporter(0, null, false)); } else { - for (int i = 0; i < gltf.materials.Count; ++i) + for (int i = 0; i < m_gltf.materials.Count; ++i) { - AddMaterial(MaterialImporter(i, gltf.materials[i], gltf.MaterialHasVertexColor(i))); + AddMaterial(MaterialImporter(i, m_gltf.materials[i], m_gltf.MaterialHasVertexColor(i))); } } } @@ -184,7 +230,22 @@ namespace UniGLTF public void Dispose() { - throw new NotImplementedException(); + foreach (var x in ObjectsForSubAsset()) + { + UnityEngine.Object.DestroyImmediate(x, true); + } + } + + public IEnumerable ObjectsForSubAsset() + { + foreach (var kv in m_textureCache) + { + yield return kv.Value; + } + foreach (var x in m_materials) + { + yield return x.GetOrCreateAsync(GetTextureAsync).Result; + } } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs index ad551e149..35191bab6 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using UnityEngine; @@ -17,7 +18,12 @@ namespace UniGLTF Name = src != null ? m_src.name : ""; } - public abstract Material GetOrCreate(GetTextureItemFunc getTexture); + public abstract Task GetOrCreateAsync(GetTextureAsyncFunc getTexture); + + public Material GetOrCreateForTest() + { + return GetOrCreateAsync(null).Result; + } protected Material CreateMaterial(string shaderName) { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs index d8e0e06ac..9a2602473 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs @@ -1,4 +1,5 @@ -using UnityEngine; +using System.Threading.Tasks; +using UnityEngine; namespace UniGLTF { @@ -45,11 +46,11 @@ namespace UniGLTF { } - public override Material GetOrCreate(GetTextureItemFunc getTexture) + public override async Task GetOrCreateAsync(GetTextureAsyncFunc getTexture) { if (getTexture == null) { - getTexture = _ => null; + getTexture = _ => Task.FromResult(null); } var material = CreateMaterial(ShaderName); @@ -67,11 +68,7 @@ namespace UniGLTF if (m_src.pbrMetallicRoughness.baseColorTexture != null && m_src.pbrMetallicRoughness.baseColorTexture.index != -1) { - var texture = getTexture(m_src.pbrMetallicRoughness.baseColorTexture.index); - if (texture != null) - { - material.mainTexture = texture.Texture; - } + material.mainTexture = await getTexture(GetTextureParam.Create(m_src.pbrMetallicRoughness.baseColorTexture.index)); // Texture Offset and Scale SetTextureOffsetAndScale(material, m_src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); @@ -80,12 +77,13 @@ namespace UniGLTF if (m_src.pbrMetallicRoughness.metallicRoughnessTexture != null && m_src.pbrMetallicRoughness.metallicRoughnessTexture.index != -1) { material.EnableKeyword("_METALLICGLOSSMAP"); - var texture = getTexture(m_src.pbrMetallicRoughness.metallicRoughnessTexture.index); + + var texture = await getTexture(GetTextureParam.CreateMetallic( + m_src.pbrMetallicRoughness.metallicRoughnessTexture.index, + m_src.pbrMetallicRoughness.metallicFactor)); if (texture != null) { - var prop = "_MetallicGlossMap"; - // Bake roughnessFactor values into a texture. - material.SetTexture(prop, texture.ConvertTexture(prop, m_src.pbrMetallicRoughness.roughnessFactor)); + material.SetTexture(GetTextureParam.METALLIC_GLOSS_PROP, texture); } material.SetFloat("_Metallic", 1.0f); @@ -105,11 +103,10 @@ namespace UniGLTF if (m_src.normalTexture != null && m_src.normalTexture.index != -1) { material.EnableKeyword("_NORMALMAP"); - var texture = getTexture(m_src.normalTexture.index); + var texture = await getTexture(GetTextureParam.CreateNormal(m_src.normalTexture.index)); if (texture != null) { - var prop = "_BumpMap"; - material.SetTexture(prop, texture.ConvertTexture(prop)); + material.SetTexture(GetTextureParam.NORMAL_PROP, texture); material.SetFloat("_BumpScale", m_src.normalTexture.scale); } @@ -119,11 +116,10 @@ namespace UniGLTF if (m_src.occlusionTexture != null && m_src.occlusionTexture.index != -1) { - var texture = getTexture(m_src.occlusionTexture.index); + var texture = await getTexture(GetTextureParam.CreateOcclusion(m_src.occlusionTexture.index)); if (texture != null) { - var prop = "_OcclusionMap"; - material.SetTexture(prop, texture.ConvertTexture(prop)); + material.SetTexture(GetTextureParam.OCCLUSION_PROP, texture); material.SetFloat("_OcclusionStrength", m_src.occlusionTexture.strength); } @@ -144,10 +140,10 @@ namespace UniGLTF if (m_src.emissiveTexture != null && m_src.emissiveTexture.index != -1) { - var texture = getTexture(m_src.emissiveTexture.index); + var texture = await getTexture(GetTextureParam.Create(m_src.emissiveTexture.index)); if (texture != null) { - material.SetTexture("_EmissionMap", texture.Texture); + material.SetTexture("_EmissionMap", texture); } // Texture Offset and Scale diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs index 9c92a7a02..352f0396e 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs @@ -1,29 +1,14 @@ using System.Collections; +using System.Threading.Tasks; using UnityEngine; namespace UniGLTF { #if UNITY_EDITOR - public class AssetTextureLoader : ITextureLoader + public static class AssetTextureLoader { - public Texture2D Texture - { - private set; - get; - } - - UnityPath m_assetPath; - - public AssetTextureLoader(UnityPath assetPath, string _) - { - m_assetPath = assetPath; - } - - public void Dispose() - { - } - - public IEnumerator ProcessOnMainThread(glTF gltf, IStorage storage, bool isLinear, glTFTextureSampler sampler) + public static Task LoadTaskAsync(UnityPath m_assetPath, + bool isLinear, glTFTextureSampler sampler) { // // texture from assets @@ -39,9 +24,8 @@ namespace UniGLTF importer.SaveAndReimport(); - Texture = m_assetPath.LoadAsset(); + var Texture = m_assetPath.LoadAsset(); - //Texture.name = m_textureName; if (Texture == null) { Debug.LogWarningFormat("fail to Load Texture2D: {0}", m_assetPath); @@ -66,7 +50,7 @@ namespace UniGLTF TextureSamplerUtil.SetSampler(Texture, sampler); } - yield break; + return Task.FromResult(Texture); } } #endif diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs index 17028c1cc..50eb5c3de 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs @@ -1,28 +1,11 @@ using System; -using System.Collections; using System.Threading.Tasks; using UnityEngine; namespace UniGLTF { - public class GltfTextureLoader : ITextureLoader + public static class GltfTextureLoader { - int m_textureIndex; - public GltfTextureLoader(int textureIndex) - { - m_textureIndex = textureIndex; - } - - public Texture2D Texture - { - private set; - get; - } - - public void Dispose() - { - } - static Byte[] ToArray(ArraySegment bytes) { if (bytes.Array == null) @@ -41,36 +24,35 @@ namespace UniGLTF } } - string m_textureName; - - public IEnumerator ProcessOnMainThread(glTF gltf, IStorage storage, bool isLinear, glTFTextureSampler sampler) + public static async Task LoadTextureAsync(glTF gltf, IStorage storage, int index) { - Byte[] imageBytes = default; - var task = Task.Run(() => + string m_textureName = default; + var imageBytes = await Task.Run(() => { - var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); + var imageIndex = gltf.GetImageIndexFromTextureIndex(index); var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); - var m_imageBytes = ToArray(segments); + return ToArray(segments); }); - while (!task.IsCompleted) - { - yield break; - } // // texture from image(png etc) bytes // - Texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, isLinear); - Texture.name = m_textureName; + var textureType = TextureIO.GetglTFTextureType(gltf, index); + var colorSpace = TextureIO.GetColorSpace(textureType); + var isLinear = colorSpace == RenderTextureReadWrite.Linear; + var sampler = gltf.GetSamplerFromTextureIndex(index); + + var texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, isLinear); + texture.name = m_textureName; if (imageBytes != null) { - Texture.LoadImage(imageBytes); + texture.LoadImage(imageBytes); } if (sampler != null) { - TextureSamplerUtil.SetSampler(Texture, sampler); + TextureSamplerUtil.SetSampler(texture, sampler); } - yield break; + return texture; } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs deleted file mode 100644 index a0381ab87..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections; -using UnityEngine; -#if UNITY_EDITOR -using UnityEditor; -#endif - - -namespace UniGLTF -{ - public interface ITextureLoader : IDisposable - { - Texture2D Texture { get; } - - /// - /// Call from unity main thread - /// - /// - /// - /// - IEnumerator ProcessOnMainThread(glTF gltf, IStorage storage, bool isLinear, glTFTextureSampler sampler); - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs.meta deleted file mode 100644 index a1aa6bbfe..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/ITextureLoader.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 4ffd8b31d371e024593b9aff2cf2495b -timeCreated: 1540300073 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs index 775f71375..226565715 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs @@ -7,7 +7,7 @@ using UnityEngine.Networking; namespace UniGLTF { - public class UnityWebRequestTextureLoader : ITextureLoader + public class UnityWebRequestTextureLoader { public Texture2D Texture { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs index 11f6cd43b..cadf7272c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs @@ -1,4 +1,5 @@ -using UnityEngine; +using System.Threading.Tasks; +using UnityEngine; namespace UniGLTF { @@ -13,11 +14,11 @@ namespace UniGLTF m_hasVertexColor = hasVertexColor; } - public override Material GetOrCreate(GetTextureItemFunc getTexture) + public override async Task GetOrCreateAsync(GetTextureAsyncFunc getTexture) { if (getTexture == null) { - getTexture = _ => null; + getTexture = _ => Task.FromResult(null); } var material = CreateMaterial(ShaderName); @@ -25,11 +26,7 @@ namespace UniGLTF // texture if (m_src.pbrMetallicRoughness.baseColorTexture != null) { - var texture = getTexture(m_src.pbrMetallicRoughness.baseColorTexture.index); - if (texture != null) - { - material.mainTexture = texture.Texture; - } + material.mainTexture = await getTexture(GetTextureParam.Create(m_src.pbrMetallicRoughness.baseColorTexture.index)); // Texture Offset and Scale SetTextureOffsetAndScale(material, m_src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); diff --git a/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs b/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs index 42c7d34bf..0860a5199 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs @@ -32,7 +32,7 @@ namespace UniGLTF var gltfMaterial = materialExporter.ExportMaterial(srcMaterial, textureManager); gltfMaterial.pbrMetallicRoughness.baseColorTexture.extensions = gltfMaterial.pbrMetallicRoughness.baseColorTexture.extensions.Deserialize(); - var dstMaterial = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var dstMaterial = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual(dstMaterial.mainTextureOffset.x, offset.x, 0.3f); Assert.AreEqual(dstMaterial.mainTextureOffset.y, offset.y, 0.2f); @@ -80,7 +80,7 @@ namespace UniGLTF Assert.IsTrue(glTF_KHR_materials_unlit.IsEnable(gltfMaterial)); - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } } @@ -99,7 +99,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -114,7 +114,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -130,7 +130,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -145,7 +145,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -160,7 +160,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -176,7 +176,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -191,7 +191,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -207,7 +207,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -217,7 +217,7 @@ namespace UniGLTF { extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } } @@ -225,7 +225,7 @@ namespace UniGLTF [Test] public void MaterialImportTest() { - var material = MaterialFactory.CreateMaterial(0, new glTFMaterial { }, false).GetOrCreate(null); + var material = MaterialFactory.CreateMaterial(0, new glTFMaterial { }, false).GetOrCreateForTest(); Assert.AreEqual("Standard", material.shader.name); } diff --git a/Assets/VRM.Samples/Scripts/VRMRuntimeExporter.cs b/Assets/VRM.Samples/Scripts/VRMRuntimeExporter.cs index 08cbcb036..1d4e3ac84 100644 --- a/Assets/VRM.Samples/Scripts/VRMRuntimeExporter.cs +++ b/Assets/VRM.Samples/Scripts/VRMRuntimeExporter.cs @@ -29,7 +29,7 @@ namespace VRM.Samples #region Load - void OnLoadClicked() + async void OnLoadClicked() { #if UNITY_STANDALONE_WIN var path = FileDialogForWindows.FileDialog("open VRM", ".vrm"); @@ -53,7 +53,7 @@ namespace VRM.Samples // metaを取得(todo: thumbnailテクスチャのロード) - var meta = context.ReadMeta(); + var meta = await context.ReadMetaAsync(); Debug.LogFormat("meta: title:{0}", meta.Title); // ParseしたJSONをシーンオブジェクトに変換していく diff --git a/Assets/VRM.Samples/Scripts/VRMRuntimeLoader.cs b/Assets/VRM.Samples/Scripts/VRMRuntimeLoader.cs index c9d20608a..4b6d85804 100644 --- a/Assets/VRM.Samples/Scripts/VRMRuntimeLoader.cs +++ b/Assets/VRM.Samples/Scripts/VRMRuntimeLoader.cs @@ -70,7 +70,7 @@ namespace VRM.Samples m_canvas.LoadBVHButton.onClick.AddListener(LoadBVHClicked); } - void LoadVRMClicked() + async void LoadVRMClicked() { #if UNITY_STANDALONE_WIN var path = FileDialogForWindows.FileDialog("open VRM", ".vrm"); @@ -94,7 +94,7 @@ namespace VRM.Samples // metaを取得(todo: thumbnailテクスチャのロード) - var meta = context.ReadMeta(); + var meta = await context.ReadMetaAsync(); Debug.LogFormat("meta: title:{0}", meta.Title); diff --git a/Assets/VRM.Samples/Scripts/ViewerUI.cs b/Assets/VRM.Samples/Scripts/ViewerUI.cs index 6de3d72ca..9c1e71288 100644 --- a/Assets/VRM.Samples/Scripts/ViewerUI.cs +++ b/Assets/VRM.Samples/Scripts/ViewerUI.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using System.Threading.Tasks; using UniHumanoid; using UnityEngine; using UnityEngine.UI; @@ -83,9 +84,9 @@ namespace VRM.Samples m_textDistributionOther.text = ""; } - public void UpdateMeta(VRMImporterContext context) + public async Task UpdateMetaAsync(VRMImporterContext context) { - var meta = context.ReadMeta(true); + var meta = await context.ReadMetaAsync(true); m_textModelTitle.text = meta.Title; m_textModelVersion.text = meta.Version; @@ -211,7 +212,7 @@ namespace VRM.Samples string[] cmds = System.Environment.GetCommandLineArgs(); if (cmds.Length > 1) { - LoadModel(cmds[1]); + LoadModelAsync(cmds[1]); } m_texts.Start(); @@ -282,7 +283,7 @@ namespace VRM.Samples case ".glb": case ".vrm": case ".zip": - LoadModel(path); + LoadModelAsync(path); break; case ".bvh": @@ -291,7 +292,7 @@ namespace VRM.Samples } } - void LoadModel(string path) + async void LoadModelAsync(string path) { if (!File.Exists(path)) { @@ -307,7 +308,7 @@ namespace VRM.Samples var context = new VRMImporterContext(); var file = File.ReadAllBytes(path); context.ParseGlb(file); - m_texts.UpdateMeta(context); + await m_texts.UpdateMetaAsync(context); context.Load(); context.ShowMeshes(); context.EnableUpdateWhenOffscreen(); diff --git a/Assets/VRM/Runtime/IO/VRMImporterContext.cs b/Assets/VRM/Runtime/IO/VRMImporterContext.cs index fc0c19780..76d8a2a5b 100644 --- a/Assets/VRM/Runtime/IO/VRMImporterContext.cs +++ b/Assets/VRM/Runtime/IO/VRMImporterContext.cs @@ -6,7 +6,7 @@ using UnityEngine; using System.IO; using System.Collections; using UniJSON; -using DepthFirstScheduler; +using System.Threading.Tasks; namespace VRM { @@ -58,7 +58,11 @@ namespace VRM using (MeasureTime("VRM LoadMeta")) { - LoadMeta(); + var task = LoadMetaAsync(); + while (!task.IsCompleted) + { + yield return null; + } } yield return null; @@ -87,9 +91,9 @@ namespace VRM } } - void LoadMeta() + async Task LoadMetaAsync() { - var meta = ReadMeta(); + var meta = await ReadMetaAsync(); var _meta = Root.AddComponent(); _meta.Meta = meta; Meta = meta; @@ -194,7 +198,9 @@ namespace VRM } } - var material = MaterialFactory.GetMaterials().FirstOrDefault(y => y.Name == x.materialName).GetOrCreate(MaterialFactory.GetTexture); + var material = MaterialFactory.GetMaterials() + .FirstOrDefault(y => y.Name == x.materialName) + .GetOrCreateAsync(MaterialFactory.GetTextureAsync).Result; var propertyName = x.propertyName; if (x.propertyName.FastEndsWith("_ST_S") || x.propertyName.FastEndsWith("_ST_T")) @@ -293,7 +299,7 @@ namespace VRM public BlendShapeAvatar BlendShapeAvatar; public VRMMetaObject Meta; - public VRMMetaObject ReadMeta(bool createThumbnail = false) + public async Task ReadMetaAsync(bool createThumbnail = false) { var meta = ScriptableObject.CreateInstance(); meta.name = "Meta"; @@ -305,24 +311,7 @@ namespace VRM meta.ContactInformation = gltfMeta.contactInformation; meta.Reference = gltfMeta.reference; meta.Title = gltfMeta.title; - - var thumbnail = MaterialFactory.GetTexture(gltfMeta.texture); - if (thumbnail != null) - { - // ロード済み - meta.Thumbnail = thumbnail.Texture; - } - else if (createThumbnail) - { - // 作成する(先行ロード用) - if (gltfMeta.texture >= 0 && gltfMeta.texture < GLTF.textures.Count) - { - var t = new TextureItem(gltfMeta.texture, MaterialFactory.CreateTextureLoader(gltfMeta.texture)); - t.ProcessOnMainThreadCoroutine(GLTF, Storage).CoroutineToEnd(); - meta.Thumbnail = t.Texture; - } - } - + meta.Thumbnail = await MaterialFactory.GetTextureAsync(GetTextureParam.Create(gltfMeta.texture)); meta.AllowedUser = gltfMeta.allowedUser; meta.ViolentUssage = gltfMeta.violentUssage; meta.SexualUssage = gltfMeta.sexualUssage; diff --git a/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs b/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs index c758deb49..26caed56c 100644 --- a/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs +++ b/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs @@ -3,6 +3,7 @@ using UniGLTF; using UnityEngine; using System.Linq; using System; +using System.Threading.Tasks; namespace VRM { @@ -29,7 +30,7 @@ namespace VRM m_vrmMaterial = vrmMaterial; } - public override Material GetOrCreate(GetTextureItemFunc getTexture) + public override async Task GetOrCreateAsync(GetTextureAsyncFunc getTexture) { var item = m_vrmMaterial; var shaderName = item.shader; @@ -47,7 +48,7 @@ namespace VRM { Debug.LogWarningFormat("unknown shader {0}.", shaderName); } - return MaterialFactory.CreateMaterial(m_index, m_src, m_hasVertexColor).GetOrCreate(getTexture); + return await MaterialFactory.CreateMaterial(m_index, m_src, m_hasVertexColor).GetOrCreateAsync(getTexture); } // @@ -78,18 +79,10 @@ namespace VRM } foreach (var kv in item.textureProperties) { - var texture = getTexture(kv.Value); + var texture = await getTexture(new GetTextureParam(kv.Key, default, kv.Value, default, default, default, default, default)); if (texture != null) { - var converted = texture.ConvertTexture(kv.Key); - if (converted != null) - { - material.SetTexture(kv.Key, converted); - } - else - { - material.SetTexture(kv.Key, texture.Texture); - } + material.SetTexture(kv.Key, texture); } } foreach (var kv in item.keywordMap) From d45589600b7b7fa580820dba7622c94a727f7fd5 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Fri, 12 Feb 2021 20:34:20 +0900 Subject: [PATCH 06/16] mv TextureItem --- .../Runtime/UniGLTF/{IO => MaterialFacotry}/TextureItem.cs | 0 .../Runtime/UniGLTF/{IO => MaterialFacotry}/TextureItem.cs.meta | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Assets/UniGLTF/Runtime/UniGLTF/{IO => MaterialFacotry}/TextureItem.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{IO => MaterialFacotry}/TextureItem.cs.meta (100%) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs rename to Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/TextureItem.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs.meta From 590fec1cdc1a7c37249633cf7baa2c694495d7e6 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Fri, 12 Feb 2021 20:36:15 +0900 Subject: [PATCH 07/16] GetTextureParam.cs --- .../MaterialFacotry/GetTextureParam.cs | 55 +++++++++++++++++++ .../MaterialFacotry/GetTextureParam.cs.meta | 11 ++++ .../MaterialFacotry/MaterialFactory.cs | 51 ----------------- 3 files changed, 66 insertions(+), 51 deletions(-) create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs new file mode 100644 index 000000000..c712f34f5 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs @@ -0,0 +1,55 @@ +using System.Threading.Tasks; +using UnityEngine; + +namespace UniGLTF +{ + public struct GetTextureParam + { + public const string NORMAL_PROP = "_BumpMap"; + public const string METALLIC_GLOSS_PROP = "_MetallicGlossMap"; + public const string OCCLUSION_PROP = "_OcclusionMap"; + + public readonly string TextureType; + public readonly float MetallicFactor; + public readonly ushort? Index0; + public readonly ushort? Index1; + public readonly ushort? Index2; + public readonly ushort? Index3; + public readonly ushort? Index4; + public readonly ushort? Index5; + + public GetTextureParam(string textureType, float metallicFactor, int i0, int i1, int i2, int i3, int i4, int i5) + { + TextureType = textureType; + MetallicFactor = metallicFactor; + Index0 = (ushort)i0; + Index1 = (ushort)i1; + Index2 = (ushort)i2; + Index3 = (ushort)i3; + Index4 = (ushort)i4; + Index5 = (ushort)i5; + } + + public static GetTextureParam Create(int index) + { + return new GetTextureParam(default, default, index, default, default, default, default, default); + } + + public static GetTextureParam CreateNormal(int index) + { + return new GetTextureParam(NORMAL_PROP, default, index, default, default, default, default, default); + } + + public static GetTextureParam CreateMetallic(int index, float metallicFactor) + { + return new GetTextureParam(METALLIC_GLOSS_PROP, metallicFactor, index, default, default, default, default, default); + } + + public static GetTextureParam CreateOcclusion(int index) + { + return new GetTextureParam(OCCLUSION_PROP, default, index, default, default, default, default, default); + } + } + + public delegate Task GetTextureAsyncFunc(GetTextureParam param); +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs.meta new file mode 100644 index 000000000..d5bf2ad96 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f1dc05e4970e724e9f50c0a5a67a25e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 5c21c8d9c..676faf0dd 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -10,59 +10,8 @@ using UnityEditor; namespace UniGLTF { - public struct GetTextureParam - { - public const string NORMAL_PROP = "_BumpMap"; - public const string METALLIC_GLOSS_PROP = "_MetallicGlossMap"; - public const string OCCLUSION_PROP = "_OcclusionMap"; - - public readonly string TextureType; - public readonly float MetallicFactor; - public readonly ushort? Index0; - public readonly ushort? Index1; - public readonly ushort? Index2; - public readonly ushort? Index3; - public readonly ushort? Index4; - public readonly ushort? Index5; - - public GetTextureParam(string textureType, float metallicFactor, int i0, int i1, int i2, int i3, int i4, int i5) - { - TextureType = textureType; - MetallicFactor = metallicFactor; - Index0 = (ushort)i0; - Index1 = (ushort)i1; - Index2 = (ushort)i2; - Index3 = (ushort)i3; - Index4 = (ushort)i4; - Index5 = (ushort)i5; - } - - public static GetTextureParam Create(int index) - { - return new GetTextureParam(default, default, index, default, default, default, default, default); - } - - public static GetTextureParam CreateNormal(int index) - { - return new GetTextureParam(NORMAL_PROP, default, index, default, default, default, default, default); - } - - public static GetTextureParam CreateMetallic(int index, float metallicFactor) - { - return new GetTextureParam(METALLIC_GLOSS_PROP, metallicFactor, index, default, default, default, default, default); - } - - public static GetTextureParam CreateOcclusion(int index) - { - return new GetTextureParam(OCCLUSION_PROP, default, index, default, default, default, default, default); - } - } - - public delegate Task GetTextureAsyncFunc(GetTextureParam param); - public delegate Shader GetShaderFunc(); public delegate MaterialItemBase MaterialImporter(int i, glTFMaterial x, bool hasVertexColor); - public class MaterialFactory : IDisposable { glTF m_gltf; From c7e0191685385c35bfbe05c8dc7479b1d1aefcae Mon Sep 17 00:00:00 2001 From: ousttrue Date: Fri, 12 Feb 2021 21:22:46 +0900 Subject: [PATCH 08/16] CreateMaterialAsyncFunc --- .../Runtime/UniGLTF/IO/ImporterContext.cs | 2 +- .../Runtime/UniGLTF/IO/MeshImporter.cs | 4 +- .../MaterialFacotry/MaterialFactory.cs | 66 ++++++++--------- .../MaterialFacotry/MaterialItemBase.cs | 62 +++++++++------- .../MaterialFacotry/PBRMaterialItem.cs | 70 +++++++++---------- .../MaterialFacotry/UnlitMaterialItem.cs | 35 ++++------ Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs | 25 +++---- Assets/VRM/Runtime/IO/VRMImporterContext.cs | 7 +- Assets/VRM/Runtime/IO/VRMMaterialImporter.cs | 23 ++---- 9 files changed, 138 insertions(+), 156 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index b6bbcbbc8..12098ecdd 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -499,7 +499,7 @@ namespace UniGLTF { // root task. do nothing }) - .ContinueWithCoroutine(Scheduler.MainThread, () => m_materialFactory.LoadMaterials()) + .ContinueWithCoroutine(Scheduler.MainThread, m_materialFactory.LoadMaterials) .OnExecute(Scheduler.ThreadPool, parent => { // UniGLTF does not support draco diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs index c4346a974..0f2701cc8 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs @@ -638,7 +638,7 @@ namespace UniGLTF var result = new MeshWithMaterials { Mesh = mesh, - Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x).GetOrCreateAsync(ctx.GetTextureAsync).Result).ToArray() + Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x)).ToArray() }; if (meshContext.BlendShapes.Count > 0) @@ -667,7 +667,7 @@ namespace UniGLTF var result = new MeshWithMaterials { Mesh = mesh, - Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x).GetOrCreateAsync(ctx.GetTextureAsync).Result).ToArray() + Materials = meshContext.MaterialIndices.Select(x => ctx.GetMaterial(x)).ToArray() }; yield return null; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 676faf0dd..060143ef7 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -10,8 +10,6 @@ using UnityEditor; namespace UniGLTF { - public delegate MaterialItemBase MaterialImporter(int i, glTFMaterial x, bool hasVertexColor); - public class MaterialFactory : IDisposable { glTF m_gltf; @@ -24,20 +22,21 @@ namespace UniGLTF public UnityPath ImageBaseDir { get; set; } - MaterialImporter m_materialImporter; - public MaterialImporter MaterialImporter + public delegate Task CreateMaterialAsyncFunc(glTF glTF, int i, GetTextureAsyncFunc getTexture); + CreateMaterialAsyncFunc m_createMaterialAsync; + public CreateMaterialAsyncFunc CreateMaterialAsync { set { - m_materialImporter = value; + m_createMaterialAsync = value; } get { - if (m_materialImporter == null) + if (m_createMaterialAsync == null) { - m_materialImporter = CreateMaterial; + m_createMaterialAsync = MaterialItemBase.DefaultCreateMaterialAsync; } - return m_materialImporter; + return m_createMaterialAsync; } } @@ -111,22 +110,19 @@ namespace UniGLTF throw new NotImplementedException(); } - List m_materials = new List(); - public void AddMaterial(MaterialItemBase material) + List m_materials = new List(); + public IReadOnlyList Materials => m_materials; + public void AddMaterial(Material material) { - var originalName = material.Name; + var originalName = material.name; int j = 2; - while (m_materials.Any(x => x.Name == material.Name)) + while (m_materials.Any(x => x.name == material.name)) { - material.Name = string.Format("{0}({1})", originalName, j++); + material.name = string.Format("{0}({1})", originalName, j++); } m_materials.Add(material); } - public IList GetMaterials() - { - return m_materials; - } - public MaterialItemBase GetMaterial(int index) + public Material GetMaterial(int index) { if (index < 0) return null; if (index >= m_materials.Count) return null; @@ -146,37 +142,31 @@ namespace UniGLTF { // using (MeasureTime("LoadMaterials")) { - if (m_gltf.materials == null || !m_gltf.materials.Any()) + if (m_gltf.materials == null || m_gltf.materials.Count == 0) { - AddMaterial(MaterialImporter(0, null, false)); + var task = CreateMaterialAsync(m_gltf, 0, GetTextureAsync); + while (!task.IsCompleted) + { + yield return null; + } + AddMaterial(task.Result); } else { for (int i = 0; i < m_gltf.materials.Count; ++i) { - AddMaterial(MaterialImporter(i, m_gltf.materials[i], m_gltf.MaterialHasVertexColor(i))); + var task = CreateMaterialAsync(m_gltf, i, GetTextureAsync); + while (!task.IsCompleted) + { + yield return null; + } + AddMaterial(task.Result); } } } yield return null; } - public static MaterialItemBase CreateMaterial(int i, glTFMaterial x, bool hasVertexColor) - { - if (x == null) - { - UnityEngine.Debug.LogWarning("glTFMaterial is empty"); - return new PBRMaterialItem(i, x); - } - - if (glTF_KHR_materials_unlit.IsEnable(x)) - { - return new UnlitMaterialItem(i, x, hasVertexColor); - } - - return new PBRMaterialItem(i, x); - } - public void Dispose() { foreach (var x in ObjectsForSubAsset()) @@ -193,7 +183,7 @@ namespace UniGLTF } foreach (var x in m_materials) { - yield return x.GetOrCreateAsync(GetTextureAsync).Result; + yield return x; } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs index 35191bab6..86e51d7e0 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs @@ -4,43 +4,24 @@ using UnityEngine; namespace UniGLTF { - public abstract class MaterialItemBase + public static class MaterialItemBase { - protected int m_index; - protected glTFMaterial m_src; - - public string Name { get; set; } - - public MaterialItemBase(int i, glTFMaterial src) - { - m_index = i; - m_src = src; - Name = src != null ? m_src.name : ""; - } - - public abstract Task GetOrCreateAsync(GetTextureAsyncFunc getTexture); - - public Material GetOrCreateForTest() - { - return GetOrCreateAsync(null).Result; - } - - protected Material CreateMaterial(string shaderName) + public static Material CreateMaterial(int index, glTFMaterial src, string shaderName) { var material = new Material(Shader.Find(shaderName)); #if UNITY_EDITOR // textureImporter.SaveAndReimport(); may destroy this material material.hideFlags = HideFlags.DontUnloadUnusedAsset; #endif - material.name = (m_src == null || string.IsNullOrEmpty(m_src.name)) - ? string.Format("material_{0:00}", m_index) - : m_src.name + material.name = (src == null || string.IsNullOrEmpty(src.name)) + ? string.Format("material_{0:00}", index) + : src.name ; return material; } - protected static void SetTextureOffsetAndScale(Material material, glTFTextureInfo textureInfo, string propertyName) + public static void SetTextureOffsetAndScale(Material material, glTFTextureInfo textureInfo, string propertyName) { if (glTF_KHR_texture_transform.TryGet(textureInfo, out glTF_KHR_texture_transform textureTransform)) { @@ -61,5 +42,36 @@ namespace UniGLTF material.SetTextureScale(propertyName, scale); } } + + public static Task DefaultCreateMaterialAsync(glTF gltf, int i, GetTextureAsyncFunc getTexture) + { + + if (i < 0 || i >= gltf.materials.Count) + { + UnityEngine.Debug.LogWarning("glTFMaterial is empty"); + return PBRMaterialItem.CreateAsync(i, null, getTexture); + } + var x = gltf.materials[i]; + + if (glTF_KHR_materials_unlit.IsEnable(x)) + { + var hasVertexColor = gltf.MaterialHasVertexColor(i); + return UnlitMaterialItem.CreateAsync(i, x, getTexture, hasVertexColor); + } + + return PBRMaterialItem.CreateAsync(i, x, getTexture); + } + + /// + /// for unittest + /// + /// + /// + /// + /// + public static Material CreateMaterialForTest(int i, glTFMaterial material) + { + throw new System.NotImplementedException(); + } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs index 9a2602473..77ca1faa6 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs @@ -30,7 +30,7 @@ namespace UniGLTF /// _SrcBlend /// _DstBlend /// _ZWrite - public class PBRMaterialItem : MaterialItemBase + public static class PBRMaterialItem { public const string ShaderName = "Standard"; @@ -42,45 +42,41 @@ namespace UniGLTF Transparent } - public PBRMaterialItem(int i, glTFMaterial src) : base(i, src) - { - } - - public override async Task GetOrCreateAsync(GetTextureAsyncFunc getTexture) + public static async Task CreateAsync(int i, glTFMaterial src, GetTextureAsyncFunc getTexture) { if (getTexture == null) { getTexture = _ => Task.FromResult(null); } - var material = CreateMaterial(ShaderName); + var material = MaterialItemBase.CreateMaterial(i, src, ShaderName); // PBR material - if (m_src != null) + if (src != null) { - if (m_src.pbrMetallicRoughness != null) + if (src.pbrMetallicRoughness != null) { - if (m_src.pbrMetallicRoughness.baseColorFactor != null && m_src.pbrMetallicRoughness.baseColorFactor.Length == 4) + if (src.pbrMetallicRoughness.baseColorFactor != null && src.pbrMetallicRoughness.baseColorFactor.Length == 4) { - var color = m_src.pbrMetallicRoughness.baseColorFactor; + var color = src.pbrMetallicRoughness.baseColorFactor; material.color = (new Color(color[0], color[1], color[2], color[3])).gamma; } - if (m_src.pbrMetallicRoughness.baseColorTexture != null && m_src.pbrMetallicRoughness.baseColorTexture.index != -1) + if (src.pbrMetallicRoughness.baseColorTexture != null && src.pbrMetallicRoughness.baseColorTexture.index != -1) { - material.mainTexture = await getTexture(GetTextureParam.Create(m_src.pbrMetallicRoughness.baseColorTexture.index)); + material.mainTexture = await getTexture(GetTextureParam.Create(src.pbrMetallicRoughness.baseColorTexture.index)); // Texture Offset and Scale - SetTextureOffsetAndScale(material, m_src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); + MaterialItemBase.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); } - if (m_src.pbrMetallicRoughness.metallicRoughnessTexture != null && m_src.pbrMetallicRoughness.metallicRoughnessTexture.index != -1) + if (src.pbrMetallicRoughness.metallicRoughnessTexture != null && src.pbrMetallicRoughness.metallicRoughnessTexture.index != -1) { material.EnableKeyword("_METALLICGLOSSMAP"); var texture = await getTexture(GetTextureParam.CreateMetallic( - m_src.pbrMetallicRoughness.metallicRoughnessTexture.index, - m_src.pbrMetallicRoughness.metallicFactor)); + src.pbrMetallicRoughness.metallicRoughnessTexture.index, + src.pbrMetallicRoughness.metallicFactor)); if (texture != null) { material.SetTexture(GetTextureParam.METALLIC_GLOSS_PROP, texture); @@ -91,69 +87,69 @@ namespace UniGLTF material.SetFloat("_GlossMapScale", 1.0f); // Texture Offset and Scale - SetTextureOffsetAndScale(material, m_src.pbrMetallicRoughness.metallicRoughnessTexture, "_MetallicGlossMap"); + MaterialItemBase.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.metallicRoughnessTexture, "_MetallicGlossMap"); } else { - material.SetFloat("_Metallic", m_src.pbrMetallicRoughness.metallicFactor); - material.SetFloat("_Glossiness", 1.0f - m_src.pbrMetallicRoughness.roughnessFactor); + material.SetFloat("_Metallic", src.pbrMetallicRoughness.metallicFactor); + material.SetFloat("_Glossiness", 1.0f - src.pbrMetallicRoughness.roughnessFactor); } } - if (m_src.normalTexture != null && m_src.normalTexture.index != -1) + if (src.normalTexture != null && src.normalTexture.index != -1) { material.EnableKeyword("_NORMALMAP"); - var texture = await getTexture(GetTextureParam.CreateNormal(m_src.normalTexture.index)); + var texture = await getTexture(GetTextureParam.CreateNormal(src.normalTexture.index)); if (texture != null) { material.SetTexture(GetTextureParam.NORMAL_PROP, texture); - material.SetFloat("_BumpScale", m_src.normalTexture.scale); + material.SetFloat("_BumpScale", src.normalTexture.scale); } // Texture Offset and Scale - SetTextureOffsetAndScale(material, m_src.normalTexture, "_BumpMap"); + MaterialItemBase.SetTextureOffsetAndScale(material, src.normalTexture, "_BumpMap"); } - if (m_src.occlusionTexture != null && m_src.occlusionTexture.index != -1) + if (src.occlusionTexture != null && src.occlusionTexture.index != -1) { - var texture = await getTexture(GetTextureParam.CreateOcclusion(m_src.occlusionTexture.index)); + var texture = await getTexture(GetTextureParam.CreateOcclusion(src.occlusionTexture.index)); if (texture != null) { material.SetTexture(GetTextureParam.OCCLUSION_PROP, texture); - material.SetFloat("_OcclusionStrength", m_src.occlusionTexture.strength); + material.SetFloat("_OcclusionStrength", src.occlusionTexture.strength); } // Texture Offset and Scale - SetTextureOffsetAndScale(material, m_src.occlusionTexture, "_OcclusionMap"); + MaterialItemBase.SetTextureOffsetAndScale(material, src.occlusionTexture, "_OcclusionMap"); } - if (m_src.emissiveFactor != null - || (m_src.emissiveTexture != null && m_src.emissiveTexture.index != -1)) + if (src.emissiveFactor != null + || (src.emissiveTexture != null && src.emissiveTexture.index != -1)) { material.EnableKeyword("_EMISSION"); material.globalIlluminationFlags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; - if (m_src.emissiveFactor != null && m_src.emissiveFactor.Length == 3) + if (src.emissiveFactor != null && src.emissiveFactor.Length == 3) { - material.SetColor("_EmissionColor", new Color(m_src.emissiveFactor[0], m_src.emissiveFactor[1], m_src.emissiveFactor[2])); + material.SetColor("_EmissionColor", new Color(src.emissiveFactor[0], src.emissiveFactor[1], src.emissiveFactor[2])); } - if (m_src.emissiveTexture != null && m_src.emissiveTexture.index != -1) + if (src.emissiveTexture != null && src.emissiveTexture.index != -1) { - var texture = await getTexture(GetTextureParam.Create(m_src.emissiveTexture.index)); + var texture = await getTexture(GetTextureParam.Create(src.emissiveTexture.index)); if (texture != null) { material.SetTexture("_EmissionMap", texture); } // Texture Offset and Scale - SetTextureOffsetAndScale(material, m_src.emissiveTexture, "_EmissionMap"); + MaterialItemBase.SetTextureOffsetAndScale(material, src.emissiveTexture, "_EmissionMap"); } } BlendMode blendMode = BlendMode.Opaque; // https://forum.unity.com/threads/standard-material-shader-ignoring-setfloat-property-_mode.344557/#post-2229980 - switch (m_src.alphaMode) + switch (src.alphaMode) { case "BLEND": blendMode = BlendMode.Fade; @@ -173,7 +169,7 @@ namespace UniGLTF material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); - material.SetFloat("_Cutoff", m_src.alphaCutoff); + material.SetFloat("_Cutoff", src.alphaCutoff); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs index cadf7272c..9f5a645fe 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs @@ -3,55 +3,48 @@ using UnityEngine; namespace UniGLTF { - public class UnlitMaterialItem : MaterialItemBase + public static class UnlitMaterialItem { public const string ShaderName = "UniGLTF/UniUnlit"; - bool m_hasVertexColor; - - public UnlitMaterialItem(int i, glTFMaterial src, bool hasVertexColor) : base(i, src) - { - m_hasVertexColor = hasVertexColor; - } - - public override async Task GetOrCreateAsync(GetTextureAsyncFunc getTexture) + public static async Task CreateAsync(int i, glTFMaterial src, GetTextureAsyncFunc getTexture, bool hasVertexColor) { if (getTexture == null) { getTexture = _ => Task.FromResult(null); } - var material = CreateMaterial(ShaderName); + var material = MaterialItemBase.CreateMaterial(i, src, ShaderName); // texture - if (m_src.pbrMetallicRoughness.baseColorTexture != null) + if (src.pbrMetallicRoughness.baseColorTexture != null) { - material.mainTexture = await getTexture(GetTextureParam.Create(m_src.pbrMetallicRoughness.baseColorTexture.index)); + material.mainTexture = await getTexture(GetTextureParam.Create(src.pbrMetallicRoughness.baseColorTexture.index)); // Texture Offset and Scale - SetTextureOffsetAndScale(material, m_src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); + MaterialItemBase.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); } // color - if (m_src.pbrMetallicRoughness.baseColorFactor != null && m_src.pbrMetallicRoughness.baseColorFactor.Length == 4) + if (src.pbrMetallicRoughness.baseColorFactor != null && src.pbrMetallicRoughness.baseColorFactor.Length == 4) { - var color = m_src.pbrMetallicRoughness.baseColorFactor; + var color = src.pbrMetallicRoughness.baseColorFactor; material.color = (new Color(color[0], color[1], color[2], color[3])).gamma; } //renderMode - if (m_src.alphaMode == "OPAQUE") + if (src.alphaMode == "OPAQUE") { UniUnlit.Utils.SetRenderMode(material, UniUnlit.UniUnlitRenderMode.Opaque); } - else if (m_src.alphaMode == "BLEND") + else if (src.alphaMode == "BLEND") { UniUnlit.Utils.SetRenderMode(material, UniUnlit.UniUnlitRenderMode.Transparent); } - else if (m_src.alphaMode == "MASK") + else if (src.alphaMode == "MASK") { UniUnlit.Utils.SetRenderMode(material, UniUnlit.UniUnlitRenderMode.Cutout); - material.SetFloat("_Cutoff", m_src.alphaCutoff); + material.SetFloat("_Cutoff", src.alphaCutoff); } else { @@ -60,7 +53,7 @@ namespace UniGLTF } // culling - if (m_src.doubleSided) + if (src.doubleSided) { UniUnlit.Utils.SetCullMode(material, UniUnlit.UniUnlitCullMode.Off); } @@ -70,7 +63,7 @@ namespace UniGLTF } // VColor - if (m_hasVertexColor) + if (hasVertexColor) { UniUnlit.Utils.SetVColBlendMode(material, UniUnlit.UniUnlitVertexColorBlendOp.Multiply); } diff --git a/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs b/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs index 0860a5199..b4e47e580 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs @@ -3,6 +3,7 @@ using NUnit.Framework; using UnityEngine; using UniJSON; using System.Linq; +using System.Threading.Tasks; namespace UniGLTF { @@ -32,7 +33,7 @@ namespace UniGLTF var gltfMaterial = materialExporter.ExportMaterial(srcMaterial, textureManager); gltfMaterial.pbrMetallicRoughness.baseColorTexture.extensions = gltfMaterial.pbrMetallicRoughness.baseColorTexture.extensions.Deserialize(); - var dstMaterial = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var dstMaterial = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual(dstMaterial.mainTextureOffset.x, offset.x, 0.3f); Assert.AreEqual(dstMaterial.mainTextureOffset.y, offset.y, 0.2f); @@ -80,7 +81,7 @@ namespace UniGLTF Assert.IsTrue(glTF_KHR_materials_unlit.IsEnable(gltfMaterial)); - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } } @@ -99,7 +100,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -114,7 +115,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -130,7 +131,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -145,7 +146,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -160,7 +161,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -176,7 +177,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -191,7 +192,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -207,7 +208,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -217,7 +218,7 @@ namespace UniGLTF { extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialFactory.CreateMaterial(0, gltfMaterial, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } } @@ -225,7 +226,7 @@ namespace UniGLTF [Test] public void MaterialImportTest() { - var material = MaterialFactory.CreateMaterial(0, new glTFMaterial { }, false).GetOrCreateForTest(); + var material = MaterialItemBase.CreateMaterialForTest(0, new glTFMaterial { }); Assert.AreEqual("Standard", material.shader.name); } diff --git a/Assets/VRM/Runtime/IO/VRMImporterContext.cs b/Assets/VRM/Runtime/IO/VRMImporterContext.cs index 76d8a2a5b..9c7c7efa1 100644 --- a/Assets/VRM/Runtime/IO/VRMImporterContext.cs +++ b/Assets/VRM/Runtime/IO/VRMImporterContext.cs @@ -43,7 +43,7 @@ namespace VRM { VRM = vrm; // override material importer - MaterialFactory.MaterialImporter = new VRMMaterialImporter(VRM.materialProperties).CreateMaterial; + MaterialFactory.CreateMaterialAsync = new VRMMaterialImporter(VRM.materialProperties).CreateMaterial; } else { @@ -198,9 +198,8 @@ namespace VRM } } - var material = MaterialFactory.GetMaterials() - .FirstOrDefault(y => y.Name == x.materialName) - .GetOrCreateAsync(MaterialFactory.GetTextureAsync).Result; + var material = MaterialFactory.Materials + .FirstOrDefault(y => y.name == x.materialName); var propertyName = x.propertyName; if (x.propertyName.FastEndsWith("_ST_S") || x.propertyName.FastEndsWith("_ST_T")) diff --git a/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs b/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs index 26caed56c..85b6acf22 100644 --- a/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs +++ b/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace VRM { - public class MToonMaterialItem : MaterialItemBase + public static class MToonMaterialItem { static string[] VRM_SHADER_NAMES = { @@ -21,18 +21,9 @@ namespace VRM "VRM/UnlitTransparentZWrite", }; - glTF_VRM_Material m_vrmMaterial; - bool m_hasVertexColor; - - public MToonMaterialItem(int i, glTFMaterial src, bool hasVertexColor, glTF_VRM_Material vrmMaterial) : base(i, src) + public static async Task CreateAsync(glTF gltf, int m_index, glTF_VRM_Material vrmMaterial, GetTextureAsyncFunc getTexture) { - m_hasVertexColor = hasVertexColor; - m_vrmMaterial = vrmMaterial; - } - - public override async Task GetOrCreateAsync(GetTextureAsyncFunc getTexture) - { - var item = m_vrmMaterial; + var item = vrmMaterial; var shaderName = item.shader; var shader = Shader.Find(shaderName); if (shader == null) @@ -48,7 +39,7 @@ namespace VRM { Debug.LogWarningFormat("unknown shader {0}.", shaderName); } - return await MaterialFactory.CreateMaterial(m_index, m_src, m_hasVertexColor).GetOrCreateAsync(getTexture); + return await MaterialItemBase.DefaultCreateMaterialAsync(gltf, m_index, getTexture); } // @@ -120,15 +111,15 @@ namespace VRM m_materials = materials; } - public MaterialItemBase CreateMaterial(int i, glTFMaterial src, bool hasVertexColor) + public Task CreateMaterial(glTF gltf, int i, GetTextureAsyncFunc getTexture) { if (i == 0 && m_materials.Count == 0) { // dummy - return new PBRMaterialItem(i, src); + return MaterialItemBase.DefaultCreateMaterialAsync(gltf, i, getTexture); } - return new MToonMaterialItem(i, src, hasVertexColor, m_materials[i]); + return MToonMaterialItem.CreateAsync(gltf, i, m_materials[i], getTexture); } } } From 6f3d3e3f2b5823b0e57056f17b8e3d0a2cecbcf5 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Fri, 12 Feb 2021 21:48:47 +0900 Subject: [PATCH 09/16] fix deadlock --- .../Runtime/Extensions/TaskExtensions.cs | 21 +++++++++++++++++++ .../Runtime/Extensions/TaskExtensions.cs.meta | 11 ++++++++++ .../MaterialFacotry/MaterialFactory.cs | 1 + .../TextureLoader/GltfTextureLoader.cs | 10 ++++----- .../UnityWebRequestTextureLoader.cs | 12 ++--------- 5 files changed, 39 insertions(+), 16 deletions(-) create mode 100644 Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs create mode 100644 Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs.meta diff --git a/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs b/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs new file mode 100644 index 000000000..4326925c3 --- /dev/null +++ b/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs @@ -0,0 +1,21 @@ +using System.Collections; +using System.Threading.Tasks; + +namespace UniGLTF +{ + public static class TaskExtensions + { + public static IEnumerator AsIEnumerator(this Task task) + { + while (!task.IsCompleted) + { + yield return null; + } + + if (task.IsFaulted) + { + throw task.Exception; + } + } + } +} diff --git a/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs.meta b/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs.meta new file mode 100644 index 000000000..b42a81728 --- /dev/null +++ b/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 54481e2d4da20ec4fa15376518f2e938 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 060143ef7..2ceb79a20 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -145,6 +145,7 @@ namespace UniGLTF if (m_gltf.materials == null || m_gltf.materials.Count == 0) { var task = CreateMaterialAsync(m_gltf, 0, GetTextureAsync); + while (!task.IsCompleted) { yield return null; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs index 50eb5c3de..b557fb49c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs @@ -27,12 +27,10 @@ namespace UniGLTF public static async Task LoadTextureAsync(glTF gltf, IStorage storage, int index) { string m_textureName = default; - var imageBytes = await Task.Run(() => - { - var imageIndex = gltf.GetImageIndexFromTextureIndex(index); - var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); - return ToArray(segments); - }); + + var imageIndex = gltf.GetImageIndexFromTextureIndex(index); + var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); + var imageBytes = ToArray(segments); // // texture from image(png etc) bytes diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs index 226565715..347fa074e 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs @@ -55,16 +55,8 @@ namespace UniGLTF public IEnumerator ProcessOnMainThread(glTF gltf, IStorage storage, bool isLinear, glTFTextureSampler sampler) { - ArraySegment bytes = default; - var task = Task.Run(() => - { - var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); - bytes = gltf.GetImageBytes(storage, imageIndex, out m_textureName); - }); - while (!task.IsCompleted) - { - yield return null; - } + var imageIndex = gltf.GetImageIndexFromTextureIndex(m_textureIndex); + var bytes = gltf.GetImageBytes(storage, imageIndex, out m_textureName); // tmp file var tmp = Path.GetTempFileName(); From 56772ff03da84c45e82731204d37ce007cb654ae Mon Sep 17 00:00:00 2001 From: ousttrue Date: Fri, 12 Feb 2021 22:01:58 +0900 Subject: [PATCH 10/16] fix --- .../UniGLTF/MaterialFacotry/MaterialFactory.cs | 11 +++++++++-- .../UniGLTF/MaterialFacotry/MaterialItemBase.cs | 7 ++++++- .../TextureLoader/GltfTextureLoader.cs | 6 +++--- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 2ceb79a20..adcc9cc8a 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -58,8 +58,15 @@ namespace UniGLTF return texture; } - texture = await LoadTextureAsync(param.Index0.Value); - m_textureCache.Add(GetTextureParam.Create(param.Index0.Value), texture); + { + var defaultParam = GetTextureParam.Create(param.Index0.Value); + if (!m_textureCache.TryGetValue(defaultParam, out texture)) + { + texture = await LoadTextureAsync(param.Index0.Value); + m_textureCache.Add(defaultParam, texture); + } + } + switch (param.TextureType) { case GetTextureParam.NORMAL_PROP: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs index 86e51d7e0..9d8538c8e 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs @@ -71,7 +71,12 @@ namespace UniGLTF /// public static Material CreateMaterialForTest(int i, glTFMaterial material) { - throw new System.NotImplementedException(); + var gltf = new glTF + { + materials = new System.Collections.Generic.List { material }, + }; + var task = DefaultCreateMaterialAsync(gltf, i, null); + return task.Result; } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs index b557fb49c..cb91fe3e3 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs @@ -24,10 +24,10 @@ namespace UniGLTF } } - public static async Task LoadTextureAsync(glTF gltf, IStorage storage, int index) + public static Task LoadTextureAsync(glTF gltf, IStorage storage, int index) { string m_textureName = default; - + var imageIndex = gltf.GetImageIndexFromTextureIndex(index); var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); var imageBytes = ToArray(segments); @@ -50,7 +50,7 @@ namespace UniGLTF { TextureSamplerUtil.SetSampler(texture, sampler); } - return texture; + return Task.FromResult(texture); } } } From e1d364718138022d31b93c5e4d8c455881669d16 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Mon, 15 Feb 2021 13:21:01 +0900 Subject: [PATCH 11/16] =?UTF-8?q?Editor=20=E3=82=B9=E3=82=AF=E3=83=AA?= =?UTF-8?q?=E3=83=97=E3=83=88=E3=81=A7=20UnitySynchronizationContext.Exec?= =?UTF-8?q?=20=E3=82=92=E3=82=AD=E3=83=83=E3=82=AF=E3=81=99=E3=82=8B?= =?UTF-8?q?=E5=AF=BE=E7=AD=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Runtime/Extensions/TaskExtensions.cs | 41 ++++++++++++++++++- .../MaterialFacotry/MaterialFactory.cs | 8 ++-- .../TextureLoader/GltfTextureLoader.cs | 13 +++--- Assets/VRM/Runtime/IO/VRMImporterContext.cs | 4 +- 4 files changed, 54 insertions(+), 12 deletions(-) diff --git a/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs b/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs index 4326925c3..f20c48fc8 100644 --- a/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs +++ b/Assets/UniGLTF/Runtime/Extensions/TaskExtensions.cs @@ -1,15 +1,52 @@ -using System.Collections; +using System; +using System.Collections; +using System.Reflection; +using System.Threading; using System.Threading.Tasks; namespace UniGLTF { + /// + /// work around + /// + /// https://forum.unity.com/threads/async-await-in-editor-script.481276/ + /// + /// https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Scripting/UnitySynchronizationContext.cs + /// + /// + /// + /// public static class TaskExtensions { - public static IEnumerator AsIEnumerator(this Task task) + delegate void ExecFunc(); + + static ExecFunc s_exec; + + static void Invoke() + { + if (s_exec == null) + { + var context = SynchronizationContext.Current; + var t = context.GetType(); + var execMethod = t.GetMethod("Exec", BindingFlags.NonPublic | BindingFlags.Instance); + var exec = execMethod.CreateDelegate(typeof(ExecFunc), context); + s_exec = (ExecFunc)exec; + } + s_exec(); + } + + public static IEnumerable AsIEnumerator(this Task task) { while (!task.IsCompleted) { yield return null; + +#if UNITY_EDITOR + if (!UnityEngine.Application.isPlaying) + { + Invoke(); + } +#endif } if (task.IsFaulted) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index adcc9cc8a..a49b368e1 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -153,10 +153,11 @@ namespace UniGLTF { var task = CreateMaterialAsync(m_gltf, 0, GetTextureAsync); - while (!task.IsCompleted) + foreach (var x in task.AsIEnumerator()) { - yield return null; + yield return x; } + AddMaterial(task.Result); } else @@ -164,10 +165,11 @@ namespace UniGLTF for (int i = 0; i < m_gltf.materials.Count; ++i) { var task = CreateMaterialAsync(m_gltf, i, GetTextureAsync); - while (!task.IsCompleted) + foreach (var x in task.AsIEnumerator()) { yield return null; } + AddMaterial(task.Result); } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs index cb91fe3e3..0ba1a2583 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs @@ -24,13 +24,16 @@ namespace UniGLTF } } - public static Task LoadTextureAsync(glTF gltf, IStorage storage, int index) + public static async Task LoadTextureAsync(glTF gltf, IStorage storage, int index) { string m_textureName = default; - var imageIndex = gltf.GetImageIndexFromTextureIndex(index); - var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); - var imageBytes = ToArray(segments); + var imageBytes = await Task.Run(() => + { + var imageIndex = gltf.GetImageIndexFromTextureIndex(index); + var segments = gltf.GetImageBytes(storage, imageIndex, out m_textureName); + return ToArray(segments); + }); // // texture from image(png etc) bytes @@ -50,7 +53,7 @@ namespace UniGLTF { TextureSamplerUtil.SetSampler(texture, sampler); } - return Task.FromResult(texture); + return texture; } } } diff --git a/Assets/VRM/Runtime/IO/VRMImporterContext.cs b/Assets/VRM/Runtime/IO/VRMImporterContext.cs index 9c7c7efa1..bd73d1959 100644 --- a/Assets/VRM/Runtime/IO/VRMImporterContext.cs +++ b/Assets/VRM/Runtime/IO/VRMImporterContext.cs @@ -59,9 +59,9 @@ namespace VRM using (MeasureTime("VRM LoadMeta")) { var task = LoadMetaAsync(); - while (!task.IsCompleted) + foreach (var x in task.AsIEnumerator()) { - yield return null; + yield return x; } } yield return null; From 48f51d33a79c55a55edd04ceca2f4420943dc1d8 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Mon, 15 Feb 2021 13:31:09 +0900 Subject: [PATCH 12/16] TextureItem.CopyTexture to TextureConverter.CopyTexture --- .../Runtime/UniGLTF/IO/TextureConverter.cs | 147 +++++++++++++++- .../UniGLTF/IO/TextureExportManager.cs | 2 +- .../UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs | 14 +- .../UniGLTF/MaterialFacotry/TextureItem.cs | 157 ------------------ .../MaterialFacotry/TextureItem.cs.meta | 13 -- 5 files changed, 154 insertions(+), 179 deletions(-) delete mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs delete mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureConverter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureConverter.cs index d6323588a..3b400d799 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureConverter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureConverter.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using UnityEngine; +using System.IO; #if UNITY_EDITOR using UnityEditor; #endif @@ -20,7 +21,7 @@ namespace UniGLTF public static Texture2D Convert(Texture2D texture, glTFTextureTypes textureType, ColorConversion colorConversion, Material convertMaterial) { - var copyTexture = TextureItem.CopyTexture(texture, TextureIO.GetColorSpace(textureType), convertMaterial); + var copyTexture = CopyTexture(texture, TextureIO.GetColorSpace(textureType), convertMaterial); if (colorConversion != null) { copyTexture.SetPixels32(copyTexture.GetPixels32().Select(x => colorConversion(x)).ToArray()); @@ -45,6 +46,150 @@ namespace UniGLTF texture.name = texture.name.Replace(extension, ""); } } + + struct ColorSpaceScope : IDisposable + { + bool m_sRGBWrite; + + public ColorSpaceScope(RenderTextureReadWrite colorSpace) + { + m_sRGBWrite = GL.sRGBWrite; + switch (colorSpace) + { + case RenderTextureReadWrite.Linear: + GL.sRGBWrite = false; + break; + + case RenderTextureReadWrite.sRGB: + default: + GL.sRGBWrite = true; + break; + } + } + public ColorSpaceScope(bool sRGBWrite) + { + m_sRGBWrite = GL.sRGBWrite; + GL.sRGBWrite = sRGBWrite; + } + + public void Dispose() + { + GL.sRGBWrite = m_sRGBWrite; + } + } + +#if UNITY_EDITOR && VRM_DEVELOP + [MenuItem("Assets/CopySRGBWrite", true)] + static bool CopySRGBWriteIsEnable() + { + return Selection.activeObject is Texture; + } + + [MenuItem("Assets/CopySRGBWrite")] + static void CopySRGBWrite() + { + CopySRGBWrite(true); + } + + [MenuItem("Assets/CopyNotSRGBWrite", true)] + static bool CopyNotSRGBWriteIsEnable() + { + return Selection.activeObject is Texture; + } + + [MenuItem("Assets/CopyNotSRGBWrite")] + static void CopyNotSRGBWrite() + { + CopySRGBWrite(false); + } + + static string AddPath(string path, string add) + { + return string.Format("{0}/{1}{2}{3}", + Path.GetDirectoryName(path), + Path.GetFileNameWithoutExtension(path), + add, + Path.GetExtension(path)); + } + + static void CopySRGBWrite(bool isSRGB) + { + var src = Selection.activeObject as Texture; + var texturePath = UnityPath.FromAsset(src); + + var path = EditorUtility.SaveFilePanel("save prefab", "Assets", + Path.GetFileNameWithoutExtension(AddPath(texturePath.FullPath, ".sRGB")), "prefab"); + var assetPath = UnityPath.FromFullpath(path); + if (!assetPath.IsUnderAssetsFolder) + { + return; + } + Debug.LogFormat("[CopySRGBWrite] {0} => {1}", texturePath, assetPath); + + var renderTexture = new RenderTexture(src.width, src.height, 0, + RenderTextureFormat.ARGB32, + RenderTextureReadWrite.sRGB); + using (var scope = new ColorSpaceScope(isSRGB)) + { + Graphics.Blit(src, renderTexture); + } + + var dst = new Texture2D(src.width, src.height, TextureFormat.ARGB32, false, + RenderTextureReadWrite.sRGB == RenderTextureReadWrite.Linear); + dst.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0); + dst.Apply(); + + RenderTexture.active = null; + + assetPath.CreateAsset(dst); + + GameObject.DestroyImmediate(renderTexture); + } +#endif + + public static Texture2D CopyTexture(Texture src, RenderTextureReadWrite colorSpace, Material material) + { + Texture2D dst = null; + + var renderTexture = new RenderTexture(src.width, src.height, 0, RenderTextureFormat.ARGB32, colorSpace); + + using (var scope = new ColorSpaceScope(colorSpace)) + { + if (material != null) + { + Graphics.Blit(src, renderTexture, material); + } + else + { + Graphics.Blit(src, renderTexture); + } + } + + dst = new Texture2D(src.width, src.height, TextureFormat.ARGB32, false, colorSpace == RenderTextureReadWrite.Linear); + dst.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0); + dst.name = src.name; + dst.anisoLevel = src.anisoLevel; + dst.filterMode = src.filterMode; + dst.mipMapBias = src.mipMapBias; + dst.wrapMode = src.wrapMode; +#if UNITY_2017_1_OR_NEWER + dst.wrapModeU = src.wrapModeU; + dst.wrapModeV = src.wrapModeV; + dst.wrapModeW = src.wrapModeW; +#endif + dst.Apply(); + + RenderTexture.active = null; + if (Application.isEditor) + { + GameObject.DestroyImmediate(renderTexture); + } + else + { + GameObject.Destroy(renderTexture); + } + return dst; + } } public class MetallicRoughnessConverter : ITextureConverter diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureExportManager.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureExportManager.cs index 6a1baad95..54806083e 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureExportManager.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureExportManager.cs @@ -66,7 +66,7 @@ namespace UniGLTF #endif // ToDo: may already exists - m_exportTextures[index] = TextureItem.CopyTexture(texture, readWrite, null); + m_exportTextures[index] = TextureConverter.CopyTexture(texture, readWrite, null); return index; } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs index ff01045bf..61b160eed 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO.cs @@ -52,7 +52,7 @@ namespace UniGLTF { foreach (var material in glTf.materials) { - var textureInfo = material.GetTextures().FirstOrDefault(x => (x!=null) && x.index == textureIndex); + var textureInfo = material.GetTextures().FirstOrDefault(x => (x != null) && x.index == textureIndex); if (textureInfo != null) { return textureInfo.TextureType; @@ -109,10 +109,10 @@ namespace UniGLTF var getSizeMethod = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance); if (textureImporter != null && getSizeMethod != null) { - var args = new object[2] {0, 0}; + var args = new object[2] { 0, 0 }; getSizeMethod.Invoke(textureImporter, args); - var originalWidth = (int) args[0]; - var originalHeight = (int) args[1]; + var originalWidth = (int)args[0]; + var originalHeight = (int)args[1]; var originalSize = Mathf.Max(originalWidth, originalHeight); var requiredMaxSize = textureImporter.maxTextureSize; @@ -122,12 +122,12 @@ namespace UniGLTF { return ( - TextureItem.CopyTexture(texture, GetColorSpace(textureType), null).EncodeToPNG(), + TextureConverter.CopyTexture(texture, GetColorSpace(textureType), null).EncodeToPNG(), "image/png" ); } } - + if (path.Extension == ".png") { return @@ -149,7 +149,7 @@ namespace UniGLTF return ( - TextureItem.CopyTexture(texture, TextureIO.GetColorSpace(textureType), null).EncodeToPNG(), + TextureConverter.CopyTexture(texture, TextureIO.GetColorSpace(textureType), null).EncodeToPNG(), "image/png" ); } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs deleted file mode 100644 index 320e23cb5..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs +++ /dev/null @@ -1,157 +0,0 @@ -using UnityEngine; -using System.IO; -using System; -#if UNITY_EDITOR -using UnityEditor; -#endif - - -namespace UniGLTF -{ - public static class TextureItem - { - struct ColorSpaceScope : IDisposable - { - bool m_sRGBWrite; - - public ColorSpaceScope(RenderTextureReadWrite colorSpace) - { - m_sRGBWrite = GL.sRGBWrite; - switch (colorSpace) - { - case RenderTextureReadWrite.Linear: - GL.sRGBWrite = false; - break; - - case RenderTextureReadWrite.sRGB: - default: - GL.sRGBWrite = true; - break; - } - } - public ColorSpaceScope(bool sRGBWrite) - { - m_sRGBWrite = GL.sRGBWrite; - GL.sRGBWrite = sRGBWrite; - } - - public void Dispose() - { - GL.sRGBWrite = m_sRGBWrite; - } - } - -#if UNITY_EDITOR && VRM_DEVELOP - [MenuItem("Assets/CopySRGBWrite", true)] - static bool CopySRGBWriteIsEnable() - { - return Selection.activeObject is Texture; - } - - [MenuItem("Assets/CopySRGBWrite")] - static void CopySRGBWrite() - { - CopySRGBWrite(true); - } - - [MenuItem("Assets/CopyNotSRGBWrite", true)] - static bool CopyNotSRGBWriteIsEnable() - { - return Selection.activeObject is Texture; - } - - [MenuItem("Assets/CopyNotSRGBWrite")] - static void CopyNotSRGBWrite() - { - CopySRGBWrite(false); - } - - static string AddPath(string path, string add) - { - return string.Format("{0}/{1}{2}{3}", - Path.GetDirectoryName(path), - Path.GetFileNameWithoutExtension(path), - add, - Path.GetExtension(path)); - } - - static void CopySRGBWrite(bool isSRGB) - { - var src = Selection.activeObject as Texture; - var texturePath = UnityPath.FromAsset(src); - - var path = EditorUtility.SaveFilePanel("save prefab", "Assets", - Path.GetFileNameWithoutExtension(AddPath(texturePath.FullPath, ".sRGB")), "prefab"); - var assetPath = UnityPath.FromFullpath(path); - if (!assetPath.IsUnderAssetsFolder) - { - return; - } - Debug.LogFormat("[CopySRGBWrite] {0} => {1}", texturePath, assetPath); - - var renderTexture = new RenderTexture(src.width, src.height, 0, - RenderTextureFormat.ARGB32, - RenderTextureReadWrite.sRGB); - using (var scope = new ColorSpaceScope(isSRGB)) - { - Graphics.Blit(src, renderTexture); - } - - var dst = new Texture2D(src.width, src.height, TextureFormat.ARGB32, false, - RenderTextureReadWrite.sRGB == RenderTextureReadWrite.Linear); - dst.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0); - dst.Apply(); - - RenderTexture.active = null; - - assetPath.CreateAsset(dst); - - GameObject.DestroyImmediate(renderTexture); - } -#endif - - public static Texture2D CopyTexture(Texture src, RenderTextureReadWrite colorSpace, Material material) - { - Texture2D dst = null; - - var renderTexture = new RenderTexture(src.width, src.height, 0, RenderTextureFormat.ARGB32, colorSpace); - - using (var scope = new ColorSpaceScope(colorSpace)) - { - if (material != null) - { - Graphics.Blit(src, renderTexture, material); - } - else - { - Graphics.Blit(src, renderTexture); - } - } - - dst = new Texture2D(src.width, src.height, TextureFormat.ARGB32, false, colorSpace == RenderTextureReadWrite.Linear); - dst.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0); - dst.name = src.name; - dst.anisoLevel = src.anisoLevel; - dst.filterMode = src.filterMode; - dst.mipMapBias = src.mipMapBias; - dst.wrapMode = src.wrapMode; -#if UNITY_2017_1_OR_NEWER - dst.wrapModeU = src.wrapModeU; - dst.wrapModeV = src.wrapModeV; - dst.wrapModeW = src.wrapModeW; -#endif - dst.Apply(); - - RenderTexture.active = null; - if (Application.isEditor) - { - GameObject.DestroyImmediate(renderTexture); - } - else - { - GameObject.Destroy(renderTexture); - } - return dst; - } - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs.meta deleted file mode 100644 index 880411948..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureItem.cs.meta +++ /dev/null @@ -1,13 +0,0 @@ -fileFormatVersion: 2 -guid: 09cdeb503b1e8234faf528b6ae134e7a -timeCreated: 1519799583 -licenseType: Free -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From 693cc665c285846d8a1a80ac933c791c4befd9d0 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Mon, 15 Feb 2021 13:44:30 +0900 Subject: [PATCH 13/16] Separate TextureFactory from MaterialFactory --- .../Runtime/UniGLTF/IO/ImporterContext.cs | 17 +- .../MaterialFacotry/MaterialFactory.cs | 162 ++++-------------- .../MaterialFacotry/TextureLoader.meta | 2 +- .../{ => TextureLoader}/GetTextureParam.cs | 1 - .../GetTextureParam.cs.meta | 2 +- .../TextureLoader/TextureFactory.cs | 126 ++++++++++++++ .../TextureLoader/TextureFactory.cs.meta | 11 ++ .../Runtime/UniGLTF/TextureLoader.meta | 8 + Assets/VRM/Runtime/IO/VRMImporterContext.cs | 2 +- 9 files changed, 195 insertions(+), 136 deletions(-) rename Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/{ => TextureLoader}/GetTextureParam.cs (95%) rename Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/{ => TextureLoader}/GetTextureParam.cs.meta (83%) create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs.meta create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index 12098ecdd..53fd5ae6d 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -108,6 +108,9 @@ namespace UniGLTF MaterialFactory m_materialFactory; public MaterialFactory MaterialFactory => m_materialFactory; + TextureFactory m_textureFactory; + public TextureFactory TextureFactory => m_textureFactory; + public ImporterContext() { } @@ -499,7 +502,13 @@ namespace UniGLTF { // root task. do nothing }) - .ContinueWithCoroutine(Scheduler.MainThread, m_materialFactory.LoadMaterials) + .ContinueWithCoroutine(Scheduler.MainThread, () => + { + using (MeasureTime("LoadMaterials")) + { + return m_materialFactory.LoadMaterials(m_textureFactory.GetTextureAsync); + } + }) .OnExecute(Scheduler.ThreadPool, parent => { // UniGLTF does not support draco @@ -690,6 +699,10 @@ namespace UniGLTF protected virtual IEnumerable ObjectsForSubAsset() { + foreach (var x in TextureFactory.ObjectsForSubAsset()) + { + yield return x; + } foreach (var x in MaterialFactory.ObjectsForSubAsset()) { yield return x; @@ -885,7 +898,7 @@ namespace UniGLTF } // texture will load from assets - m_materialFactory.ImageBaseDir = prefabParentDir; + m_textureFactory.ImageBaseDir = prefabParentDir; } #endregion #endif diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index a49b368e1..17b8b0426 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -4,9 +4,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using UnityEngine; -#if UNITY_EDITOR -using UnityEditor; -#endif namespace UniGLTF { @@ -20,8 +17,6 @@ namespace UniGLTF m_storage = storage; } - public UnityPath ImageBaseDir { get; set; } - public delegate Task CreateMaterialAsyncFunc(glTF glTF, int i, GetTextureAsyncFunc getTexture); CreateMaterialAsyncFunc m_createMaterialAsync; public CreateMaterialAsyncFunc CreateMaterialAsync @@ -40,85 +35,24 @@ namespace UniGLTF } } - List m_textuers = new List(); - Dictionary m_textureCache = new Dictionary(); - - /// - /// テクスチャーをロード、必要であれば変換して返す。 - /// 同じものはキャッシュを返す - /// - /// 変換の有無を判断する: METALLIC_GLOSS_PROP - /// METALLIC_GLOSS_PROPの追加パラメーター - /// gltf の texture index - /// - public async Task GetTextureAsync(GetTextureParam param) - { - if (m_textureCache.TryGetValue(param, out Texture2D texture)) - { - return texture; - } - - { - var defaultParam = GetTextureParam.Create(param.Index0.Value); - if (!m_textureCache.TryGetValue(defaultParam, out texture)) - { - texture = await LoadTextureAsync(param.Index0.Value); - m_textureCache.Add(defaultParam, texture); - } - } - - switch (param.TextureType) - { - case GetTextureParam.NORMAL_PROP: - { - if (Application.isPlaying) - { - var converted = new NormalConverter().GetImportTexture(texture); - m_textureCache.Add(param, converted); - return converted; - } - else - { -#if UNITY_EDITOR - var textureAssetPath = AssetDatabase.GetAssetPath(texture); - if (!string.IsNullOrEmpty(textureAssetPath)) - { - TextureIO.MarkTextureAssetAsNormalMap(textureAssetPath); - } - else - { - Debug.LogWarningFormat("no asset for {0}", texture); - } -#endif - m_textureCache.Add(param, texture); - return texture; - } - } - - case GetTextureParam.METALLIC_GLOSS_PROP: - { - // Bake roughnessFactor values into a texture. - var converted = new MetallicRoughnessConverter(param.MetallicFactor).GetImportTexture(texture); - m_textureCache.Add(param, converted); - return converted; - } - - case GetTextureParam.OCCLUSION_PROP: - { - var converted = new OcclusionConverter().GetImportTexture(texture); - m_textureCache.Add(param, converted); - return converted; - } - - default: - return texture; - } - - throw new NotImplementedException(); - } - List m_materials = new List(); public IReadOnlyList Materials => m_materials; + public void Dispose() + { + foreach (var x in ObjectsForSubAsset()) + { + UnityEngine.Object.DestroyImmediate(x, true); + } + } + + public IEnumerable ObjectsForSubAsset() + { + foreach (var x in m_materials) + { + yield return x; + } + } + public void AddMaterial(Material material) { var originalName = material.name; @@ -136,65 +70,33 @@ namespace UniGLTF return m_materials[index]; } - public virtual Task LoadTextureAsync(int index) + public IEnumerator LoadMaterials(GetTextureAsyncFunc getTexture) { -#if UNIGLTF_USE_WEBREQUEST_TEXTURELOADER - return UnityWebRequestTextureLoader.LoadTextureAsync(index); -#else - return GltfTextureLoader.LoadTextureAsync(m_gltf, m_storage, index); -#endif - } - - public IEnumerator LoadMaterials() - { - // using (MeasureTime("LoadMaterials")) + if (m_gltf.materials == null || m_gltf.materials.Count == 0) { - if (m_gltf.materials == null || m_gltf.materials.Count == 0) - { - var task = CreateMaterialAsync(m_gltf, 0, GetTextureAsync); + var task = CreateMaterialAsync(m_gltf, 0, getTexture); + foreach (var x in task.AsIEnumerator()) + { + yield return x; + } + + AddMaterial(task.Result); + } + else + { + for (int i = 0; i < m_gltf.materials.Count; ++i) + { + var task = CreateMaterialAsync(m_gltf, i, getTexture); foreach (var x in task.AsIEnumerator()) { - yield return x; + yield return null; } AddMaterial(task.Result); } - else - { - for (int i = 0; i < m_gltf.materials.Count; ++i) - { - var task = CreateMaterialAsync(m_gltf, i, GetTextureAsync); - foreach (var x in task.AsIEnumerator()) - { - yield return null; - } - - AddMaterial(task.Result); - } - } } yield return null; } - - public void Dispose() - { - foreach (var x in ObjectsForSubAsset()) - { - UnityEngine.Object.DestroyImmediate(x, true); - } - } - - public IEnumerable ObjectsForSubAsset() - { - foreach (var kv in m_textureCache) - { - yield return kv.Value; - } - foreach (var x in m_materials) - { - yield return x; - } - } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta index 84d4a147d..1ef61d2aa 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 54a405d31cce94643be8f76f805da8c8 +guid: a4bd2e8f388fb204186d743f337ddb83 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs similarity index 95% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs rename to Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs index c712f34f5..c2bce5fbc 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs @@ -51,5 +51,4 @@ namespace UniGLTF } } - public delegate Task GetTextureAsyncFunc(GetTextureParam param); } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs.meta similarity index 83% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs.meta index d5bf2ad96..cdeb33876 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/GetTextureParam.cs.meta +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8f1dc05e4970e724e9f50c0a5a67a25e +guid: 405597f56d6540347bbecb1203aba033 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs new file mode 100644 index 000000000..fc20ef08e --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using UnityEditor; +using UnityEngine; + +namespace UniGLTF +{ + public delegate Task GetTextureAsyncFunc(GetTextureParam param); + public class TextureFactory : IDisposable + + { + glTF m_gltf; + IStorage m_storage; + + public UnityPath ImageBaseDir { get; set; } + + public TextureFactory(glTF gltf, IStorage storage) + { + m_gltf = gltf; + m_storage = storage; + } + + List m_textuers = new List(); + public void Dispose() + { + foreach (var x in ObjectsForSubAsset()) + { + UnityEngine.Object.DestroyImmediate(x, true); + } + } + + public IEnumerable ObjectsForSubAsset() + { + foreach (var kv in m_textureCache) + { + yield return kv.Value; + } + } + + Dictionary m_textureCache = new Dictionary(); + + public virtual Task LoadTextureAsync(int index) + { +#if UNIGLTF_USE_WEBREQUEST_TEXTURELOADER + return UnityWebRequestTextureLoader.LoadTextureAsync(index); +#else + return GltfTextureLoader.LoadTextureAsync(m_gltf, m_storage, index); +#endif + } + + /// + /// テクスチャーをロード、必要であれば変換して返す。 + /// 同じものはキャッシュを返す + /// + /// 変換の有無を判断する: METALLIC_GLOSS_PROP + /// METALLIC_GLOSS_PROPの追加パラメーター + /// gltf の texture index + /// + public async Task GetTextureAsync(GetTextureParam param) + { + if (m_textureCache.TryGetValue(param, out Texture2D texture)) + { + return texture; + } + + { + var defaultParam = GetTextureParam.Create(param.Index0.Value); + if (!m_textureCache.TryGetValue(defaultParam, out texture)) + { + texture = await LoadTextureAsync(param.Index0.Value); + m_textureCache.Add(defaultParam, texture); + } + } + + switch (param.TextureType) + { + case GetTextureParam.NORMAL_PROP: + { + if (Application.isPlaying) + { + var converted = new NormalConverter().GetImportTexture(texture); + m_textureCache.Add(param, converted); + return converted; + } + else + { +#if UNITY_EDITOR + var textureAssetPath = AssetDatabase.GetAssetPath(texture); + if (!string.IsNullOrEmpty(textureAssetPath)) + { + TextureIO.MarkTextureAssetAsNormalMap(textureAssetPath); + } + else + { + Debug.LogWarningFormat("no asset for {0}", texture); + } +#endif + m_textureCache.Add(param, texture); + return texture; + } + } + + case GetTextureParam.METALLIC_GLOSS_PROP: + { + // Bake roughnessFactor values into a texture. + var converted = new MetallicRoughnessConverter(param.MetallicFactor).GetImportTexture(texture); + m_textureCache.Add(param, converted); + return converted; + } + + case GetTextureParam.OCCLUSION_PROP: + { + var converted = new OcclusionConverter().GetImportTexture(texture); + m_textureCache.Add(param, converted); + return converted; + } + + default: + return texture; + } + + throw new NotImplementedException(); + } + } +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs.meta new file mode 100644 index 000000000..58a2c5064 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d6069f2bfbfc0c4c9276e8a5f8b0789 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta b/Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta new file mode 100644 index 000000000..84d4a147d --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 54a405d31cce94643be8f76f805da8c8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM/Runtime/IO/VRMImporterContext.cs b/Assets/VRM/Runtime/IO/VRMImporterContext.cs index bd73d1959..c15c9995c 100644 --- a/Assets/VRM/Runtime/IO/VRMImporterContext.cs +++ b/Assets/VRM/Runtime/IO/VRMImporterContext.cs @@ -310,7 +310,7 @@ namespace VRM meta.ContactInformation = gltfMeta.contactInformation; meta.Reference = gltfMeta.reference; meta.Title = gltfMeta.title; - meta.Thumbnail = await MaterialFactory.GetTextureAsync(GetTextureParam.Create(gltfMeta.texture)); + meta.Thumbnail = await TextureFactory.GetTextureAsync(GetTextureParam.Create(gltfMeta.texture)); meta.AllowedUser = gltfMeta.allowedUser; meta.ViolentUssage = gltfMeta.violentUssage; meta.SexualUssage = gltfMeta.sexualUssage; From 912664768f69a866d51fef94a46d595870edcf5f Mon Sep 17 00:00:00 2001 From: ousttrue Date: Mon, 15 Feb 2021 13:49:49 +0900 Subject: [PATCH 14/16] merge MaterialItemBase to MaterialFactory --- .../MaterialFacotry/MaterialFactory.cs | 75 ++++++++++++++++- .../MaterialFacotry/MaterialItemBase.cs | 82 ------------------- .../MaterialFacotry/MaterialItemBase.cs.meta | 11 --- .../MaterialFacotry/PBRMaterialItem.cs | 12 +-- .../MaterialFacotry/UnlitMaterialItem.cs | 4 +- Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs | 24 +++--- Assets/VRM/Runtime/IO/VRMMaterialImporter.cs | 4 +- 7 files changed, 96 insertions(+), 116 deletions(-) delete mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs delete mode 100644 Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs index 17b8b0426..c4e63eeb2 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs @@ -29,7 +29,7 @@ namespace UniGLTF { if (m_createMaterialAsync == null) { - m_createMaterialAsync = MaterialItemBase.DefaultCreateMaterialAsync; + m_createMaterialAsync = MaterialFactory.DefaultCreateMaterialAsync; } return m_createMaterialAsync; } @@ -98,5 +98,78 @@ namespace UniGLTF } yield return null; } + + public static Material CreateMaterial(int index, glTFMaterial src, string shaderName) + { + var material = new Material(Shader.Find(shaderName)); +#if UNITY_EDITOR + // textureImporter.SaveAndReimport(); may destroy this material + material.hideFlags = HideFlags.DontUnloadUnusedAsset; +#endif + material.name = (src == null || string.IsNullOrEmpty(src.name)) + ? string.Format("material_{0:00}", index) + : src.name + ; + + return material; + } + + public static void SetTextureOffsetAndScale(Material material, glTFTextureInfo textureInfo, string propertyName) + { + if (glTF_KHR_texture_transform.TryGet(textureInfo, out glTF_KHR_texture_transform textureTransform)) + { + Vector2 offset = new Vector2(0, 0); + Vector2 scale = new Vector2(1, 1); + if (textureTransform.offset != null && textureTransform.offset.Length == 2) + { + offset = new Vector2(textureTransform.offset[0], textureTransform.offset[1]); + } + if (textureTransform.scale != null && textureTransform.scale.Length == 2) + { + scale = new Vector2(textureTransform.scale[0], textureTransform.scale[1]); + } + + offset.y = (offset.y + scale.y - 1.0f) * -1.0f; + + material.SetTextureOffset(propertyName, offset); + material.SetTextureScale(propertyName, scale); + } + } + + public static Task DefaultCreateMaterialAsync(glTF gltf, int i, GetTextureAsyncFunc getTexture) + { + + if (i < 0 || i >= gltf.materials.Count) + { + UnityEngine.Debug.LogWarning("glTFMaterial is empty"); + return PBRMaterialItem.CreateAsync(i, null, getTexture); + } + var x = gltf.materials[i]; + + if (glTF_KHR_materials_unlit.IsEnable(x)) + { + var hasVertexColor = gltf.MaterialHasVertexColor(i); + return UnlitMaterialItem.CreateAsync(i, x, getTexture, hasVertexColor); + } + + return PBRMaterialItem.CreateAsync(i, x, getTexture); + } + + /// + /// for unittest + /// + /// + /// + /// + /// + public static Material CreateMaterialForTest(int i, glTFMaterial material) + { + var gltf = new glTF + { + materials = new System.Collections.Generic.List { material }, + }; + var task = DefaultCreateMaterialAsync(gltf, i, null); + return task.Result; + } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs deleted file mode 100644 index 9d8538c8e..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.Threading.Tasks; -using UnityEngine; - - -namespace UniGLTF -{ - public static class MaterialItemBase - { - public static Material CreateMaterial(int index, glTFMaterial src, string shaderName) - { - var material = new Material(Shader.Find(shaderName)); -#if UNITY_EDITOR - // textureImporter.SaveAndReimport(); may destroy this material - material.hideFlags = HideFlags.DontUnloadUnusedAsset; -#endif - material.name = (src == null || string.IsNullOrEmpty(src.name)) - ? string.Format("material_{0:00}", index) - : src.name - ; - - return material; - } - - public static void SetTextureOffsetAndScale(Material material, glTFTextureInfo textureInfo, string propertyName) - { - if (glTF_KHR_texture_transform.TryGet(textureInfo, out glTF_KHR_texture_transform textureTransform)) - { - Vector2 offset = new Vector2(0, 0); - Vector2 scale = new Vector2(1, 1); - if (textureTransform.offset != null && textureTransform.offset.Length == 2) - { - offset = new Vector2(textureTransform.offset[0], textureTransform.offset[1]); - } - if (textureTransform.scale != null && textureTransform.scale.Length == 2) - { - scale = new Vector2(textureTransform.scale[0], textureTransform.scale[1]); - } - - offset.y = (offset.y + scale.y - 1.0f) * -1.0f; - - material.SetTextureOffset(propertyName, offset); - material.SetTextureScale(propertyName, scale); - } - } - - public static Task DefaultCreateMaterialAsync(glTF gltf, int i, GetTextureAsyncFunc getTexture) - { - - if (i < 0 || i >= gltf.materials.Count) - { - UnityEngine.Debug.LogWarning("glTFMaterial is empty"); - return PBRMaterialItem.CreateAsync(i, null, getTexture); - } - var x = gltf.materials[i]; - - if (glTF_KHR_materials_unlit.IsEnable(x)) - { - var hasVertexColor = gltf.MaterialHasVertexColor(i); - return UnlitMaterialItem.CreateAsync(i, x, getTexture, hasVertexColor); - } - - return PBRMaterialItem.CreateAsync(i, x, getTexture); - } - - /// - /// for unittest - /// - /// - /// - /// - /// - public static Material CreateMaterialForTest(int i, glTFMaterial material) - { - var gltf = new glTF - { - materials = new System.Collections.Generic.List { material }, - }; - var task = DefaultCreateMaterialAsync(gltf, i, null); - return task.Result; - } - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs.meta deleted file mode 100644 index d6713eb21..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialItemBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f49a88d3a0e6eb24e91af983452f59f6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs index 77ca1faa6..444353f98 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs @@ -49,7 +49,7 @@ namespace UniGLTF getTexture = _ => Task.FromResult(null); } - var material = MaterialItemBase.CreateMaterial(i, src, ShaderName); + var material = MaterialFactory.CreateMaterial(i, src, ShaderName); // PBR material if (src != null) @@ -67,7 +67,7 @@ namespace UniGLTF material.mainTexture = await getTexture(GetTextureParam.Create(src.pbrMetallicRoughness.baseColorTexture.index)); // Texture Offset and Scale - MaterialItemBase.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); + MaterialFactory.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); } if (src.pbrMetallicRoughness.metallicRoughnessTexture != null && src.pbrMetallicRoughness.metallicRoughnessTexture.index != -1) @@ -87,7 +87,7 @@ namespace UniGLTF material.SetFloat("_GlossMapScale", 1.0f); // Texture Offset and Scale - MaterialItemBase.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.metallicRoughnessTexture, "_MetallicGlossMap"); + MaterialFactory.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.metallicRoughnessTexture, "_MetallicGlossMap"); } else { @@ -107,7 +107,7 @@ namespace UniGLTF } // Texture Offset and Scale - MaterialItemBase.SetTextureOffsetAndScale(material, src.normalTexture, "_BumpMap"); + MaterialFactory.SetTextureOffsetAndScale(material, src.normalTexture, "_BumpMap"); } if (src.occlusionTexture != null && src.occlusionTexture.index != -1) @@ -120,7 +120,7 @@ namespace UniGLTF } // Texture Offset and Scale - MaterialItemBase.SetTextureOffsetAndScale(material, src.occlusionTexture, "_OcclusionMap"); + MaterialFactory.SetTextureOffsetAndScale(material, src.occlusionTexture, "_OcclusionMap"); } if (src.emissiveFactor != null @@ -143,7 +143,7 @@ namespace UniGLTF } // Texture Offset and Scale - MaterialItemBase.SetTextureOffsetAndScale(material, src.emissiveTexture, "_EmissionMap"); + MaterialFactory.SetTextureOffsetAndScale(material, src.emissiveTexture, "_EmissionMap"); } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs index 9f5a645fe..f39da4366 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs @@ -14,7 +14,7 @@ namespace UniGLTF getTexture = _ => Task.FromResult(null); } - var material = MaterialItemBase.CreateMaterial(i, src, ShaderName); + var material = MaterialFactory.CreateMaterial(i, src, ShaderName); // texture if (src.pbrMetallicRoughness.baseColorTexture != null) @@ -22,7 +22,7 @@ namespace UniGLTF material.mainTexture = await getTexture(GetTextureParam.Create(src.pbrMetallicRoughness.baseColorTexture.index)); // Texture Offset and Scale - MaterialItemBase.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); + MaterialFactory.SetTextureOffsetAndScale(material, src.pbrMetallicRoughness.baseColorTexture, "_MainTex"); } // color diff --git a/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs b/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs index b4e47e580..d37a0e54c 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/MaterialTests.cs @@ -33,7 +33,7 @@ namespace UniGLTF var gltfMaterial = materialExporter.ExportMaterial(srcMaterial, textureManager); gltfMaterial.pbrMetallicRoughness.baseColorTexture.extensions = gltfMaterial.pbrMetallicRoughness.baseColorTexture.extensions.Deserialize(); - var dstMaterial = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var dstMaterial = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual(dstMaterial.mainTextureOffset.x, offset.x, 0.3f); Assert.AreEqual(dstMaterial.mainTextureOffset.y, offset.y, 0.2f); @@ -81,7 +81,7 @@ namespace UniGLTF Assert.IsTrue(glTF_KHR_materials_unlit.IsEnable(gltfMaterial)); - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } } @@ -100,7 +100,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -115,7 +115,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -131,7 +131,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -146,7 +146,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -161,7 +161,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -177,7 +177,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -192,7 +192,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -208,7 +208,7 @@ namespace UniGLTF }, extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } @@ -218,7 +218,7 @@ namespace UniGLTF { extensions = glTF_KHR_materials_unlit.Serialize().Deserialize(), }; - var material = MaterialItemBase.CreateMaterialForTest(0, gltfMaterial); + var material = MaterialFactory.CreateMaterialForTest(0, gltfMaterial); Assert.AreEqual("UniGLTF/UniUnlit", material.shader.name); } } @@ -226,7 +226,7 @@ namespace UniGLTF [Test] public void MaterialImportTest() { - var material = MaterialItemBase.CreateMaterialForTest(0, new glTFMaterial { }); + var material = MaterialFactory.CreateMaterialForTest(0, new glTFMaterial { }); Assert.AreEqual("Standard", material.shader.name); } diff --git a/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs b/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs index 85b6acf22..145ee7338 100644 --- a/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs +++ b/Assets/VRM/Runtime/IO/VRMMaterialImporter.cs @@ -39,7 +39,7 @@ namespace VRM { Debug.LogWarningFormat("unknown shader {0}.", shaderName); } - return await MaterialItemBase.DefaultCreateMaterialAsync(gltf, m_index, getTexture); + return await MaterialFactory.DefaultCreateMaterialAsync(gltf, m_index, getTexture); } // @@ -116,7 +116,7 @@ namespace VRM if (i == 0 && m_materials.Count == 0) { // dummy - return MaterialItemBase.DefaultCreateMaterialAsync(gltf, i, getTexture); + return MaterialFactory.DefaultCreateMaterialAsync(gltf, i, getTexture); } return MToonMaterialItem.CreateAsync(gltf, i, m_materials[i], getTexture); From 745631be1dfe7cbd6c6023e88bfbef6fabcaff20 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Mon, 15 Feb 2021 13:51:01 +0900 Subject: [PATCH 15/16] mv --- .../{MaterialFacotry.meta => IO/MaterialLoader.meta} | 0 .../MaterialLoader}/MaterialFactory.cs | 0 .../MaterialLoader}/MaterialFactory.cs.meta | 0 .../MaterialLoader}/PBRMaterialItem.cs | 0 .../MaterialLoader}/PBRMaterialItem.cs.meta | 0 .../MaterialLoader}/UnlitMaterialItem.cs | 0 .../MaterialLoader}/UnlitMaterialItem.cs.meta | 0 .../UniGLTF/{MaterialFacotry => IO}/TextureLoader.meta | 0 .../TextureLoader/AssetTextureLoader.cs | 0 .../TextureLoader/AssetTextureLoader.cs.meta | 0 .../TextureLoader/GetTextureParam.cs | 0 .../TextureLoader/GetTextureParam.cs.meta | 0 .../TextureLoader/GltfTextureLoader.cs | 0 .../TextureLoader/GltfTextureLoader.cs.meta | 0 .../TextureLoader/TextureFactory.cs | 0 .../TextureLoader/TextureFactory.cs.meta | 0 .../TextureLoader/UnityWebRequestTextureLoader.cs | 0 .../TextureLoader/UnityWebRequestTextureLoader.cs.meta | 0 Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta | 8 -------- 19 files changed, 8 deletions(-) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry.meta => IO/MaterialLoader.meta} (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO/MaterialLoader}/MaterialFactory.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO/MaterialLoader}/MaterialFactory.cs.meta (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO/MaterialLoader}/PBRMaterialItem.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO/MaterialLoader}/PBRMaterialItem.cs.meta (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO/MaterialLoader}/UnlitMaterialItem.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO/MaterialLoader}/UnlitMaterialItem.cs.meta (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader.meta (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/AssetTextureLoader.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/AssetTextureLoader.cs.meta (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/GetTextureParam.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/GetTextureParam.cs.meta (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/GltfTextureLoader.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/GltfTextureLoader.cs.meta (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/TextureFactory.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/TextureFactory.cs.meta (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/UnityWebRequestTextureLoader.cs (100%) rename Assets/UniGLTF/Runtime/UniGLTF/{MaterialFacotry => IO}/TextureLoader/UnityWebRequestTextureLoader.cs.meta (100%) delete mode 100644 Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/MaterialFactory.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/MaterialFactory.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/PBRMaterialItem.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/PBRMaterialItem.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/UnlitMaterialItem.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/UnlitMaterialItem.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/UnlitMaterialItem.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/UnlitMaterialItem.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialLoader/UnlitMaterialItem.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/AssetTextureLoader.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/AssetTextureLoader.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GetTextureParam.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GetTextureParam.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GetTextureParam.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GetTextureParam.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GetTextureParam.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GltfTextureLoader.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GltfTextureLoader.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GltfTextureLoader.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/GltfTextureLoader.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/GltfTextureLoader.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/TextureFactory.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/TextureFactory.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/UnityWebRequestTextureLoader.cs similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/UnityWebRequestTextureLoader.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/UnityWebRequestTextureLoader.cs.meta similarity index 100% rename from Assets/UniGLTF/Runtime/UniGLTF/MaterialFacotry/TextureLoader/UnityWebRequestTextureLoader.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/TextureLoader/UnityWebRequestTextureLoader.cs.meta diff --git a/Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta b/Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta deleted file mode 100644 index 84d4a147d..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/TextureLoader.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 54a405d31cce94643be8f76f805da8c8 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: From da7d1db04d82f3ecdee3bb57c33bdb8fe1cc0b24 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Mon, 15 Feb 2021 13:54:37 +0900 Subject: [PATCH 16/16] dispose, new --- Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index 53fd5ae6d..25f231224 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -270,6 +270,7 @@ namespace UniGLTF throw new UniGLTFException("unknown gltf version {0}", GLTF.asset.version); } + m_textureFactory = new TextureFactory(GLTF, Storage); m_materialFactory = new MaterialFactory(GLTF, Storage); // Version Compatibility @@ -941,7 +942,6 @@ namespace UniGLTF if (Root != null) GameObject.Destroy(Root); // Remove resources. materials, textures meshes etc... - MaterialFactory.Dispose(); foreach (var x in Meshes) { UnityEngine.Object.DestroyImmediate(x.Mesh, true); @@ -950,6 +950,8 @@ namespace UniGLTF { UnityEngine.Object.DestroyImmediate(x, true); } + MaterialFactory.Dispose(); + TextureFactory.Dispose(); } #if UNITY_EDITOR