diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs index 6f0d0114b..22ab1a442 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/EditorMaterial.cs @@ -34,14 +34,14 @@ namespace UniGLTF static bool s_foldMaterials = true; static bool s_foldTextures = true; - public static void OnGUIMaterial(ScriptedImporter importer, GltfParser parser) + public static void OnGUIMaterial(ScriptedImporter importer, GltfParser parser, EnumerateAllTexturesDistinctFunc enumTextures) { var canExtract = !importer.GetExternalObjectMap().Any(x => x.Value is Material || x.Value is Texture2D); using (new TmpGuiEnable(canExtract)) { if (GUILayout.Button("Extract Materials And Textures ...")) { - ExtractMaterialsAndTextures(importer, parser); + ExtractMaterialsAndTextures(importer, parser, enumTextures); } } @@ -57,7 +57,7 @@ namespace UniGLTF s_foldTextures = EditorGUILayout.Foldout(s_foldTextures, "Remapped Textures"); if (s_foldTextures) { - var names = GltfTextureEnumerator.Enumerate(parser) + var names = enumTextures(parser) .Select(x => { if (x.TextureType != TextureImportTypes.StandardMap && !string.IsNullOrEmpty(x.Uri)) @@ -122,7 +122,7 @@ namespace UniGLTF AssetDatabase.ImportAsset(self.assetPath, ImportAssetOptions.ForceUpdate); } - static void ExtractMaterialsAndTextures(ScriptedImporter self, GltfParser parser) + static void ExtractMaterialsAndTextures(ScriptedImporter self, GltfParser parser, EnumerateAllTexturesDistinctFunc enumTextures) { if (string.IsNullOrEmpty(self.assetPath)) { @@ -143,7 +143,7 @@ namespace UniGLTF var assetPath = UnityPath.FromFullpath(parser.TargetPath); var dirName = $"{assetPath.FileNameWithoutExtension}.Textures"; TextureExtractor.ExtractTextures(parser, assetPath.Parent.Child(dirName), - GltfTextureEnumerator.Enumerate, + enumTextures, self.GetSubAssets(self.assetPath).ToArray(), addRemap, onCompleted diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs index f80403f2e..de7544c95 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GlbScriptedImporterEditorGUI.cs @@ -48,7 +48,7 @@ namespace UniGLTF break; case Tabs.Materials: - EditorMaterial.OnGUIMaterial(m_importer, m_parser); + EditorMaterial.OnGUIMaterial(m_importer, m_parser, GltfTextureEnumerator.EnumerateAllTexturesDistinct); break; } } diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs index 0afc418c8..dc9e56cd5 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/GltfScriptedImporterEditorGUI.cs @@ -48,7 +48,7 @@ namespace UniGLTF break; case Tabs.Materials: - EditorMaterial.OnGUIMaterial(m_importer, m_parser); + EditorMaterial.OnGUIMaterial(m_importer, m_parser, GltfTextureEnumerator.EnumerateAllTexturesDistinct); break; } } diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs index 6857bf7e7..e6018af21 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/ScriptedImporterImpl.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using UnityEditor; @@ -37,32 +36,28 @@ namespace UniGLTF // Import(create unity objects) // var externalObjectMap = scriptedImporter.GetExternalObjectMap().Select(kv => (kv.Value.name, kv.Value)).ToArray(); - + var externalTextures = EnumerateTexturesFromUri(externalObjectMap, parser, UnityPath.FromUnityPath(scriptedImporter.assetPath).Parent).ToArray(); - using (var loaded = new ImporterContext(parser, externalObjectMap.Concat(externalTextures))) + using (var loader = new ImporterContext(parser, externalObjectMap.Concat(externalTextures))) { // settings TextureImporters - foreach (var textureInfo in GltfTextureEnumerator.Enumerate(parser)) + foreach (var textureInfo in GltfTextureEnumerator.EnumerateAllTexturesDistinct(parser)) { - TextureImporterConfigurator.Configure(textureInfo, loaded.TextureFactory.ExternalMap); + TextureImporterConfigurator.Configure(textureInfo, loader.TextureFactory.ExternalMap); } - loaded.InvertAxis = reverseAxis; - loaded.Load(); - loaded.ShowMeshes(); + loader.InvertAxis = reverseAxis; + loader.Load(); + loader.ShowMeshes(); - loaded.TransferOwnership(o => + loader.TransferOwnership(o => { -#if VRM_DEVELOP - Debug.Log($"[{o.GetType().Name}] {o.name} will not destroy"); -#endif - context.AddObjectToAsset(o.name, o); if (o is GameObject) { // Root GameObject is main object - context.SetMainObject(loaded.Root); + context.SetMainObject(loader.Root); } return true; @@ -74,7 +69,7 @@ namespace UniGLTF GltfParser parser, UnityPath dir) { var used = new HashSet(); - foreach (var texParam in GltfTextureEnumerator.Enumerate(parser)) + foreach (var texParam in GltfTextureEnumerator.EnumerateAllTexturesDistinct(parser)) { switch (texParam.TextureType) { @@ -96,8 +91,10 @@ namespace UniGLTF { // exclude. skip } - else{ - if(used.Add(asset)){ + else + { + if (used.Add(asset)) + { yield return (asset.name, asset); } } diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs index ebbf35db8..44ed3f36c 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs @@ -102,7 +102,7 @@ namespace UniGLTF /// /// public static void ExtractTextures(GltfParser parser, UnityPath textureDirectory, - TextureEnumerator textureEnumerator, Texture2D[] subAssets, Action addRemap, + EnumerateAllTexturesDistinctFunc textureEnumerator, Texture2D[] subAssets, Action addRemap, Action> onCompleted = null) { var extractor = new TextureExtractor(parser, textureDirectory, subAssets); diff --git a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs index ceb8e9642..1cc651848 100644 --- a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs +++ b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs @@ -476,5 +476,51 @@ namespace UniGLTF self.RemoveUnusedExtensions(json); return (json, self.buffers); } + + public static bool IsGeneratedUniGLTFAndOlderThan(string generatorVersion, int major, int minor) + { + if (string.IsNullOrEmpty(generatorVersion)) return false; + if (generatorVersion == "UniGLTF") return true; + if (!generatorVersion.FastStartsWith("UniGLTF-")) return false; + + try + { + var splitted = generatorVersion.Substring(8).Split('.'); + var generatorMajor = int.Parse(splitted[0]); + var generatorMinor = int.Parse(splitted[1]); + + if (generatorMajor < major) + { + return true; + } + else if (generatorMajor > major) + { + return false; + } + else + { + if (generatorMinor >= minor) + { + return false; + } + else + { + return true; + } + } + } + catch (Exception ex) + { + Debug.LogWarningFormat("{0}: {1}", generatorVersion, ex); + return false; + } + } + + public static bool IsGeneratedUniGLTFAndOlder(this glTF gltf, int major, int minor) + { + if (gltf == null) return false; + if (gltf.asset == null) return false; + return IsGeneratedUniGLTFAndOlderThan(gltf.asset.generator, major, minor); + } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/ArraySegmentByteBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/ArraySegmentByteBuffer.cs index bdd66ae95..5788b59b3 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/ArraySegmentByteBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/ArraySegmentByteBuffer.cs @@ -1,5 +1,4 @@ using System; -using System.IO; namespace UniGLTF @@ -27,9 +26,11 @@ namespace UniGLTF throw new NotImplementedException(); } - public ArraySegment GetBytes() + public void ExtendCapacity(int capacity) { - return m_bytes; + throw new NotImplementedException(); } + + public ArraySegment Bytes => m_bytes; } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/IBytesBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/IBytesBuffer.cs index 6984bb1ec..6ec19069a 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/IBytesBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/IBytesBuffer.cs @@ -5,7 +5,8 @@ namespace UniGLTF public interface IBytesBuffer { string Uri { get; } - ArraySegment GetBytes(); - glTFBufferView Extend(ArraySegment array, glBufferTarget target) where T : struct; + ArraySegment Bytes { get; } + glTFBufferView Extend(ArraySegment array, glBufferTarget target = glBufferTarget.NONE) where T : struct; + void ExtendCapacity(int capacity); } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs index 6c893b836..ed5dbb166 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs @@ -6,11 +6,12 @@ namespace UniGLTF [Serializable] public class glTFBuffer { - IBytesBuffer Storage; + IBytesBuffer m_buffer; + public IBytesBuffer Buffer => m_buffer; public void OpenStorage(IStorage storage) { - Storage = new ArraySegmentByteBuffer(storage.Get(uri)); + m_buffer = new ArraySegmentByteBuffer(storage.Get(uri)); } public glTFBuffer() @@ -20,7 +21,7 @@ namespace UniGLTF public glTFBuffer(IBytesBuffer storage) { - Storage = storage; + m_buffer = storage; } public string uri; @@ -39,14 +40,14 @@ namespace UniGLTF } public glTFBufferView Append(ArraySegment segment, glBufferTarget target) where T : struct { - var view = Storage.Extend(segment, target); - byteLength = Storage.GetBytes().Count; + var view = m_buffer.Extend(segment, target); + byteLength = m_buffer.Bytes.Count; return view; } public ArraySegment GetBytes() { - return Storage.GetBytes(); + return m_buffer.Bytes; } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ArrayByteBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ArrayByteBuffer.cs new file mode 100644 index 000000000..a08c767fb --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ArrayByteBuffer.cs @@ -0,0 +1,98 @@ +using System; +using System.Runtime.InteropServices; + + +namespace UniGLTF +{ + /// + /// for exporter + /// + public class ArrayByteBuffer : IBytesBuffer + { + public string Uri + { + get; + private set; + } + + Byte[] m_bytes; + int m_used; + + public ArrayByteBuffer(Byte[] bytes = null) + { + Uri = ""; + m_bytes = bytes; + } + + public glTFBufferView Extend(ArraySegment array, glBufferTarget target) where T : struct + { + using (var pin = Pin.Create(array)) + { + var elementSize = Marshal.SizeOf(typeof(T)); + var view = Extend(pin.Ptr, array.Count * elementSize, elementSize, target); + return view; + } + } + + public glTFBufferView Extend(IntPtr p, int bytesLength, int stride, glBufferTarget target) + { + var tmp = m_bytes; + // alignment + var padding = m_used % stride == 0 ? 0 : stride - m_used % stride; + + if (m_bytes == null || m_used + padding + bytesLength > m_bytes.Length) + { + // recreate buffer + m_bytes = new Byte[m_used + padding + bytesLength]; + if (m_used > 0) + { + Buffer.BlockCopy(tmp, 0, m_bytes, 0, m_used); + } + } + if (m_used + padding + bytesLength > m_bytes.Length) + { + throw new ArgumentOutOfRangeException(); + } + + Marshal.Copy(p, m_bytes, m_used + padding, bytesLength); + var result = new glTFBufferView + { + buffer = 0, + byteLength = bytesLength, + byteOffset = m_used + padding, + byteStride = stride, + target = target, + }; + m_used = m_used + padding + bytesLength; + return result; + } + + public void ExtendCapacity(int capacity) + { + if (m_bytes != null && capacity < m_bytes.Length) + { + return; + } + + var newBuffer = new byte[capacity]; + if (m_bytes != null && m_used > 0) + { + Buffer.BlockCopy(m_bytes, 0, newBuffer, 0, m_used); + } + m_bytes = newBuffer; + } + + public ArraySegment Bytes + { + get + { + if (m_bytes == null) + { + return new ArraySegment(); + } + + return new ArraySegment(m_bytes, 0, m_used); + } + } + } +} diff --git a/Assets/VRM/Runtime/IO/VRMTextureEnumerator.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/ArrayByteBuffer.cs.meta similarity index 83% rename from Assets/VRM/Runtime/IO/VRMTextureEnumerator.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/ArrayByteBuffer.cs.meta index 70ddd38c5..6321c430b 100644 --- a/Assets/VRM/Runtime/IO/VRMTextureEnumerator.cs.meta +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ArrayByteBuffer.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: d9b840dcce2a5b94aae00d4bc4bf7e10 +guid: d095d4c4eb5e68f4bb10c21bb3604cdb MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/BytesBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/BytesBuffer.cs deleted file mode 100644 index bd7963734..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/BytesBuffer.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; -using System.IO; -using System.Runtime.InteropServices; - - -namespace UniGLTF -{ - public static class IBytesBufferExtensions - { - public static glTFBufferView Extend(this IBytesBuffer buffer, T[] array, glBufferTarget target) where T : struct - { - return buffer.Extend(new ArraySegment(array), target); - } - } - - /// - /// for buffer with uri read - /// - public class UriByteBuffer : IBytesBuffer - { - public string Uri - { - get; - private set; - } - - Byte[] m_bytes; - public ArraySegment GetBytes() - { - return new ArraySegment(m_bytes); - } - - public UriByteBuffer(string baseDir, string uri) - { - Uri = uri; - m_bytes = ReadFromUri(baseDir, uri); - } - - const string DataPrefix = "data:application/octet-stream;base64,"; - - const string DataPrefix2 = "data:application/gltf-buffer;base64,"; - - const string DataPrefix3 = "data:image/jpeg;base64,"; - - [Obsolete("Use ReadEmbedded(uri)")] - public static Byte[] ReadEmbeded(string uri) - { - return ReadEmbedded(uri); - } - - public static Byte[] ReadEmbedded(string uri) - { - var pos = uri.IndexOf(";base64,"); - if (pos < 0) - { - throw new NotImplementedException(); - } - else - { - return Convert.FromBase64String(uri.Substring(pos + 8)); - } - } - - Byte[] ReadFromUri(string baseDir, string uri) - { - var bytes = ReadEmbedded(uri); - if (bytes != null) - { - return bytes; - } - else - { - // as local file path - return File.ReadAllBytes(Path.Combine(baseDir, uri)); - } - } - - public glTFBufferView Extend(ArraySegment array, glBufferTarget target) where T : struct - { - throw new NotImplementedException(); - } - } - - - /// - /// for exporter - /// - public class ArrayByteBuffer : IBytesBuffer - { - public string Uri - { - get; - private set; - } - - Byte[] m_bytes; - int m_used; - - public ArrayByteBuffer(Byte[] bytes = null) - { - Uri = ""; - m_bytes = bytes; - } - - public glTFBufferView Extend(ArraySegment array, glBufferTarget target) where T : struct - { - using (var pin = Pin.Create(array)) - { - var elementSize = Marshal.SizeOf(typeof(T)); - var view = Extend(pin.Ptr, array.Count * elementSize, elementSize, target); - return view; - } - } - - public glTFBufferView Extend(IntPtr p, int bytesLength, int stride, glBufferTarget target) - { - var tmp = m_bytes; - // alignment - var padding = m_used % stride == 0 ? 0 : stride - m_used % stride; - - if (m_bytes == null || m_used + padding + bytesLength > m_bytes.Length) - { - // recreate buffer - m_bytes = new Byte[m_used + padding + bytesLength]; - if (m_used > 0) - { - Buffer.BlockCopy(tmp, 0, m_bytes, 0, m_used); - } - } - if (m_used + padding + bytesLength > m_bytes.Length) - { - throw new ArgumentOutOfRangeException(); - } - - Marshal.Copy(p, m_bytes, m_used + padding, bytesLength); - var result=new glTFBufferView - { - buffer = 0, - byteLength = bytesLength, - byteOffset = m_used + padding, - byteStride = stride, - target = target, - }; - m_used = m_used + padding + bytesLength; - return result; - } - - public ArraySegment GetBytes() - { - if (m_bytes == null) - { - return new ArraySegment(); - } - - return new ArraySegment(m_bytes, 0, m_used); - } - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfParser.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfParser.cs index d08aad586..cc561be08 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfParser.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfParser.cs @@ -25,51 +25,6 @@ namespace UniGLTF /// public IStorage Storage; - public static bool IsGeneratedUniGLTFAndOlderThan(string generatorVersion, int major, int minor) - { - if (string.IsNullOrEmpty(generatorVersion)) return false; - if (generatorVersion == "UniGLTF") return true; - if (!generatorVersion.FastStartsWith("UniGLTF-")) return false; - - try - { - var splitted = generatorVersion.Substring(8).Split('.'); - var generatorMajor = int.Parse(splitted[0]); - var generatorMinor = int.Parse(splitted[1]); - - if (generatorMajor < major) - { - return true; - } - else if (generatorMajor > major) - { - return false; - } - else - { - if (generatorMinor >= minor) - { - return false; - } - else - { - return true; - } - } - } - catch (Exception ex) - { - Debug.LogWarningFormat("{0}: {1}", generatorVersion, ex); - return false; - } - } - - public bool IsGeneratedUniGLTFAndOlder(int major, int minor) - { - if (GLTF == null) return false; - if (GLTF.asset == null) return false; - return IsGeneratedUniGLTFAndOlderThan(GLTF.asset.generator, major, minor); - } #region Parse public void ParsePath(string path) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/IAnimationImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/IAnimationImporter.cs index 2c65bbd11..1d3057d66 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/IAnimationImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/IAnimationImporter.cs @@ -1,7 +1,10 @@ -namespace UniGLTF +using System.Collections.Generic; +using UnityEngine; + +namespace UniGLTF { public interface IAnimationImporter { - void Import(ImporterContext context); + List Import(glTF gltf, GameObject root, Axises invertAxis); } -} \ No newline at end of file +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index 5f7d6422b..50cff20c5 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Collections.Generic; using UnityEngine; using System.Threading.Tasks; -using System.Text; using VRMShaders; + namespace UniGLTF { /// @@ -41,8 +41,6 @@ namespace UniGLTF TextureFactory m_textureFactory; public TextureFactory TextureFactory => m_textureFactory; - IAwaitCaller m_awaitCaller; - public ImporterContext(GltfParser parser, IEnumerable<(string, UnityEngine.Object)> externalObjectMap = null) { @@ -81,20 +79,12 @@ namespace UniGLTF { awaitCaller = new TaskCaller(); } - m_awaitCaller = awaitCaller; if (MeasureTime == null) { MeasureTime = new ImporterContextSpeedLog().MeasureTime; } - var inverter = InvertAxis.Create(); - - if (Root == null) - { - Root = new GameObject("GLTF"); - } - if (GLTF.extensionsRequired != null) { var sb = new List(); @@ -116,14 +106,28 @@ namespace UniGLTF await LoadMaterialsAsync(); } + await LoadGeometryAsync(awaitCaller, MeasureTime); + + using (MeasureTime("AnimationImporter")) + { + AnimationClips.AddRange(AnimationImporter.Import(GLTF, Root, InvertAxis)); + } + + await OnLoadHierarchy(awaitCaller, MeasureTime); + } + + protected virtual async Task LoadGeometryAsync(IAwaitCaller awaitCaller, Func MeasureTime) + { + var inverter = InvertAxis.Create(); + var meshImporter = new MeshImporter(); for (int i = 0; i < GLTF.meshes.Count; ++i) { var index = i; using (MeasureTime("ReadMesh")) { - var x = meshImporter.ReadMesh(this, index, inverter); - var y = await BuildMeshAsync(MeasureTime, x, index); + var x = meshImporter.ReadMesh(GLTF, index, inverter); + var y = await BuildMeshAsync(awaitCaller, MeasureTime, x, index); Meshes.Add(y); } } @@ -135,14 +139,14 @@ namespace UniGLTF Nodes.Add(NodeImporter.ImportNode(GLTF.nodes[i], i).transform); } } - await m_awaitCaller.NextFrame(); + await awaitCaller.NextFrame(); using (MeasureTime("BuildHierarchy")) { var nodes = new List(); for (int i = 0; i < Nodes.Count; ++i) { - nodes.Add(NodeImporter.BuildHierarchy(this, i)); + nodes.Add(NodeImporter.BuildHierarchy(GLTF, i, Nodes, Meshes)); } NodeImporter.FixCoordinate(this, nodes, inverter); @@ -153,6 +157,10 @@ namespace UniGLTF NodeImporter.SetupSkinning(this, nodes, i, inverter); } + if (Root == null) + { + Root = new GameObject("GLTF"); + } if (GLTF.rootnodes != null) { // connect root @@ -163,14 +171,7 @@ namespace UniGLTF } } } - await m_awaitCaller.NextFrame(); - - using (MeasureTime("AnimationImporter")) - { - AnimationImporter.Import(this); - } - - await OnLoadModel(m_awaitCaller, MeasureTime); + await awaitCaller.NextFrame(); } public async Task LoadMaterialsAsync() @@ -191,17 +192,17 @@ namespace UniGLTF } } - protected virtual Task OnLoadModel(IAwaitCaller awaitCaller, Func MeasureTime) + protected virtual Task OnLoadHierarchy(IAwaitCaller awaitCaller, Func MeasureTime) { // do nothing return Task.FromResult(null); } - async Task BuildMeshAsync(Func MeasureTime, MeshImporter.MeshContext x, int i) + async Task BuildMeshAsync(IAwaitCaller awaitCaller, Func MeasureTime, MeshImporter.MeshContext x, int i) { using (MeasureTime("BuildMesh")) { - var meshWithMaterials = await MeshImporter.BuildMeshAsync(m_awaitCaller, MaterialFactory, x); + var meshWithMaterials = await MeshImporter.BuildMeshAsync(awaitCaller, MaterialFactory, x); var mesh = meshWithMaterials.Mesh; // mesh name diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialIO/GltfTextureEnumerator.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialIO/GltfTextureEnumerator.cs index 3fb2e059c..52511e709 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialIO/GltfTextureEnumerator.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MaterialIO/GltfTextureEnumerator.cs @@ -4,7 +4,7 @@ using VRMShaders; namespace UniGLTF { - public delegate IEnumerable TextureEnumerator(GltfParser parser); + public delegate IEnumerable EnumerateAllTexturesDistinctFunc(GltfParser parser); /// /// Texture 生成に関して @@ -34,8 +34,10 @@ namespace UniGLTF /// public static class GltfTextureEnumerator { - public static IEnumerable EnumerateTextures(GltfParser parser, glTFMaterial m) + public static IEnumerable EnumerateTexturesForMaterial(GltfParser parser, int i) { + var m = parser.GLTF.materials[i]; + int? metallicRoughnessTexture = default; if (m.pbrMetallicRoughness != null) { @@ -79,14 +81,20 @@ namespace UniGLTF } } - public static IEnumerable Enumerate(GltfParser parser) + /// + /// glTF 全体で使うテクスチャーをユニークになるように列挙する + /// + /// + /// + public static IEnumerable EnumerateAllTexturesDistinct(GltfParser parser) { var used = new HashSet(); - foreach (var material in parser.GLTF.materials) + for (int i = 0; i < parser.GLTF.materials.Count; ++i) { - foreach (var textureInfo in EnumerateTextures(parser, material)) + foreach (var textureInfo in EnumerateTexturesForMaterial(parser, i)) { - if(used.Add(textureInfo.ExtractKey)){ + if (used.Add(textureInfo.ExtractKey)) + { yield return textureInfo; } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs index 42c87fddd..cd6d73f85 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshImporter.cs @@ -124,7 +124,7 @@ namespace UniGLTF /// /// /// - public void ImportMeshIndependentVertexBuffer(ImporterContext ctx, glTFMesh gltfMesh, IAxisInverter inverter) + public void ImportMeshIndependentVertexBuffer(glTF gltf, glTFMesh gltfMesh, IAxisInverter inverter) { foreach (var prim in gltfMesh.primitives) { @@ -132,14 +132,14 @@ namespace UniGLTF var indexBuffer = prim.indices; // position は必ずある - var positions = ctx.GLTF.GetArrayFromAccessor(prim.attributes.POSITION); + var positions = gltf.GetArrayFromAccessor(prim.attributes.POSITION); var fillLength = m_positions.Count; m_positions.AddRange(positions.Select(inverter.InvertVector3)); // normal if (prim.attributes.NORMAL != -1) { - var normals = ctx.GLTF.GetArrayFromAccessor(prim.attributes.NORMAL); + var normals = gltf.GetArrayFromAccessor(prim.attributes.NORMAL); if (normals.Length != positions.Length) { throw new Exception("different length"); @@ -151,7 +151,7 @@ namespace UniGLTF #if false if (prim.attributes.TANGENT != -1) { - var tangents = ctx.GLTF.GetArrayFromAccessor(prim.attributes.TANGENT); + var tangents = gltf.GetArrayFromAccessor(prim.attributes.TANGENT); if (tangents.Length != positions.Length) { throw new Exception("different length"); @@ -164,12 +164,12 @@ namespace UniGLTF // uv if (prim.attributes.TEXCOORD_0 != -1) { - var uvs = ctx.GLTF.GetArrayFromAccessor(prim.attributes.TEXCOORD_0); + var uvs = gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_0); if (uvs.Length != positions.Length) { throw new Exception("different length"); } - if (ctx.Parser.IsGeneratedUniGLTFAndOlder(1, 16)) + if (gltf.IsGeneratedUniGLTFAndOlder(1, 16)) { #pragma warning disable 0612 // backward compatibility @@ -187,7 +187,7 @@ namespace UniGLTF // uv2 if (prim.attributes.TEXCOORD_1 != -1) { - var uvs = ctx.GLTF.GetArrayFromAccessor(prim.attributes.TEXCOORD_1); + var uvs = gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_1); if (uvs.Length != positions.Length) { throw new Exception("different length"); @@ -199,7 +199,7 @@ namespace UniGLTF // color if (prim.attributes.COLOR_0 != -1) { - var colors = ctx.GLTF.GetArrayFromAccessor(prim.attributes.COLOR_0); + var colors = gltf.GetArrayFromAccessor(prim.attributes.COLOR_0); if (colors.Length != positions.Length) { throw new Exception("different length"); @@ -211,8 +211,8 @@ namespace UniGLTF // skin if (prim.attributes.JOINTS_0 != -1 && prim.attributes.WEIGHTS_0 != -1) { - var (joints0, jointsLength) = JointsAccessor.GetAccessor(ctx.GLTF, prim.attributes.JOINTS_0); - var (weights0, weightsLength) = WeightsAccessor.GetAccessor(ctx.GLTF, prim.attributes.WEIGHTS_0); + var (joints0, jointsLength) = JointsAccessor.GetAccessor(gltf, prim.attributes.JOINTS_0); + var (weights0, weightsLength) = WeightsAccessor.GetAccessor(gltf, prim.attributes.WEIGHTS_0); if (jointsLength != positions.Length) { throw new Exception("different length"); @@ -256,7 +256,7 @@ namespace UniGLTF var blendShape = new BlendShape(i.ToString()); if (primTarget.POSITION != -1) { - var array = ctx.GLTF.GetArrayFromAccessor(primTarget.POSITION); + var array = gltf.GetArrayFromAccessor(primTarget.POSITION); if (array.Length != positions.Length) { throw new Exception("different length"); @@ -266,7 +266,7 @@ namespace UniGLTF } if (primTarget.NORMAL != -1) { - var array = ctx.GLTF.GetArrayFromAccessor(primTarget.NORMAL); + var array = gltf.GetArrayFromAccessor(primTarget.NORMAL); if (array.Length != positions.Length) { throw new Exception("different length"); @@ -276,7 +276,7 @@ namespace UniGLTF } if (primTarget.TANGENT != -1) { - var array = ctx.GLTF.GetArrayFromAccessor(primTarget.TANGENT); + var array = gltf.GetArrayFromAccessor(primTarget.TANGENT); if (array.Length != positions.Length) { throw new Exception("different length"); @@ -290,7 +290,7 @@ namespace UniGLTF var indices = (indexBuffer >= 0) - ? ctx.GLTF.GetIndices(indexBuffer) + ? gltf.GetIndices(indexBuffer) : TriangleUtil.FlipTriangle(Enumerable.Range(0, m_positions.Count)).ToArray() // without index array ; for (int i = 0; i < indices.Length; ++i) @@ -313,55 +313,55 @@ namespace UniGLTF /// /// /// - public void ImportMeshSharingVertexBuffer(ImporterContext ctx, glTFMesh gltfMesh, IAxisInverter inverter) + public void ImportMeshSharingVertexBuffer(glTF gltf, glTFMesh gltfMesh, IAxisInverter inverter) { { // 同じVertexBufferを共有しているので先頭のモノを使う var prim = gltfMesh.primitives.First(); - m_positions.AddRange(ctx.GLTF.GetArrayFromAccessor(prim.attributes.POSITION).SelectInplace(inverter.InvertVector3)); + m_positions.AddRange(gltf.GetArrayFromAccessor(prim.attributes.POSITION).SelectInplace(inverter.InvertVector3)); // normal if (prim.attributes.NORMAL != -1) { - m_normals.AddRange(ctx.GLTF.GetArrayFromAccessor(prim.attributes.NORMAL).SelectInplace(inverter.InvertVector3)); + m_normals.AddRange(gltf.GetArrayFromAccessor(prim.attributes.NORMAL).SelectInplace(inverter.InvertVector3)); } #if false // tangent if (prim.attributes.TANGENT != -1) { - tangents.AddRange(ctx.GLTF.GetArrayFromAccessor(prim.attributes.TANGENT).SelectInplace(inverter.InvertVector4)); + tangents.AddRange(gltf.GetArrayFromAccessor(prim.attributes.TANGENT).SelectInplace(inverter.InvertVector4)); } #endif // uv if (prim.attributes.TEXCOORD_0 != -1) { - if (ctx.Parser.IsGeneratedUniGLTFAndOlder(1, 16)) + if (gltf.IsGeneratedUniGLTFAndOlder(1, 16)) { #pragma warning disable 0612 // backward compatibility - m_uv.AddRange(ctx.GLTF.GetArrayFromAccessor(prim.attributes.TEXCOORD_0).SelectInplace(x => x.ReverseY())); + m_uv.AddRange(gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_0).SelectInplace(x => x.ReverseY())); #pragma warning restore 0612 } else { - m_uv.AddRange(ctx.GLTF.GetArrayFromAccessor(prim.attributes.TEXCOORD_0).SelectInplace(x => x.ReverseUV())); + m_uv.AddRange(gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_0).SelectInplace(x => x.ReverseUV())); } } // uv2 if (prim.attributes.TEXCOORD_1 != -1) { - m_uv2.AddRange(ctx.GLTF.GetArrayFromAccessor(prim.attributes.TEXCOORD_1).SelectInplace(x => x.ReverseUV())); + m_uv2.AddRange(gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_1).SelectInplace(x => x.ReverseUV())); } // color if (prim.attributes.COLOR_0 != -1) { - if (ctx.GLTF.accessors[prim.attributes.COLOR_0].TypeCount == 3) + if (gltf.accessors[prim.attributes.COLOR_0].TypeCount == 3) { - var vec3Color = ctx.GLTF.GetArrayFromAccessor(prim.attributes.COLOR_0); + var vec3Color = gltf.GetArrayFromAccessor(prim.attributes.COLOR_0); m_colors.AddRange(new Color[vec3Color.Length]); for (int i = 0; i < vec3Color.Length; i++) @@ -370,21 +370,21 @@ namespace UniGLTF m_colors[i] = new Color(color.x, color.y, color.z); } } - else if (ctx.GLTF.accessors[prim.attributes.COLOR_0].TypeCount == 4) + else if (gltf.accessors[prim.attributes.COLOR_0].TypeCount == 4) { - m_colors.AddRange(ctx.GLTF.GetArrayFromAccessor(prim.attributes.COLOR_0)); + m_colors.AddRange(gltf.GetArrayFromAccessor(prim.attributes.COLOR_0)); } else { - throw new NotImplementedException(string.Format("unknown color type {0}", ctx.GLTF.accessors[prim.attributes.COLOR_0].type)); + throw new NotImplementedException(string.Format("unknown color type {0}", gltf.accessors[prim.attributes.COLOR_0].type)); } } // skin if (prim.attributes.JOINTS_0 != -1 && prim.attributes.WEIGHTS_0 != -1) { - var (joints0, jointsLength) = JointsAccessor.GetAccessor(ctx.GLTF, prim.attributes.JOINTS_0); - var (weights0, weightsLength) = WeightsAccessor.GetAccessor(ctx.GLTF, prim.attributes.WEIGHTS_0); + var (joints0, jointsLength) = JointsAccessor.GetAccessor(gltf, prim.attributes.JOINTS_0); + var (weights0, weightsLength) = WeightsAccessor.GetAccessor(gltf, prim.attributes.WEIGHTS_0); for (int j = 0; j < jointsLength; ++j) { @@ -424,17 +424,17 @@ namespace UniGLTF if (primTarget.POSITION != -1) { blendShape.Positions.Assign( - ctx.GLTF.GetArrayFromAccessor(primTarget.POSITION), inverter.InvertVector3); + gltf.GetArrayFromAccessor(primTarget.POSITION), inverter.InvertVector3); } if (primTarget.NORMAL != -1) { blendShape.Normals.Assign( - ctx.GLTF.GetArrayFromAccessor(primTarget.NORMAL), inverter.InvertVector3); + gltf.GetArrayFromAccessor(primTarget.NORMAL), inverter.InvertVector3); } if (primTarget.TANGENT != -1) { blendShape.Tangents.Assign( - ctx.GLTF.GetArrayFromAccessor(primTarget.TANGENT), inverter.InvertVector3); + gltf.GetArrayFromAccessor(primTarget.TANGENT), inverter.InvertVector3); } } } @@ -448,7 +448,7 @@ namespace UniGLTF } else { - var indices = ctx.GLTF.GetIndices(prim.indices); + var indices = gltf.GetIndices(prim.indices); m_subMeshes.Add(indices); } @@ -530,18 +530,18 @@ namespace UniGLTF return sharedAttributes; } - public MeshContext ReadMesh(ImporterContext ctx, int meshIndex, IAxisInverter inverter) + public MeshContext ReadMesh(glTF gltf, int meshIndex, IAxisInverter inverter) { - var gltfMesh = ctx.GLTF.meshes[meshIndex]; + var gltfMesh = gltf.meshes[meshIndex]; var meshContext = new MeshContext(gltfMesh.name, meshIndex); if (HasSharedVertexBuffer(gltfMesh)) { - meshContext.ImportMeshSharingVertexBuffer(ctx, gltfMesh, inverter); + meshContext.ImportMeshSharingVertexBuffer(gltf, gltfMesh, inverter); } else { - meshContext.ImportMeshIndependentVertexBuffer(ctx, gltfMesh, inverter); + meshContext.ImportMeshIndependentVertexBuffer(gltf, gltfMesh, inverter); } meshContext.RenameBlendShape(gltfMesh); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/NodeImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/NodeImporter.cs index 940653521..8461da81c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/NodeImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/NodeImporter.cs @@ -64,9 +64,9 @@ namespace UniGLTF public int? SkinIndex; } - public static TransformWithSkin BuildHierarchy(ImporterContext context, int i) + public static TransformWithSkin BuildHierarchy(glTF gltf, int i, List nodes, List meshes) { - var go = context.Nodes[i].gameObject; + var go = nodes[i].gameObject; if (string.IsNullOrEmpty(go.name)) { go.name = string.Format("node{0:000}", i); @@ -80,12 +80,12 @@ namespace UniGLTF // // build hierarchy // - var node = context.GLTF.nodes[i]; + var node = gltf.nodes[i]; if (node.children != null) { foreach (var child in node.children) { - context.Nodes[child].transform.SetParent(context.Nodes[i].transform, + nodes[child].transform.SetParent(nodes[i].transform, false // node has local transform ); } @@ -96,7 +96,7 @@ namespace UniGLTF // if (node.mesh != -1) { - var mesh = context.Meshes[node.mesh]; + var mesh = meshes[node.mesh]; if (mesh.Mesh.blendShapeCount == 0 && node.skin == -1) { // without blendshape and bone skinning diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/RootAnimationImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/RootAnimationImporter.cs index d48f7ee81..7c062da4b 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/RootAnimationImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/RootAnimationImporter.cs @@ -6,28 +6,28 @@ namespace UniGLTF { public sealed class RootAnimationImporter : IAnimationImporter { - public void Import(ImporterContext context) + public List Import(glTF gltf, GameObject root, Axises invertAxis) { - // animation - if (context.GLTF.animations != null && context.GLTF.animations.Any()) + var animationClips = new List(); + if (gltf.animations != null && gltf.animations.Any()) { - var animation = context.Root.AddComponent(); - context.AnimationClips = ImportAnimationClips(context.GLTF, context.InvertAxis); + var animation = root.AddComponent(); + animationClips.AddRange(ImportAnimationClips(gltf, invertAxis)); - foreach (var clip in context.AnimationClips) + foreach (var clip in animationClips) { animation.AddClip(clip, clip.name); } - if (context.AnimationClips.Count > 0) + if (animationClips.Count > 0) { - animation.clip = context.AnimationClips.First(); + animation.clip = animationClips.First(); } } + return animationClips; } - private List ImportAnimationClips(glTF gltf, Axises invertAxis) + private IEnumerable ImportAnimationClips(glTF gltf, Axises invertAxis) { - var animationClips = new List(); for (var i = 0; i < gltf.animations.Count; ++i) { var clip = new AnimationClip(); @@ -46,10 +46,8 @@ namespace UniGLTF animation.name = $"animation:{i}"; } - animationClips.Add(AnimationImporterUtil.ConvertAnimationClip(gltf, animation, invertAxis.Create())); + yield return AnimationImporterUtil.ConvertAnimationClip(gltf, animation, invertAxis.Create()); } - - return animationClips; } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureImporter.cs index c23c4cd93..cc70367ba 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureImporter.cs @@ -13,7 +13,7 @@ namespace UniGLTF /// public static class GltfTextureImporter { - static Byte[] ToArray(ArraySegment bytes) + public static Byte[] ToArray(ArraySegment bytes) { if (bytes.Array == null) { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/UriByteBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/UriByteBuffer.cs new file mode 100644 index 000000000..2ca07a1ab --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/UriByteBuffer.cs @@ -0,0 +1,75 @@ +using System; +using System.IO; + +namespace UniGLTF +{ + /// + /// for buffer with uri read + /// + public class UriByteBuffer : IBytesBuffer + { + public string Uri + { + get; + private set; + } + + Byte[] m_bytes; + public ArraySegment Bytes => new ArraySegment(m_bytes); + + public UriByteBuffer(string baseDir, string uri) + { + Uri = uri; + m_bytes = ReadFromUri(baseDir, uri); + } + + const string DataPrefix = "data:application/octet-stream;base64,"; + + const string DataPrefix2 = "data:application/gltf-buffer;base64,"; + + const string DataPrefix3 = "data:image/jpeg;base64,"; + + [Obsolete("Use ReadEmbedded(uri)")] + public static Byte[] ReadEmbeded(string uri) + { + return ReadEmbedded(uri); + } + + public static Byte[] ReadEmbedded(string uri) + { + var pos = uri.IndexOf(";base64,"); + if (pos < 0) + { + throw new NotImplementedException(); + } + else + { + return Convert.FromBase64String(uri.Substring(pos + 8)); + } + } + + Byte[] ReadFromUri(string baseDir, string uri) + { + var bytes = ReadEmbedded(uri); + if (bytes != null) + { + return bytes; + } + else + { + // as local file path + return File.ReadAllBytes(Path.Combine(baseDir, uri)); + } + } + + public glTFBufferView Extend(ArraySegment array, glBufferTarget target) where T : struct + { + throw new NotImplementedException(); + } + + public void ExtendCapacity(int capacity) + { + throw new NotImplementedException(); + } + } +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/BytesBuffer.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/UriByteBuffer.cs.meta similarity index 83% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/BytesBuffer.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/UriByteBuffer.cs.meta index cdca54f8f..3cd3bff9b 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/BytesBuffer.cs.meta +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/UriByteBuffer.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1e9c9201942704b4f9dd050115073032 +guid: 8b75aca0e4a7415418cd1c3d018483b2 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/UniGLTF/Runtime/UniJSON/ListTreeNode/ListTreeNodeObjectExtensions.cs b/Assets/UniGLTF/Runtime/UniJSON/ListTreeNode/ListTreeNodeObjectExtensions.cs index 6a3d3e34b..5f884988c 100644 --- a/Assets/UniGLTF/Runtime/UniJSON/ListTreeNode/ListTreeNodeObjectExtensions.cs +++ b/Assets/UniGLTF/Runtime/UniJSON/ListTreeNode/ListTreeNodeObjectExtensions.cs @@ -66,6 +66,27 @@ namespace UniJSON return self.ContainsKey(ukey); } + public static bool TryGet(this JsonNode self, Utf8String key, out JsonNode found) + { + foreach (var kv in self.ObjectItems()) + { + if (kv.Key.GetUtf8String() == key) + { + found = kv.Value; + return true; + } + } + + found = default; + return false; + } + + public static bool TryGet(this JsonNode self, String key, out JsonNode found) + { + var ukey = Utf8String.From(key); + return self.TryGet(ukey, out found); + } + public static Utf8String KeyOf(this JsonNode self, JsonNode node) { foreach (var kv in self.ObjectItems()) diff --git a/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs b/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs index e0f42e241..7ee3382d7 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs @@ -99,7 +99,7 @@ namespace UniGLTF } // should unique - var gltfTextures = GltfTextureEnumerator.Enumerate(parser).ToArray(); + var gltfTextures = GltfTextureEnumerator.EnumerateAllTexturesDistinct(parser).ToArray(); var distinct = gltfTextures.Distinct().ToArray(); Assert.True(gltfTextures.SequenceEqual(distinct)); } diff --git a/Assets/UniGLTF/Tests/UniGLTF/TextureEnumerateTests.cs b/Assets/UniGLTF/Tests/UniGLTF/TextureEnumerateTests.cs index 403638bb5..938a78118 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/TextureEnumerateTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/TextureEnumerateTests.cs @@ -207,7 +207,7 @@ namespace UniGLTF { GLTF = TwoTexture(), }; - var items = GltfTextureEnumerator.Enumerate(parser).ToArray(); + var items = GltfTextureEnumerator.EnumerateAllTexturesDistinct(parser).ToArray(); Assert.AreEqual(2, items.Length); } @@ -216,7 +216,7 @@ namespace UniGLTF { GLTF = TwoTextureOneUri(), }; - var items = GltfTextureEnumerator.Enumerate(parser).ToArray(); + var items = GltfTextureEnumerator.EnumerateAllTexturesDistinct(parser).ToArray(); Assert.AreEqual(1, items.Length); } @@ -225,7 +225,7 @@ namespace UniGLTF { GLTF = TwoTextureOneImage(), }; - var items = GltfTextureEnumerator.Enumerate(parser).ToArray(); + var items = GltfTextureEnumerator.EnumerateAllTexturesDistinct(parser).ToArray(); Assert.AreEqual(1, items.Length); } @@ -234,7 +234,7 @@ namespace UniGLTF { GLTF = CombineMetallicSmoothOcclusion(), }; - var items = GltfTextureEnumerator.Enumerate(parser).ToArray(); + var items = GltfTextureEnumerator.EnumerateAllTexturesDistinct(parser).ToArray(); Assert.AreEqual(1, items.Length); } } diff --git a/Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs b/Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs index b2750e424..9cf2512a1 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs @@ -185,12 +185,12 @@ namespace UniGLTF [Test] public void VersionChecker() { - Assert.False(GltfParser.IsGeneratedUniGLTFAndOlderThan("hoge", 1, 16)); - Assert.False(GltfParser.IsGeneratedUniGLTFAndOlderThan("UniGLTF-1.16", 1, 16)); - Assert.True(GltfParser.IsGeneratedUniGLTFAndOlderThan("UniGLTF-1.15", 1, 16)); - Assert.False(GltfParser.IsGeneratedUniGLTFAndOlderThan("UniGLTF-11.16", 1, 16)); - Assert.True(GltfParser.IsGeneratedUniGLTFAndOlderThan("UniGLTF-0.16", 1, 16)); - Assert.True(GltfParser.IsGeneratedUniGLTFAndOlderThan("UniGLTF", 1, 16)); + Assert.False(glTFExtensions.IsGeneratedUniGLTFAndOlderThan("hoge", 1, 16)); + Assert.False(glTFExtensions.IsGeneratedUniGLTFAndOlderThan("UniGLTF-1.16", 1, 16)); + Assert.True(glTFExtensions.IsGeneratedUniGLTFAndOlderThan("UniGLTF-1.15", 1, 16)); + Assert.False(glTFExtensions.IsGeneratedUniGLTFAndOlderThan("UniGLTF-11.16", 1, 16)); + Assert.True(glTFExtensions.IsGeneratedUniGLTFAndOlderThan("UniGLTF-0.16", 1, 16)); + Assert.True(glTFExtensions.IsGeneratedUniGLTFAndOlderThan("UniGLTF", 1, 16)); } [Test] diff --git a/Assets/VRM/Editor/Format/VRMEditorImporterContext.cs b/Assets/VRM/Editor/Format/VRMEditorImporterContext.cs index 4ef829449..66d316a1b 100644 --- a/Assets/VRM/Editor/Format/VRMEditorImporterContext.cs +++ b/Assets/VRM/Editor/Format/VRMEditorImporterContext.cs @@ -149,9 +149,9 @@ namespace VRM .Where(x => x.IsUsed) .Select(x => x.Texture) .ToArray(); - var vrmTextures = new VRMTextureEnumerator(m_context.VRM); + var vrmTextures = new VRMMtoonMaterialImporter(m_context.VRM); var dirName = $"{m_prefabPath.FileNameWithoutExtension}.Textures"; - TextureExtractor.ExtractTextures(m_context.Parser, m_prefabPath.Parent.Child(dirName), vrmTextures.Enumerate, subAssets, _ => { }, onTextureReloaded); + TextureExtractor.ExtractTextures(m_context.Parser, m_prefabPath.Parent.Child(dirName), vrmTextures.EnumerateAllTexturesDistinct, subAssets, _ => { }, onTextureReloaded); } bool SaveAsAsset(UnityEngine.Object o) diff --git a/Assets/VRM/Editor/Format/VRMImporterMenu.cs b/Assets/VRM/Editor/Format/VRMImporterMenu.cs index 97d26f9f6..d45358480 100644 --- a/Assets/VRM/Editor/Format/VRMImporterMenu.cs +++ b/Assets/VRM/Editor/Format/VRMImporterMenu.cs @@ -83,7 +83,7 @@ namespace VRM using (var context = new VRMImporterContext(parser, map)) { var editor = new VRMEditorImporterContext(context, prefabPath); - foreach (var textureInfo in new VRMTextureEnumerator(context.VRM).Enumerate(parser)) + foreach (var textureInfo in new VRMMtoonMaterialImporter(context.VRM).EnumerateAllTexturesDistinct(parser)) { TextureImporterConfigurator.Configure(textureInfo, map.ToDictionary(x => x.name, x => x.texture as Texture2D)); } diff --git a/Assets/VRM/Editor/Format/vrmAssetPostprocessor.cs b/Assets/VRM/Editor/Format/vrmAssetPostprocessor.cs index 218057dd6..cbc19a7ce 100644 --- a/Assets/VRM/Editor/Format/vrmAssetPostprocessor.cs +++ b/Assets/VRM/Editor/Format/vrmAssetPostprocessor.cs @@ -60,7 +60,7 @@ namespace VRM using (var context = new VRMImporterContext(parser, map)) { var editor = new VRMEditorImporterContext(context, prefabPath); - foreach (var textureInfo in new VRMTextureEnumerator(context.VRM).Enumerate(parser)) + foreach (var textureInfo in new VRMMtoonMaterialImporter(context.VRM).EnumerateAllTexturesDistinct(parser)) { TextureImporterConfigurator.Configure(textureInfo, map.ToDictionary(x => x.name, x => x.texture as Texture2D)); } diff --git a/Assets/VRM/Runtime/IO/VRMImporterContext.cs b/Assets/VRM/Runtime/IO/VRMImporterContext.cs index ef9d9c841..8953d8da2 100644 --- a/Assets/VRM/Runtime/IO/VRMImporterContext.cs +++ b/Assets/VRM/Runtime/IO/VRMImporterContext.cs @@ -26,7 +26,7 @@ namespace VRM { VRM = vrm; // override material importer - GltfMaterialImporter.GltfMaterialParamProcessors.Insert(0, new MToonMaterialImporter(VRM.materialProperties).TryCreateParam); + GltfMaterialImporter.GltfMaterialParamProcessors.Insert(0, new VRMMtoonMaterialImporter(VRM).TryCreateParam); } else { @@ -35,7 +35,7 @@ namespace VRM } #region OnLoad - protected override async Task OnLoadModel(IAwaitCaller awaitCaller, Func MeasureTime) + protected override async Task OnLoadHierarchy(IAwaitCaller awaitCaller, Func MeasureTime) { Root.name = "VRM"; diff --git a/Assets/VRM/Runtime/IO/MToonMaterialImporter.cs b/Assets/VRM/Runtime/IO/VRMMtoonMaterialImporter.cs similarity index 57% rename from Assets/VRM/Runtime/IO/MToonMaterialImporter.cs rename to Assets/VRM/Runtime/IO/VRMMtoonMaterialImporter.cs index ae6bfaa5b..c2ca44185 100644 --- a/Assets/VRM/Runtime/IO/MToonMaterialImporter.cs +++ b/Assets/VRM/Runtime/IO/VRMMtoonMaterialImporter.cs @@ -3,13 +3,19 @@ using UniGLTF; using UnityEngine; using VRMShaders; - namespace VRM { - public class MToonMaterialImporter + public class VRMMtoonMaterialImporter { - public static bool TryCreateParam(GltfParser parser, int i, glTF_VRM_Material vrmMaterial, out MaterialImportParam param) + readonly glTF_VRM_extensions m_vrm; + public VRMMtoonMaterialImporter(glTF_VRM_extensions vrm) { + m_vrm = vrm; + } + + public bool TryCreateParam(GltfParser parser, int i, out MaterialImportParam param) + { + var vrmMaterial = m_vrm.materialProperties[i]; if (vrmMaterial.shader == VRM.glTF_VRM_Material.VRM_USE_GLTFSHADER) { // fallback to gltf @@ -87,21 +93,64 @@ namespace VRM return true; } - List m_materials; - public MToonMaterialImporter(List materials) + public IEnumerable EnumerateTexturesForMaterial(GltfParser parser, int i) { - m_materials = materials; - } - - public bool TryCreateParam(GltfParser parser, int i, out MaterialImportParam param) - { - if (TryCreateParam(parser, i, m_materials[i], out param)) + // mtoon + if (!TryCreateParam(parser, i, out MaterialImportParam param)) { - return true; + // unlit + if (!GltfUnlitMaterial.TryCreateParam(parser, i, out param)) + { + // pbr + GltfPBRMaterial.TryCreateParam(parser, i, out param); + } } - param = default; - return false; + foreach (var kv in param.TextureSlots) + { + yield return kv.Value; + } + } + + public IEnumerable EnumerateAllTexturesDistinct(GltfParser parser) + { + var used = new HashSet(); + for (int i = 0; i < parser.GLTF.materials.Count; ++i) + { + var vrmMaterial = m_vrm.materialProperties[i]; + if (vrmMaterial.shader == MToon.Utils.ShaderName) + { + // MToon + foreach (var textureInfo in EnumerateTexturesForMaterial(parser, i)) + { + if (used.Add(textureInfo.ExtractKey)) + { + yield return textureInfo; + } + } + } + else + { + // PBR or Unlit + foreach (var textureInfo in GltfTextureEnumerator.EnumerateTexturesForMaterial(parser, i)) + { + if (used.Add(textureInfo.ExtractKey)) + { + yield return textureInfo; + } + } + } + } + + // thumbnail + if (m_vrm.meta != null && m_vrm.meta.texture != -1) + { + var textureInfo = GltfTextureImporter.CreateSRGB(parser, m_vrm.meta.texture, Vector2.zero, Vector2.one); + if (used.Add(textureInfo.ExtractKey)) + { + yield return textureInfo; + } + } } } } diff --git a/Assets/VRM10/Editor/ScriptedImporter/IExternalUnityObject.cs.meta b/Assets/VRM/Runtime/IO/VRMMtoonMaterialImporter.cs.meta similarity index 83% rename from Assets/VRM10/Editor/ScriptedImporter/IExternalUnityObject.cs.meta rename to Assets/VRM/Runtime/IO/VRMMtoonMaterialImporter.cs.meta index fe35916e7..ea615db5e 100644 --- a/Assets/VRM10/Editor/ScriptedImporter/IExternalUnityObject.cs.meta +++ b/Assets/VRM/Runtime/IO/VRMMtoonMaterialImporter.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8e6d15fc36df79649bb4724b06b5eae3 +guid: bad75b40d017eb74ba79f561d22dc372 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/VRM/Runtime/IO/VRMTextureEnumerator.cs b/Assets/VRM/Runtime/IO/VRMTextureEnumerator.cs deleted file mode 100644 index 20ed7f39d..000000000 --- a/Assets/VRM/Runtime/IO/VRMTextureEnumerator.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Collections.Generic; -using UniGLTF; -using UnityEngine; -using VRMShaders; - -namespace VRM -{ - public class VRMTextureEnumerator - { - readonly glTF_VRM_extensions m_vrm; - public VRMTextureEnumerator(glTF_VRM_extensions vrm) - { - m_vrm = vrm; - } - - public IEnumerable EnumerateMaterial(GltfParser parser, glTF_VRM_Material vrmMaterial) - { - // MToon - var offsetScaleMap = new Dictionary(); - foreach (var kv in vrmMaterial.vectorProperties) - { - if (vrmMaterial.textureProperties.ContainsKey(kv.Key)) - { - // texture offset & scale - offsetScaleMap.Add(kv.Key, kv.Value); - } - } - foreach (var kv in vrmMaterial.textureProperties) - { - var (offset, scale) = (Vector2.zero, Vector2.one); - if (offsetScaleMap.TryGetValue(kv.Key, out float[] value)) - { - offset = new Vector2(value[0], value[1]); - scale = new Vector2(value[2], value[3]); - } - - // SRGB color or normalmap - yield return MToonTextureParam.Create(parser, kv.Value, offset, scale, kv.Key, default, default); - } - } - - public IEnumerable Enumerate(GltfParser parser) - { - var used = new HashSet(); - for (int i = 0; i < parser.GLTF.materials.Count; ++i) - { - var vrmMaterial = m_vrm.materialProperties[i]; - if (vrmMaterial.shader == MToon.Utils.ShaderName) - { - // MToon - foreach(var textureInfo in EnumerateMaterial(parser, vrmMaterial)) - { - if (used.Add(textureInfo.ExtractKey)) - { - yield return textureInfo; - } - } - } - else - { - // PBR or Unlit - foreach (var textureInfo in GltfTextureEnumerator.EnumerateTextures(parser, parser.GLTF.materials[i])) - { - if (used.Add(textureInfo.ExtractKey)) - { - yield return textureInfo; - } - } - } - } - - // thumbnail - if (m_vrm.meta != null && m_vrm.meta.texture != -1) - { - var textureInfo = GltfTextureImporter.CreateSRGB(parser, m_vrm.meta.texture, Vector2.zero, Vector2.one); - if (used.Add(textureInfo.ExtractKey)) - { - yield return textureInfo; - } - } - } - } -} diff --git a/Assets/VRM/Tests/MToonTest.cs b/Assets/VRM/Tests/MToonTest.cs index 551b29e5b..b8326d7e0 100644 --- a/Assets/VRM/Tests/MToonTest.cs +++ b/Assets/VRM/Tests/MToonTest.cs @@ -24,12 +24,15 @@ namespace VRM srcMaterial.mainTexture = tex0; srcMaterial.mainTextureOffset = offset; srcMaterial.mainTextureScale = scale; - + var materialExporter = new VRMMaterialExporter(); var vrmMaterial = VRMMaterialExporter.CreateFromMaterial(srcMaterial, textureManager); - Assert.AreEqual(vrmMaterial.vectorProperties["_MainTex"], new float[]{0.3f, 0.2f, 0.5f, 0.6f}); - - var materialImporter = new MToonMaterialImporter(new System.Collections.Generic.List{ vrmMaterial }); + Assert.AreEqual(vrmMaterial.vectorProperties["_MainTex"], new float[] { 0.3f, 0.2f, 0.5f, 0.6f }); + + var materialImporter = new VRMMtoonMaterialImporter(new glTF_VRM_extensions + { + materialProperties = new System.Collections.Generic.List { vrmMaterial } + }); } } } diff --git a/Assets/VRM/Tests/VRMTextureEnumerateTests.cs b/Assets/VRM/Tests/VRMTextureEnumerateTests.cs index 5964a528c..478466fba 100644 --- a/Assets/VRM/Tests/VRMTextureEnumerateTests.cs +++ b/Assets/VRM/Tests/VRMTextureEnumerateTests.cs @@ -71,7 +71,7 @@ namespace VRM }, } }; - var items = new VRMTextureEnumerator(vrm).Enumerate(parser).ToArray(); + var items = new VRMMtoonMaterialImporter(vrm).EnumerateAllTexturesDistinct(parser).ToArray(); Assert.AreEqual(1, items.Length); } } diff --git a/Assets/VRM10.Samples/Runtime/AIUEO.cs b/Assets/VRM10.Samples/Runtime/AIUEO.cs index 58fe8e65b..f59bd3dcf 100644 --- a/Assets/VRM10.Samples/Runtime/AIUEO.cs +++ b/Assets/VRM10.Samples/Runtime/AIUEO.cs @@ -26,7 +26,7 @@ namespace UniVRM10.Samples } } - IEnumerator RoutineNest(VrmLib.ExpressionPreset preset, float velocity, float wait) + IEnumerator RoutineNest(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset preset, float velocity, float wait) { for (var value = 0.0f; value <= 1.0f; value += velocity) { @@ -52,11 +52,11 @@ namespace UniVRM10.Samples var velocity = 0.1f; - yield return RoutineNest(VrmLib.ExpressionPreset.Aa, velocity, m_wait); - yield return RoutineNest(VrmLib.ExpressionPreset.Ih, velocity, m_wait); - yield return RoutineNest(VrmLib.ExpressionPreset.Ou, velocity, m_wait); - yield return RoutineNest(VrmLib.ExpressionPreset.Ee, velocity, m_wait); - yield return RoutineNest(VrmLib.ExpressionPreset.Oh, velocity, m_wait); + yield return RoutineNest(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.aa, velocity, m_wait); + yield return RoutineNest(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ih, velocity, m_wait); + yield return RoutineNest(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ou, velocity, m_wait); + yield return RoutineNest(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ee, velocity, m_wait); + yield return RoutineNest(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.oh, velocity, m_wait); } } diff --git a/Assets/VRM10.Samples/Runtime/Blinker.cs b/Assets/VRM10.Samples/Runtime/Blinker.cs index 815312342..e6517000c 100644 --- a/Assets/VRM10.Samples/Runtime/Blinker.cs +++ b/Assets/VRM10.Samples/Runtime/Blinker.cs @@ -72,10 +72,10 @@ namespace UniVRM10.Samples break; } - m_controller.Expression.SetWeight(ExpressionKey.CreateFromPreset(VrmLib.ExpressionPreset.Blink), value); + m_controller.Expression.SetWeight(ExpressionKey.CreateFromPreset(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blink), value); yield return null; } - m_controller.Expression.SetWeight(ExpressionKey.CreateFromPreset(VrmLib.ExpressionPreset.Blink), 1.0f); + m_controller.Expression.SetWeight(ExpressionKey.CreateFromPreset(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blink), 1.0f); // wait... yield return new WaitForSeconds(ClosingTime); @@ -91,10 +91,10 @@ namespace UniVRM10.Samples break; } - m_controller.Expression.SetWeight(ExpressionKey.CreateFromPreset(VrmLib.ExpressionPreset.Blink), value); + m_controller.Expression.SetWeight(ExpressionKey.CreateFromPreset(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blink), value); yield return null; } - m_controller.Expression.SetWeight(ExpressionKey.CreateFromPreset(VrmLib.ExpressionPreset.Blink), 0); + m_controller.Expression.SetWeight(ExpressionKey.CreateFromPreset(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blink), 0); } } diff --git a/Assets/VRM10.Samples/Runtime/ViewerUI.cs b/Assets/VRM10.Samples/Runtime/ViewerUI.cs index 3d87e4089..0055a3334 100644 --- a/Assets/VRM10.Samples/Runtime/ViewerUI.cs +++ b/Assets/VRM10.Samples/Runtime/ViewerUI.cs @@ -84,16 +84,18 @@ namespace UniVRM10.Samples m_textDistributionOther.text = ""; } - public void UpdateMeta(VRM10Controller context) + public void UpdateMeta(VRM10MetaObject meta) { - // var meta = context.ReadMeta(true); - var meta = context.Meta; + if (meta == null) + { + return; + } m_textModelTitle.text = meta.Name; m_textModelVersion.text = meta.Version; m_textModelAuthor.text = meta.Authors[0]; m_textModelContact.text = meta.ContactInformation; - m_textModelReference.text = meta.Reference; + m_textModelReference.text = meta.References[0]; m_textPermissionAllowed.text = meta.AllowedUser.ToString(); m_textPermissionViolent.text = meta.ViolentUsage.ToString(); @@ -306,28 +308,17 @@ namespace UniVRM10.Samples { case ".vrm": { - // var context = new ImporterContext(); - var file = File.ReadAllBytes(path); - // context.ParseGlb(file); - // context.Load(); - // context.ShowMeshes(); - // context.EnableUpdateWhenOffscreen(); - // context.ShowMeshes(); + var parser = new UniGLTF.GltfParser(); + parser.ParsePath(path); - var model = UniVRM10.VrmLoader.CreateVrmModel(file, new FileInfo(path)); - - // UniVRM-0.XXのコンポーネントを構築する - var assets = UniVRM10.RuntimeUnityBuilder.ToUnityAsset(model, showMesh: false); - - // showRenderer = false のときに後で表示する例 - foreach (var renderer in assets.Renderers) + using (var loader = new RuntimeUnityBuilder(parser)) { - renderer.enabled = true; + loader.Load(); + loader.ShowMeshes(); + loader.EnableUpdateWhenOffscreen(); + var destroyer = loader.DisposeOnGameObjectDestroyed(); + SetModel(destroyer.gameObject); } - - UniVRM10.ComponentBuilder.Build10(model, assets); - - SetModel(assets.Root); break; } @@ -337,12 +328,15 @@ namespace UniVRM10.Samples var parser = new GltfParser(); parser.ParseGlb(file); - var context = new UniGLTF.ImporterContext(parser); - context.Load(); - context.ShowMeshes(); - context.EnableUpdateWhenOffscreen(); - context.ShowMeshes(); - SetModel(context.Root); + using (var loader = new UniGLTF.ImporterContext(parser)) + { + loader.Load(); + loader.ShowMeshes(); + loader.EnableUpdateWhenOffscreen(); + loader.ShowMeshes(); + var destroyer = loader.DisposeOnGameObjectDestroyed(); + SetModel(destroyer.gameObject); + } break; } @@ -352,12 +346,15 @@ namespace UniVRM10.Samples var parser = new GltfParser(); parser.ParsePath(path); - var context = new UniGLTF.ImporterContext(parser); - context.Load(); - context.ShowMeshes(); - context.EnableUpdateWhenOffscreen(); - context.ShowMeshes(); - SetModel(context.Root); + using (var loader = new UniGLTF.ImporterContext(parser)) + { + loader.Load(); + loader.ShowMeshes(); + loader.EnableUpdateWhenOffscreen(); + loader.ShowMeshes(); + var destroyer = loader.DisposeOnGameObjectDestroyed(); + SetModel(destroyer.gameObject); + } break; } @@ -382,19 +379,22 @@ namespace UniVRM10.Samples if (go != null) { m_controller = go.GetComponent(); - - m_texts.UpdateMeta(m_controller); - - m_controller.Controller.UpdateType = VRM10Controller.VRM10ControllerImpl.UpdateTypes.LateUpdate; // after HumanPoseTransfer's setPose + if (m_controller != null) { - m_loaded = go.AddComponent(); - m_loaded.Source = m_src; - m_loaded.SourceType = HumanPoseTransfer.HumanPoseTransferSourceType.HumanPoseTransfer; - m_lipSync = go.AddComponent(); - m_blink = go.AddComponent(); + m_texts.UpdateMeta(m_controller.Meta); - m_controller.LookAt.Gaze = m_target.transform; + m_controller.Controller.UpdateType = VRM10Controller.VRM10ControllerImpl.UpdateTypes.LateUpdate; // after HumanPoseTransfer's setPose + { + m_loaded = go.AddComponent(); + m_loaded.Source = m_src; + m_loaded.SourceType = HumanPoseTransfer.HumanPoseTransferSourceType.HumanPoseTransfer; + + m_lipSync = go.AddComponent(); + m_blink = go.AddComponent(); + + m_controller.LookAt.Gaze = m_target.transform; + } } var animation = go.GetComponent(); @@ -402,7 +402,6 @@ namespace UniVRM10.Samples { animation.Play(animation.clip.name); } - } } diff --git a/Assets/VRM10/Editor/Components/Expression/ExpressionEditorBase.cs b/Assets/VRM10/Editor/Components/Expression/ExpressionEditorBase.cs index b4317464e..766093048 100644 --- a/Assets/VRM10/Editor/Components/Expression/ExpressionEditorBase.cs +++ b/Assets/VRM10/Editor/Components/Expression/ExpressionEditorBase.cs @@ -275,24 +275,5 @@ namespace UniVRM10 } } } - - public override string GetInfoString() - { - var expression = CurrentExpression(); - if (expression == null) - { - return "no expression"; - } - - var key = ExpressionKey.CreateFromClip(expression); - if (key.Preset != VrmLib.ExpressionPreset.Custom) - { - return string.Format("Preset: {0}", key.Preset); - } - else - { - return string.Format("Custom: {0}", key.Name); - } - } } } diff --git a/Assets/VRM10/Editor/Components/Expression/ReorderableMaterialColorBindingList.cs b/Assets/VRM10/Editor/Components/Expression/ReorderableMaterialColorBindingList.cs index 75f843228..e8ab85982 100644 --- a/Assets/VRM10/Editor/Components/Expression/ReorderableMaterialColorBindingList.cs +++ b/Assets/VRM10/Editor/Components/Expression/ReorderableMaterialColorBindingList.cs @@ -52,7 +52,7 @@ namespace UniVRM10 // 対象のプロパティを enum から選択する var bindTypeProp = property.FindPropertyRelative("BindType"); - var bindTypes = (VrmLib.MaterialBindType[])Enum.GetValues(typeof(VrmLib.MaterialBindType)); + var bindTypes = (UniGLTF.Extensions.VRMC_vrm.MaterialColorType[])Enum.GetValues(typeof(UniGLTF.Extensions.VRMC_vrm.MaterialColorType)); var bindType = bindTypes[bindTypeProp.enumValueIndex]; var newBindType = ExpressionEditorHelper.EnumPopup(rect, bindType); if (newBindType != bindType) diff --git a/Assets/VRM10/Editor/Components/VRM10ControllerEditor.cs b/Assets/VRM10/Editor/Components/VRM10ControllerEditor.cs index 8e4c425d3..4d3309419 100644 --- a/Assets/VRM10/Editor/Components/VRM10ControllerEditor.cs +++ b/Assets/VRM10/Editor/Components/VRM10ControllerEditor.cs @@ -58,7 +58,6 @@ namespace UniVRM10 m_lookAt = PropGui.FromObject(serializedObject, nameof(m_target.LookAt)); m_firstPerson = PropGui.FromObject(serializedObject, nameof(m_target.FirstPerson)); m_springBone = PropGui.FromObject(serializedObject, nameof(m_target.SpringBone)); - m_asset = PropGui.FromObject(serializedObject, nameof(m_target.ModelAsset)); } void OnDisable() @@ -78,7 +77,6 @@ namespace UniVRM10 LookAt, FirstPerson, SpringBone, - Assets, } Tabs _tab; @@ -136,7 +134,7 @@ namespace UniVRM10 } serializedObject.Update(); - + // Setup runtime function. m_target.Setup(); @@ -167,10 +165,6 @@ namespace UniVRM10 case Tabs.SpringBone: m_springBone.RecursiveProperty(); break; - - case Tabs.Assets: - m_asset.RecursiveProperty(); - break; } serializedObject.ApplyModifiedProperties(); @@ -194,7 +188,7 @@ namespace UniVRM10 { EditorGUILayout.Space(); EditorGUILayout.LabelField("Expression Weights", EditorStyles.boldLabel); - + var sliders = m_sliders.Select(x => x.Slider()); foreach (var slider in sliders) { @@ -202,7 +196,7 @@ namespace UniVRM10 } m_target.Expression.SetWeights(m_expressionKeyWeights); } - + EditorGUILayout.Space(); EditorGUILayout.LabelField("Override rates", EditorStyles.boldLabel); EditorGUI.BeginDisabledGroup(true); diff --git a/Assets/VRM10/Editor/EditorUnityBuilder.cs b/Assets/VRM10/Editor/EditorUnityBuilder.cs index 948851801..8d7413577 100644 --- a/Assets/VRM10/Editor/EditorUnityBuilder.cs +++ b/Assets/VRM10/Editor/EditorUnityBuilder.cs @@ -8,132 +8,132 @@ namespace UniVRM10 { public static class EditorUnityBuilder { - static public ModelAsset ToUnityAsset(VrmLib.Model model, string assetPath, IExternalUnityObject scriptedImporter) - { - var modelAsset = new ModelAsset(); - CreateTextureAsset(model, modelAsset, scriptedImporter); - CreateMaterialAsset(model, modelAsset, scriptedImporter); - CreateMeshAsset(model, modelAsset); + // static public ModelAsset ToUnityAsset(VrmLib.Model model, string assetPath, IExternalUnityObject scriptedImporter) + // { + // var modelAsset = new ModelAsset(); + // CreateTextureAsset(model, modelAsset, scriptedImporter); + // CreateMaterialAsset(model, modelAsset, scriptedImporter); + // CreateMeshAsset(model, modelAsset); - // node - RuntimeUnityBuilder.CreateNodes(model.Root, null, modelAsset.Map.Nodes); - modelAsset.Root = modelAsset.Map.Nodes[model.Root]; + // // node + // RuntimeUnityBuilder.CreateNodes(model.Root, null, modelAsset.Map.Nodes); + // modelAsset.Root = modelAsset.Map.Nodes[model.Root]; - // renderer - var map = modelAsset.Map; - foreach (var (node, go) in map.Nodes) - { - if (node.MeshGroup is null) - { - continue; - } + // // renderer + // var map = modelAsset.Map; + // foreach (var (node, go) in map.Nodes) + // { + // if (node.MeshGroup is null) + // { + // continue; + // } - if (node.MeshGroup.Meshes.Count > 1) - { - throw new NotImplementedException("invalid isolated vertexbuffer"); - } + // if (node.MeshGroup.Meshes.Count > 1) + // { + // throw new NotImplementedException("invalid isolated vertexbuffer"); + // } - var renderer = RuntimeUnityBuilder.CreateRenderer(node, go, map); - map.Renderers.Add(node, renderer); - modelAsset.Renderers.Add(renderer); - } + // var renderer = RuntimeUnityBuilder.CreateRenderer(node, go, map); + // map.Renderers.Add(node, renderer); + // modelAsset.Renderers.Add(renderer); + // } - if (model.Vrm != null) - { - // humanoid - var humanoid = modelAsset.Root.AddComponent(); - humanoid.AssignBones(modelAsset.Map.Nodes.Select(x => (x.Key.HumanoidBone.GetValueOrDefault().ToUnity(), x.Value.transform))); - modelAsset.HumanoidAvatar = humanoid.CreateAvatar(); - modelAsset.HumanoidAvatar.name = "VRM"; + // if (model.Vrm != null) + // { + // // humanoid + // var humanoid = modelAsset.Root.AddComponent(); + // humanoid.AssignBones(modelAsset.Map.Nodes.Select(x => (x.Key.HumanoidBone.GetValueOrDefault().ToUnity(), x.Value.transform))); + // modelAsset.HumanoidAvatar = humanoid.CreateAvatar(); + // modelAsset.HumanoidAvatar.name = "VRM"; - var animator = modelAsset.Root.AddComponent(); - animator.avatar = modelAsset.HumanoidAvatar; - } + // var animator = modelAsset.Root.AddComponent(); + // animator.avatar = modelAsset.HumanoidAvatar; + // } - return modelAsset; - } + // return modelAsset; + // } - static private void CreateTextureAsset(VrmLib.Model model, ModelAsset modelAsset, IExternalUnityObject scriptedImporter) - { - var externalObjects = scriptedImporter.GetExternalUnityObjects(); + // static private void CreateTextureAsset(VrmLib.Model model, ModelAsset modelAsset, IExternalUnityObject scriptedImporter) + // { + // var externalObjects = scriptedImporter.GetExternalUnityObjects(); - // textures - for (int i = 0; i < model.Textures.Count; ++i) - { - if (model.Textures[i] is VrmLib.ImageTexture imageTexture) - { - if (string.IsNullOrEmpty(model.Textures[i].Name)) - { - model.Textures[i].Name = string.Format("{0}_img{1}", model.Root.Name, i); - } - if (externalObjects.ContainsKey(model.Textures[i].Name)) - { - modelAsset.Map.Textures.Add(imageTexture, externalObjects[model.Textures[i].Name]); - modelAsset.Textures.Add(externalObjects[model.Textures[i].Name]); - } - else - { - var name = !string.IsNullOrEmpty(imageTexture.Name) - ? imageTexture.Name - : string.Format("{0}_img{1}", model.Root.Name, i); + // // textures + // for (int i = 0; i < model.Textures.Count; ++i) + // { + // if (model.Textures[i] is VrmLib.ImageTexture imageTexture) + // { + // if (string.IsNullOrEmpty(model.Textures[i].Name)) + // { + // model.Textures[i].Name = string.Format("{0}_img{1}", model.Root.Name, i); + // } + // if (externalObjects.ContainsKey(model.Textures[i].Name)) + // { + // modelAsset.Map.Textures.Add(imageTexture, externalObjects[model.Textures[i].Name]); + // modelAsset.Textures.Add(externalObjects[model.Textures[i].Name]); + // } + // else + // { + // var name = !string.IsNullOrEmpty(imageTexture.Name) + // ? imageTexture.Name + // : string.Format("{0}_img{1}", model.Root.Name, i); - var texture = RuntimeUnityBuilder.CreateTexture(imageTexture); - texture.name = name; + // var texture = RuntimeUnityBuilder.CreateTexture(imageTexture); + // texture.name = name; - modelAsset.Map.Textures.Add(imageTexture, texture); - modelAsset.Textures.Add(texture); - } - } - else - { - Debug.LogWarning($"{i} not ImageTexture"); - } - } - } + // modelAsset.Map.Textures.Add(imageTexture, texture); + // modelAsset.Textures.Add(texture); + // } + // } + // else + // { + // Debug.LogWarning($"{i} not ImageTexture"); + // } + // } + // } - static private void CreateMaterialAsset(VrmLib.Model model, ModelAsset modelAsset, IExternalUnityObject scriptedImporter) - { - var externalObjects = scriptedImporter.GetExternalUnityObjects(); + // static private void CreateMaterialAsset(VrmLib.Model model, ModelAsset modelAsset, IExternalUnityObject scriptedImporter) + // { + // var externalObjects = scriptedImporter.GetExternalUnityObjects(); - foreach (var src in model.Materials) - { - if (externalObjects.ContainsKey(src.Name)) - { - modelAsset.Map.Materials.Add(src, externalObjects[src.Name]); - modelAsset.Materials.Add(externalObjects[src.Name]); - } - else - { - // TODO: material has VertexColor - var material = RuntimeUnityMaterialBuilder.CreateMaterialAsset(src, hasVertexColor: false, modelAsset.Map.Textures); - material.name = src.Name; - modelAsset.Map.Materials.Add(src, material); - modelAsset.Materials.Add(material); - } - } - } + // foreach (var src in model.Materials) + // { + // if (externalObjects.ContainsKey(src.Name)) + // { + // modelAsset.Map.Materials.Add(src, externalObjects[src.Name]); + // modelAsset.Materials.Add(externalObjects[src.Name]); + // } + // else + // { + // // TODO: material has VertexColor + // var material = RuntimeUnityMaterialBuilder.CreateMaterialAsset(src, hasVertexColor: false, modelAsset.Map.Textures); + // material.name = src.Name; + // modelAsset.Map.Materials.Add(src, material); + // modelAsset.Materials.Add(material); + // } + // } + // } - static private void CreateMeshAsset(VrmLib.Model model, ModelAsset modelAsset) - { - for (int i = 0; i < model.MeshGroups.Count; ++i) - { - var src = model.MeshGroups[i]; - if (src.Meshes.Count == 1) - { - // submesh 方式 - var mesh = new UnityEngine.Mesh(); - mesh.name = src.Name; - mesh.LoadMesh(src.Meshes[0], src.Skin); - modelAsset.Map.Meshes.Add(src, mesh); - modelAsset.Meshes.Add(mesh); - } - else - { - // 頂点バッファの連結が必用 - throw new NotImplementedException(); - } - } - } + // static private void CreateMeshAsset(VrmLib.Model model, ModelAsset modelAsset) + // { + // for (int i = 0; i < model.MeshGroups.Count; ++i) + // { + // var src = model.MeshGroups[i]; + // if (src.Meshes.Count == 1) + // { + // // submesh 方式 + // var mesh = new UnityEngine.Mesh(); + // mesh.name = src.Name; + // mesh.LoadMesh(src.Meshes[0], src.Skin); + // modelAsset.Map.Meshes.Add(src, mesh); + // modelAsset.Meshes.Add(mesh); + // } + // else + // { + // // 頂点バッファの連結が必用 + // throw new NotImplementedException(); + // } + // } + // } } } diff --git a/Assets/VRM10/Editor/ScriptedImporter/IExternalUnityObject.cs b/Assets/VRM10/Editor/ScriptedImporter/IExternalUnityObject.cs deleted file mode 100644 index 996e9be8b..000000000 --- a/Assets/VRM10/Editor/ScriptedImporter/IExternalUnityObject.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections.Generic; - -namespace UniVRM10 -{ - public interface IExternalUnityObject - { - Dictionary GetExternalUnityObjects() where T : UnityEngine.Object; - void SetExternalUnityObject(UnityEditor.AssetImporter.SourceAssetIdentifier sourceAssetIdentifier, T obj) where T : UnityEngine.Object; - } -} - - diff --git a/Assets/VRM10/Editor/ScriptedImporter/ScriptedImporterExtension.cs b/Assets/VRM10/Editor/ScriptedImporter/ScriptedImporterExtension.cs deleted file mode 100644 index 631a5c2bf..000000000 --- a/Assets/VRM10/Editor/ScriptedImporter/ScriptedImporterExtension.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEditor; -using System; -using UnityEngine; -#if UNITY_2020_2_OR_NEWER -using UnityEditor.AssetImporters; -#else -using UnityEditor.Experimental.AssetImporters; -#endif - - -namespace UniVRM10 -{ - public static class ScriptedImporterExtension - { - public static void ClearExternalObjects(this ScriptedImporter importer) where T : UnityEngine.Object - { - foreach (var extarnalObject in importer.GetExternalObjectMap().Where(x => x.Key.type == typeof(T))) - { - importer.RemoveRemap(extarnalObject.Key); - } - - AssetDatabase.WriteImportSettingsIfDirty(importer.assetPath); - AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate); - } - - public static void ClearExtarnalObjects(this ScriptedImporter importer) - { - foreach (var extarnalObject in importer.GetExternalObjectMap()) - { - importer.RemoveRemap(extarnalObject.Key); - } - - AssetDatabase.WriteImportSettingsIfDirty(importer.assetPath); - AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate); - } - - private static T GetSubAsset(this ScriptedImporter importer, string assetPath) where T : UnityEngine.Object - { - return importer.GetSubAssets(assetPath) - .FirstOrDefault(); - } - - public static IEnumerable GetSubAssets(this ScriptedImporter importer, string assetPath) where T : UnityEngine.Object - { - return AssetDatabase - .LoadAllAssetsAtPath(assetPath) - .Where(x => AssetDatabase.IsSubAsset(x)) - .Where(x => x is T) - .Select(x => x as T); - } - - private static void ExtractFromAsset(UnityEngine.Object subAsset, string destinationPath, bool isForceUpdate) - { - string assetPath = AssetDatabase.GetAssetPath(subAsset); - - var clone = UnityEngine.Object.Instantiate(subAsset); - AssetDatabase.CreateAsset(clone, destinationPath); - - var assetImporter = AssetImporter.GetAtPath(assetPath); - assetImporter.AddRemap(new AssetImporter.SourceAssetIdentifier(subAsset), clone); - - if (isForceUpdate) - { - AssetDatabase.WriteImportSettingsIfDirty(assetPath); - AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); - } - } - - public static void ExtractAssets(this ScriptedImporter importer, string dirName, string extension) where T : UnityEngine.Object - { - if (string.IsNullOrEmpty(importer.assetPath)) - return; - - var subAssets = importer.GetSubAssets(importer.assetPath); - - var path = string.Format("{0}/{1}.{2}", - Path.GetDirectoryName(importer.assetPath), - Path.GetFileNameWithoutExtension(importer.assetPath), - dirName - ); - - var info = importer.SafeCreateDirectory(path); - - foreach (var asset in subAssets) - { - ExtractFromAsset(asset, string.Format("{0}/{1}{2}", path, asset.name, extension), false); - } - } - - - public static void ExtractTextures(this ScriptedImporter importer, string dirName, Func CreateModel, Action onComplited = null) - { - if (string.IsNullOrEmpty(importer.assetPath)) - return; - - var subAssets = importer.GetSubAssets(importer.assetPath); - - var path = string.Format("{0}/{1}.{2}", - Path.GetDirectoryName(importer.assetPath), - Path.GetFileNameWithoutExtension(importer.assetPath), - dirName - ); - - importer.SafeCreateDirectory(path); - - Dictionary targetPaths = new Dictionary(); - - // Reload Model - var model = CreateModel(importer.assetPath); - var mimeTypeReg = new System.Text.RegularExpressions.Regex("image/(?.*)$"); - int count = 0; - foreach (var texture in model.Textures) - { - var imageTexture = texture as VrmLib.ImageTexture; - if (imageTexture == null) continue; - - var mimeType = mimeTypeReg.Match(imageTexture.Image.MimeType); - var assetName = !string.IsNullOrEmpty(imageTexture.Name) ? imageTexture.Name : string.Format("{0}_img{1}", model.Root.Name, count); - var targetPath = string.Format("{0}/{1}.{2}", - path, - assetName, - mimeType.Groups["mime"].Value); - imageTexture.Name = assetName; - - if (imageTexture.TextureType == VrmLib.Texture.TextureTypes.MetallicRoughness - || imageTexture.TextureType == VrmLib.Texture.TextureTypes.Occlusion) - { - var subAssetTexture = subAssets.Where(x => x.name == imageTexture.Name).FirstOrDefault(); - File.WriteAllBytes(targetPath, subAssetTexture.EncodeToPNG()); - } - else - { - File.WriteAllBytes(targetPath, imageTexture.Image.Bytes.ToArray()); - } - - AssetDatabase.ImportAsset(targetPath); - targetPaths.Add(imageTexture, targetPath); - - count++; - } - - EditorApplication.delayCall += () => - { - foreach (var targetPath in targetPaths) - { - var imageTexture = targetPath.Key; - var targetTextureImporter = AssetImporter.GetAtPath(targetPath.Value) as TextureImporter; - targetTextureImporter.sRGBTexture = (imageTexture.ColorSpace == VrmLib.Texture.ColorSpaceTypes.Srgb); - if (imageTexture.TextureType == VrmLib.Texture.TextureTypes.NormalMap) - { - targetTextureImporter.textureType = TextureImporterType.NormalMap; - } - targetTextureImporter.SaveAndReimport(); - - var externalObject = AssetDatabase.LoadAssetAtPath(targetPath.Value, typeof(UnityEngine.Texture2D)); - importer.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(UnityEngine.Texture2D), imageTexture.Name), externalObject); - } - - //AssetDatabase.WriteImportSettingsIfDirty(assetPath); - AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate); - - if (onComplited != null) - { - onComplited(); - } - }; - } - - public static DirectoryInfo SafeCreateDirectory(this ScriptedImporter importer, string path) - { - if (Directory.Exists(path)) - { - return null; - } - return Directory.CreateDirectory(path); - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/Editor/ScriptedImporter/ScriptedImporterExtension.cs.meta b/Assets/VRM10/Editor/ScriptedImporter/ScriptedImporterExtension.cs.meta deleted file mode 100644 index 8cfda53c8..000000000 --- a/Assets/VRM10/Editor/ScriptedImporter/ScriptedImporterExtension.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: eb950c51864585a4688048266e6c3a00 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporter.cs b/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporter.cs index 71bfc5ffd..2df3dce66 100644 --- a/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporter.cs +++ b/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporter.cs @@ -1,221 +1,22 @@ -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEditor; -#if UNITY_2020_2_OR_NEWER +#if UNITY_2020_2_OR_NEWER using UnityEditor.AssetImporters; #else using UnityEditor.Experimental.AssetImporters; +using UnityEngine; #endif namespace UniVRM10 { - [ScriptedImporter(1, "vrm")] - public class VrmScriptedImporter : ScriptedImporter, IExternalUnityObject + public class VrmScriptedImporter : ScriptedImporter { - const string TextureDirName = "Textures"; - const string MaterialDirName = "Materials"; - const string MetaDirName = "MetaObjects"; - const string ExpressionDirName = "Expressions"; + [SerializeField] + public bool MigrateToVrm1 = default; public override void OnImportAsset(AssetImportContext ctx) { - Debug.Log("OnImportAsset to " + ctx.assetPath); - - try - { - // Create Vrm Model - VrmLib.Model model = VrmLoader.CreateVrmModel(ctx.assetPath); - if (model == null) - { - // maybe VRM-0.X - return; - } - Debug.Log($"VrmLoader.CreateVrmModel: {model}"); - - // Build Unity Model - var assets = EditorUnityBuilder.ToUnityAsset(model, assetPath, this); - ComponentBuilder.Build10(model, assets); - - // Texture - var externalTextures = this.GetExternalUnityObjects(); - foreach (var texture in assets.Textures) - { - if (texture == null) - continue; - - if (externalTextures.ContainsValue(texture)) - { - } - else - { - ctx.AddObjectToAsset(texture.name, texture); - } - } - - // Material - var externalMaterials = this.GetExternalUnityObjects(); - foreach (var material in assets.Materials) - { - if (material == null) - continue; - - if (externalMaterials.ContainsValue(material)) - { - - } - else - { - ctx.AddObjectToAsset(material.name, material); - } - } - - // Mesh - foreach (var mesh in assets.Meshes) - { - ctx.AddObjectToAsset(mesh.name, mesh); - } - - //// ScriptableObject - // avatar - ctx.AddObjectToAsset("avatar", assets.HumanoidAvatar); - - // meta - { - var external = this.GetExternalUnityObjects().FirstOrDefault(); - if (external.Value != null) - { - var controller = assets.Root.GetComponent(); - if (controller != null) - { - controller.Meta = external.Value; - } - } - else - { - var meta = assets.ScriptableObjects - .FirstOrDefault(x => x.GetType() == typeof(UniVRM10.VRM10MetaObject)) as UniVRM10.VRM10MetaObject; - if (meta != null) - { - meta.name = "meta"; - ctx.AddObjectToAsset(meta.name, meta); - } - } - } - - // expression - { - var external = this.GetExternalUnityObjects(); - if (external.Any()) - { - } - else - { - var expression = assets.ScriptableObjects - .Where(x => x.GetType() == typeof(UniVRM10.VRM10Expression)) - .Select(x => x as UniVRM10.VRM10Expression); - foreach (var clip in expression) - { - clip.name = clip.ExpressionName; - ctx.AddObjectToAsset(clip.ExpressionName, clip); - } - } - } - { - var external = this.GetExternalUnityObjects().FirstOrDefault(); - if (external.Value != null) - { - var controller = assets.Root.GetComponent(); - if (controller != null) - { - controller.Expression.ExpressionAvatar = external.Value; - } - } - else - { - var expressionAvatar = assets.ScriptableObjects - .FirstOrDefault(x => x.GetType() == typeof(UniVRM10.VRM10ExpressionAvatar)) as UniVRM10.VRM10ExpressionAvatar; - if (expressionAvatar != null) - { - expressionAvatar.name = "expressionAvatar"; - ctx.AddObjectToAsset(expressionAvatar.name, expressionAvatar); - } - } - } - - // Root - ctx.AddObjectToAsset(assets.Root.name, assets.Root); - ctx.SetMainObject(assets.Root); - - } - catch (System.Exception ex) - { - Debug.LogError(ex); - } - } - - public void ExtractTextures() - { - this.ExtractTextures(TextureDirName, (path) => { return VrmLoader.CreateVrmModel(path); }); - AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); - } - - public void ExtractMaterials() - { - this.ExtractAssets(MaterialDirName, ".mat"); - AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); - } - - public void ExtractMaterialsAndTextures() - { - this.ExtractTextures(TextureDirName, (path) => { return VrmLoader.CreateVrmModel(path); }, () => { this.ExtractAssets(MaterialDirName, ".mat"); }); - AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); - } - - public void ExtractMeta() - { - this.ExtractAssets(MetaDirName, ".asset"); - var metaObject = this.GetExternalUnityObjects().FirstOrDefault(); - var metaObjectPath = AssetDatabase.GetAssetPath(metaObject.Value); - if (!string.IsNullOrEmpty(metaObjectPath)) - { - EditorUtility.SetDirty(metaObject.Value); - AssetDatabase.WriteImportSettingsIfDirty(metaObjectPath); - } - AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); - } - - public void ExtractExpressions() - { - this.ExtractAssets(ExpressionDirName, ".asset"); - this.ExtractAssets(ExpressionDirName, ".asset"); - - var expressionAvatar = this.GetExternalUnityObjects().FirstOrDefault(); - var expressions = this.GetExternalUnityObjects(); - - expressionAvatar.Value.Clips = expressions.Select(x => x.Value).ToList(); - var avatarPath = AssetDatabase.GetAssetPath(expressionAvatar.Value); - if (!string.IsNullOrEmpty(avatarPath)) - { - EditorUtility.SetDirty(expressionAvatar.Value); - AssetDatabase.WriteImportSettingsIfDirty(avatarPath); - } - - AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); - } - - public Dictionary GetExternalUnityObjects() where T : UnityEngine.Object - { - return this.GetExternalObjectMap().Where(x => x.Key.type == typeof(T)).ToDictionary(x => x.Key.name, x => (T)x.Value); - } - - public void SetExternalUnityObject(UnityEditor.AssetImporter.SourceAssetIdentifier sourceAssetIdentifier, T obj) where T : UnityEngine.Object - { - this.AddRemap(sourceAssetIdentifier, obj); - AssetDatabase.WriteImportSettingsIfDirty(this.assetPath); - AssetDatabase.ImportAsset(this.assetPath, ImportAssetOptions.ForceUpdate); + VrmScriptedImporterImpl.Import(this, ctx, MigrateToVrm1); } } -} \ No newline at end of file +} diff --git a/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterEditorGUI.cs b/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterEditorGUI.cs index a9aacd84d..f89d8be68 100644 --- a/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterEditorGUI.cs +++ b/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterEditorGUI.cs @@ -1,6 +1,7 @@ using System.Linq; using UnityEditor; using UnityEngine; +using UniGLTF; #if UNITY_2020_2_OR_NEWER using UnityEditor.AssetImporters; #else @@ -13,91 +14,140 @@ namespace UniVRM10 [CustomEditor(typeof(VrmScriptedImporter))] public class VrmScriptedImporterEditorGUI : ScriptedImporterEditor { + // const string TextureDirName = "Textures"; + // const string MaterialDirName = "Materials"; + // const string MetaDirName = "MetaObjects"; + // const string ExpressionDirName = "Expressions"; - private bool _isOpen = true; + VrmScriptedImporter m_importer; + GltfParser m_parser; + VrmLib.Model m_model; + + public override void OnEnable() + { + base.OnEnable(); + + m_importer = target as VrmScriptedImporter; + m_parser = VrmScriptedImporterImpl.Parse(m_importer.assetPath, m_importer.MigrateToVrm1); + if (m_parser == null) + { + return; + } + + m_model = VrmLoader.CreateVrmModel(m_parser); + } + + enum Tabs + { + Model, + Materials, + Vrm, + } + static Tabs s_currentTab; public override void OnInspectorGUI() { - var importer = target as VrmScriptedImporter; + s_currentTab = MeshUtility.TabBar.OnGUI(s_currentTab); + GUILayout.Space(10); - EditorGUILayout.LabelField("Extract settings"); + switch (s_currentTab) + { + case Tabs.Model: + base.OnInspectorGUI(); + break; - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Materials And Textures"); - GUI.enabled = !(importer.GetExternalUnityObjects().Any() - && importer.GetExternalUnityObjects().Any()); - if (GUILayout.Button("Extract")) - { - importer.ExtractMaterialsAndTextures(); - } - GUI.enabled = !GUI.enabled; - if (GUILayout.Button("Clear")) - { - importer.ClearExternalObjects(); - importer.ClearExternalObjects(); - } - GUI.enabled = true; - EditorGUILayout.EndHorizontal(); + case Tabs.Materials: + if (m_parser != null) + { + EditorMaterial.OnGUIMaterial(m_importer, m_parser, Vrm10MToonMaterialImporter.EnumerateAllTexturesDistinct); + } + break; - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Meta"); - GUI.enabled = !importer.GetExternalUnityObjects().Any(); - if (GUILayout.Button("Extract")) - { - importer.ExtractMeta(); + case Tabs.Vrm: + break; } - GUI.enabled = !GUI.enabled; - if (GUILayout.Button("Clear")) - { - importer.ClearExternalObjects(); - } - GUI.enabled = true; - EditorGUILayout.EndHorizontal(); - - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Expressions"); - GUI.enabled = !(importer.GetExternalUnityObjects().Any() - && importer.GetExternalUnityObjects().Any()); - if (GUILayout.Button("Extract")) - { - importer.ExtractExpressions(); - } - GUI.enabled = !GUI.enabled; - if (GUILayout.Button("Clear")) - { - importer.ClearExternalObjects(); - importer.ClearExternalObjects(); - } - GUI.enabled = true; - EditorGUILayout.EndHorizontal(); - - // ObjectMap - DrawRemapGUI("Material Remap", importer); - DrawRemapGUI("Texture Remap", importer); - DrawRemapGUI("Meta Remap", importer); - DrawRemapGUI("ExpressionAvatar Remap", importer); - DrawRemapGUI("Expression Remap", importer); - - base.OnInspectorGUI(); } - private void DrawRemapGUI(string title, VrmScriptedImporter importer) where T : UnityEngine.Object - { - EditorGUILayout.Foldout(_isOpen, title); - EditorGUI.indentLevel++; - var objects = importer.GetExternalObjectMap().Where(x => x.Key.type == typeof(T)); - foreach (var obj in objects) - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel(obj.Key.name); - var asset = EditorGUILayout.ObjectField(obj.Value, obj.Key.type, true) as T; - if (asset != obj.Value) - { - importer.SetExternalUnityObject(obj.Key, asset); - } - EditorGUILayout.EndHorizontal(); - } - EditorGUI.indentLevel--; - } + // var importer = target as VrmScriptedImporter; + + // EditorGUILayout.LabelField("Extract settings"); + + // EditorGUILayout.BeginHorizontal(); + // EditorGUILayout.PrefixLabel("Materials And Textures"); + // GUI.enabled = !(importer.GetExternalUnityObjects().Any() + // && importer.GetExternalUnityObjects().Any()); + // if (GUILayout.Button("Extract")) + // { + // importer.ExtractMaterialsAndTextures(); + // } + // GUI.enabled = !GUI.enabled; + // if (GUILayout.Button("Clear")) + // { + // importer.ClearExternalObjects(); + // importer.ClearExternalObjects(); + // } + // GUI.enabled = true; + // EditorGUILayout.EndHorizontal(); + + // EditorGUILayout.BeginHorizontal(); + // EditorGUILayout.PrefixLabel("Meta"); + // GUI.enabled = !importer.GetExternalUnityObjects().Any(); + // if (GUILayout.Button("Extract")) + // { + // importer.ExtractMeta(); + // } + // GUI.enabled = !GUI.enabled; + // if (GUILayout.Button("Clear")) + // { + // importer.ClearExternalObjects(); + // } + // GUI.enabled = true; + // EditorGUILayout.EndHorizontal(); + + // EditorGUILayout.BeginHorizontal(); + // EditorGUILayout.PrefixLabel("Expressions"); + // GUI.enabled = !(importer.GetExternalUnityObjects().Any() + // && importer.GetExternalUnityObjects().Any()); + // if (GUILayout.Button("Extract")) + // { + // importer.ExtractExpressions(); + // } + // GUI.enabled = !GUI.enabled; + // if (GUILayout.Button("Clear")) + // { + // importer.ClearExternalObjects(); + // importer.ClearExternalObjects(); + // } + // GUI.enabled = true; + // EditorGUILayout.EndHorizontal(); + + // // ObjectMap + // DrawRemapGUI("Material Remap", importer); + // DrawRemapGUI("Texture Remap", importer); + // DrawRemapGUI("Meta Remap", importer); + // DrawRemapGUI("ExpressionAvatar Remap", importer); + // DrawRemapGUI("Expression Remap", importer); + + // base.OnInspectorGUI(); + // } + + // private void DrawRemapGUI(string title, VrmScriptedImporter importer) where T : UnityEngine.Object + // { + // EditorGUILayout.Foldout(_isOpen, title); + // EditorGUI.indentLevel++; + // var objects = importer.GetExternalObjectMap().Where(x => x.Key.type == typeof(T)); + // foreach (var obj in objects) + // { + // EditorGUILayout.BeginHorizontal(); + // EditorGUILayout.PrefixLabel(obj.Key.name); + // var asset = EditorGUILayout.ObjectField(obj.Value, obj.Key.type, true) as T; + // if (asset != obj.Value) + // { + // importer.SetExternalUnityObject(obj.Key, asset); + // } + // EditorGUILayout.EndHorizontal(); + // } + // EditorGUI.indentLevel--; + // } } } diff --git a/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterImpl.cs b/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterImpl.cs new file mode 100644 index 000000000..53a1b35de --- /dev/null +++ b/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterImpl.cs @@ -0,0 +1,208 @@ +using System.Linq; +using UnityEngine; +using UniGLTF; +using System.IO; +#if UNITY_2020_2_OR_NEWER +using UnityEditor.AssetImporters; +#else +using UnityEditor.Experimental.AssetImporters; +#endif + + +namespace UniVRM10 +{ + public static class VrmScriptedImporterImpl + { + /// + /// VRM1 で パースし、失敗したら Migration してから VRM1 でパースする + /// + /// + /// + /// + public static GltfParser Parse(string path, bool migrateToVrm1) + { + // + // Parse(parse glb, parser gltf json) + // + var parser = new GltfParser(); + parser.ParsePath(path); + if (UniGLTF.Extensions.VRMC_vrm.GltfDeserializer.TryGet(parser.GLTF.extensions, out UniGLTF.Extensions.VRMC_vrm.VRMC_vrm vrm)) + { + return parser; + } + + if (migrateToVrm1) + { + // try migrateion + var migrated = MigrationVrm.Migrate(File.ReadAllBytes(path)); + parser = new GltfParser(); + parser.Parse(path, migrated); + return parser; + } + + return null; + } + + public static void Import(ScriptedImporter scriptedImporter, AssetImportContext context, bool migrateToVrm1) + { +#if VRM_DEVELOP + Debug.Log("OnImportAsset to " + scriptedImporter.assetPath); +#endif + + var parser = Parse(scriptedImporter.assetPath, migrateToVrm1); + if (parser == null) + { + // fail to parse vrm1 + return; + } + + // + // Import(create unity objects) + // + var externalObjectMap = scriptedImporter.GetExternalObjectMap().Select(kv => (kv.Value.name, kv.Value)).ToArray(); + + using (var loader = new RuntimeUnityBuilder(parser, externalObjectMap)) + { + // settings TextureImporters + foreach (var textureInfo in Vrm10MToonMaterialImporter.EnumerateAllTexturesDistinct(parser)) + { + TextureImporterConfigurator.Configure(textureInfo, loader.TextureFactory.ExternalMap); + } + + loader.Load(); + loader.ShowMeshes(); + + loader.TransferOwnership(o => + { + context.AddObjectToAsset(o.name, o); + if (o is GameObject) + { + // Root GameObject is main object + context.SetMainObject(loader.Root); + } + + return true; + }); + } + } + + // public void ExtractMeta() + // { + // this.ExtractAssets(MetaDirName, ".asset"); + // var metaObject = this.GetExternalUnityObjects().FirstOrDefault(); + // var metaObjectPath = AssetDatabase.GetAssetPath(metaObject.Value); + // if (!string.IsNullOrEmpty(metaObjectPath)) + // { + // EditorUtility.SetDirty(metaObject.Value); + // AssetDatabase.WriteImportSettingsIfDirty(metaObjectPath); + // } + // AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); + // } + + // public void ExtractExpressions() + // { + // this.ExtractAssets(ExpressionDirName, ".asset"); + // this.ExtractAssets(ExpressionDirName, ".asset"); + + // var expressionAvatar = this.GetExternalUnityObjects().FirstOrDefault(); + // var expressions = this.GetExternalUnityObjects(); + + // expressionAvatar.Value.Clips = expressions.Select(x => x.Value).ToList(); + // var avatarPath = AssetDatabase.GetAssetPath(expressionAvatar.Value); + // if (!string.IsNullOrEmpty(avatarPath)) + // { + // EditorUtility.SetDirty(expressionAvatar.Value); + // AssetDatabase.WriteImportSettingsIfDirty(avatarPath); + // } + + // AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); + // } + + // public Dictionary GetExternalUnityObjects() where T : UnityEngine.Object + // { + // return this.GetExternalObjectMap().Where(x => x.Key.type == typeof(T)).ToDictionary(x => x.Key.name, x => (T)x.Value); + // } + + // public void SetExternalUnityObject(UnityEditor.AssetImporter.SourceAssetIdentifier sourceAssetIdentifier, T obj) where T : UnityEngine.Object + // { + // this.AddRemap(sourceAssetIdentifier, obj); + // AssetDatabase.WriteImportSettingsIfDirty(this.assetPath); + // AssetDatabase.ImportAsset(this.assetPath, ImportAssetOptions.ForceUpdate); + // } + + // public static void ClearExternalObjects(this ScriptedImporter importer) where T : UnityEngine.Object + // { + // foreach (var extarnalObject in importer.GetExternalObjectMap().Where(x => x.Key.type == typeof(T))) + // { + // importer.RemoveRemap(extarnalObject.Key); + // } + + // AssetDatabase.WriteImportSettingsIfDirty(importer.assetPath); + // AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate); + // } + + // public static void ClearExtarnalObjects(this ScriptedImporter importer) + // { + // foreach (var extarnalObject in importer.GetExternalObjectMap()) + // { + // importer.RemoveRemap(extarnalObject.Key); + // } + + // AssetDatabase.WriteImportSettingsIfDirty(importer.assetPath); + // AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate); + // } + + // private static T GetSubAsset(this ScriptedImporter importer, string assetPath) where T : UnityEngine.Object + // { + // return importer.GetSubAssets(assetPath) + // .FirstOrDefault(); + // } + + // public static IEnumerable GetSubAssets(this ScriptedImporter importer, string assetPath) where T : UnityEngine.Object + // { + // return AssetDatabase + // .LoadAllAssetsAtPath(assetPath) + // .Where(x => AssetDatabase.IsSubAsset(x)) + // .Where(x => x is T) + // .Select(x => x as T); + // } + + // private static void ExtractFromAsset(UnityEngine.Object subAsset, string destinationPath, bool isForceUpdate) + // { + // string assetPath = AssetDatabase.GetAssetPath(subAsset); + + // var clone = UnityEngine.Object.Instantiate(subAsset); + // AssetDatabase.CreateAsset(clone, destinationPath); + + // var assetImporter = AssetImporter.GetAtPath(assetPath); + // assetImporter.AddRemap(new AssetImporter.SourceAssetIdentifier(subAsset), clone); + + // if (isForceUpdate) + // { + // AssetDatabase.WriteImportSettingsIfDirty(assetPath); + // AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); + // } + // } + + // public static void ExtractAssets(this ScriptedImporter importer, string dirName, string extension) where T : UnityEngine.Object + // { + // if (string.IsNullOrEmpty(importer.assetPath)) + // return; + + // var subAssets = importer.GetSubAssets(importer.assetPath); + + // var path = string.Format("{0}/{1}.{2}", + // Path.GetDirectoryName(importer.assetPath), + // Path.GetFileNameWithoutExtension(importer.assetPath), + // dirName + // ); + + // var info = importer.SafeCreateDirectory(path); + + // foreach (var asset in subAssets) + // { + // ExtractFromAsset(asset, string.Format("{0}/{1}{2}", path, asset.name, extension), false); + // } + // } + } +} diff --git a/Assets/VRM/Runtime/IO/MToonMaterialImporter.cs.meta b/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterImpl.cs.meta similarity index 83% rename from Assets/VRM/Runtime/IO/MToonMaterialImporter.cs.meta rename to Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterImpl.cs.meta index cfac19cb9..4a1a7d4f9 100644 --- a/Assets/VRM/Runtime/IO/MToonMaterialImporter.cs.meta +++ b/Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterImpl.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 35c90d5d3fa706b4f87a92ce4dc59008 +guid: f08e514e6a60bd0479ed1c928e8b515e MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/VRM10/Editor/VRM10.Editor.asmdef b/Assets/VRM10/Editor/VRM10.Editor.asmdef index 9d1baa8c8..ad11988fe 100644 --- a/Assets/VRM10/Editor/VRM10.Editor.asmdef +++ b/Assets/VRM10/Editor/VRM10.Editor.asmdef @@ -6,7 +6,8 @@ "MeshUtility", "MeshUtility.Editor", "UniGLTF.Editor", - "UniGLTF" + "UniGLTF", + "VRMShaders" ], "optionalUnityReferences": [], "includePlatforms": [ diff --git a/Assets/VRM10/Editor/VRM10MetaObjectEditor.cs b/Assets/VRM10/Editor/VRM10MetaObjectEditor.cs index 9a1f06bbd..b5a906de5 100644 --- a/Assets/VRM10/Editor/VRM10MetaObjectEditor.cs +++ b/Assets/VRM10/Editor/VRM10MetaObjectEditor.cs @@ -135,7 +135,7 @@ namespace UniVRM10 { return ("", MessageType.None); }); - m_reference = new ValidateProperty(serializedObject.FindProperty(nameof(m_target.Reference)), prop => + m_reference = new ValidateProperty(serializedObject.FindProperty(nameof(m_target.References)), prop => { return ("", MessageType.None); }); diff --git a/Assets/VRM10/Editor/Vrm10ExportDialog.cs b/Assets/VRM10/Editor/Vrm10ExportDialog.cs index 743dba81d..de2d5665f 100644 --- a/Assets/VRM10/Editor/Vrm10ExportDialog.cs +++ b/Assets/VRM10/Editor/Vrm10ExportDialog.cs @@ -68,7 +68,7 @@ namespace UniVRM10 Selection.selectionChanged += Repaint; m_tmpMeta = ScriptableObject.CreateInstance(); - m_tmpMeta.Authors = new string[] { "" }; + m_tmpMeta.Authors = new List { "" }; m_state = new MeshUtility.ExporterDialogState(); m_state.ExportRootChanged += (root) => diff --git a/Assets/VRM10/Runtime/Components/Constraint/ConstraintAxes.cs b/Assets/VRM10/Runtime/Components/Constraint/ConstraintAxes.cs index 8229db85b..f2e1165a1 100644 --- a/Assets/VRM10/Runtime/Components/Constraint/ConstraintAxes.cs +++ b/Assets/VRM10/Runtime/Components/Constraint/ConstraintAxes.cs @@ -7,7 +7,7 @@ namespace UniVRM10 /// FreezeAxesで使う。bitマスク /// [Flags] - public enum AxesMask + public enum AxisMask { X = 1, Y = 2, @@ -16,17 +16,17 @@ namespace UniVRM10 public static class AxesMaskExtensions { - public static Vector3 Freeze(this AxesMask mask, Vector3 src) + public static Vector3 Freeze(this AxisMask mask, Vector3 src) { - if (mask.HasFlag(AxesMask.X)) + if (mask.HasFlag(AxisMask.X)) { src.x = 0; } - if (mask.HasFlag(AxesMask.Y)) + if (mask.HasFlag(AxisMask.Y)) { src.y = 0; } - if (mask.HasFlag(AxesMask.Z)) + if (mask.HasFlag(AxisMask.Z)) { src.z = 0; } diff --git a/Assets/VRM10/Runtime/Components/Constraint/ConstraintDestination.cs b/Assets/VRM10/Runtime/Components/Constraint/ConstraintDestination.cs index 4cca644dc..57478bba3 100644 --- a/Assets/VRM10/Runtime/Components/Constraint/ConstraintDestination.cs +++ b/Assets/VRM10/Runtime/Components/Constraint/ConstraintDestination.cs @@ -1,33 +1,28 @@ using System; +using UniGLTF.Extensions.VRMC_constraints; using UnityEngine; namespace UniVRM10 { - public enum DestinationCoordinates - { - World, - Local, - } - class ConstraintDestination { readonly Transform m_transform; - readonly DestinationCoordinates m_coords; + readonly ObjectSpace m_coords; readonly TRS m_initial; - public ConstraintDestination(Transform t, DestinationCoordinates coords) + public ConstraintDestination(Transform t, ObjectSpace coords) { m_transform = t; m_coords = coords; switch (m_coords) { - case DestinationCoordinates.World: - m_initial = TRS.GetWorld(t); - break; + // case ObjectSpace.World: + // m_initial = TRS.GetWorld(t); + // break; - case DestinationCoordinates.Local: + case ObjectSpace.local: m_initial = TRS.GetLocal(t); break; @@ -41,11 +36,11 @@ namespace UniVRM10 var value = m_initial.Translation + delta * weight; switch (m_coords) { - case DestinationCoordinates.World: - m_transform.position = value; - break; + // case DestinationCoordinates.World: + // m_transform.position = value; + // break; - case DestinationCoordinates.Local: + case ObjectSpace.local: m_transform.localPosition = value; break; @@ -60,11 +55,11 @@ namespace UniVRM10 var value = Quaternion.LerpUnclamped(Quaternion.identity, delta, weight) * m_initial.Rotation; switch (m_coords) { - case DestinationCoordinates.World: - m_transform.rotation = value; - break; + // case DestinationCoordinates.World: + // m_transform.rotation = value; + // break; - case DestinationCoordinates.Local: + case ObjectSpace.local: m_transform.localRotation = value; break; diff --git a/Assets/VRM10/Runtime/Components/Constraint/ConstraintSource.cs b/Assets/VRM10/Runtime/Components/Constraint/ConstraintSource.cs index a74ca1db3..3101adf18 100644 --- a/Assets/VRM10/Runtime/Components/Constraint/ConstraintSource.cs +++ b/Assets/VRM10/Runtime/Components/Constraint/ConstraintSource.cs @@ -1,33 +1,16 @@ using UnityEngine; using System; +using UniGLTF.Extensions.VRMC_constraints; namespace UniVRM10 { - public enum SourceCoordinates - { - /// - /// ワールド座標 - /// - World, - - /// - /// モデルルート(指定のTransform)ローカル座標 - /// - Model, - - /// - /// m_transform ローカル座標 - /// - Local, - } - class ConstraintSource { readonly Transform m_modelRoot; readonly Transform m_transform; - readonly SourceCoordinates m_coords; + readonly ObjectSpace m_coords; readonly TRS m_initial; @@ -37,9 +20,9 @@ namespace UniVRM10 { switch (m_coords) { - case SourceCoordinates.World: return m_transform.position - m_initial.Translation; - case SourceCoordinates.Local: return m_transform.localPosition - m_initial.Translation; - case SourceCoordinates.Model: return m_modelRoot.worldToLocalMatrix.MultiplyPoint(m_transform.position) - m_initial.Translation; + // case ObjectSpace.World: return m_transform.position - m_initial.Translation; + case ObjectSpace.local: return m_transform.localPosition - m_initial.Translation; + case ObjectSpace.model: return m_modelRoot.worldToLocalMatrix.MultiplyPoint(m_transform.position) - m_initial.Translation; default: throw new NotImplementedException(); } } @@ -52,30 +35,30 @@ namespace UniVRM10 switch (m_coords) { // 右からかけるか、左からかけるか、それが問題なのだ - case SourceCoordinates.World: return m_transform.rotation * Quaternion.Inverse(m_initial.Rotation); - case SourceCoordinates.Local: return m_transform.localRotation * Quaternion.Inverse(m_initial.Rotation); - case SourceCoordinates.Model: return m_transform.rotation * Quaternion.Inverse(m_modelRoot.rotation) * Quaternion.Inverse(m_initial.Rotation); + // case SourceCoordinates.World: return m_transform.rotation * Quaternion.Inverse(m_initial.Rotation); + case ObjectSpace.local: return m_transform.localRotation * Quaternion.Inverse(m_initial.Rotation); + case ObjectSpace.model: return m_transform.rotation * Quaternion.Inverse(m_modelRoot.rotation) * Quaternion.Inverse(m_initial.Rotation); default: throw new NotImplementedException(); } } } - public ConstraintSource(Transform t, SourceCoordinates coords, Transform modelRoot = null) + public ConstraintSource(Transform t, ObjectSpace coords, Transform modelRoot = null) { m_transform = t; m_coords = coords; switch (coords) { - case SourceCoordinates.World: - m_initial = TRS.GetWorld(t); - break; + // case SourceCoordinates.World: + // m_initial = TRS.GetWorld(t); + // break; - case SourceCoordinates.Local: + case ObjectSpace.local: m_initial = TRS.GetLocal(t); break; - case SourceCoordinates.Model: + case ObjectSpace.model: { var world = TRS.GetWorld(t); m_modelRoot = modelRoot; diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRMAimConstraint.cs b/Assets/VRM10/Runtime/Components/Constraint/VRM10AimConstraint.cs similarity index 95% rename from Assets/VRM10/Runtime/Components/Constraint/VRMAimConstraint.cs rename to Assets/VRM10/Runtime/Components/Constraint/VRM10AimConstraint.cs index 685116b57..5f2529c48 100644 --- a/Assets/VRM10/Runtime/Components/Constraint/VRMAimConstraint.cs +++ b/Assets/VRM10/Runtime/Components/Constraint/VRM10AimConstraint.cs @@ -11,10 +11,10 @@ namespace UniVRM10 /// /// [DisallowMultipleComponent] - public class VRMAimConstraint : VRMConstraint + public class VRM10AimConstraint : VRM10Constraint { [SerializeField] - Transform Source = default; + public Transform Source = default; // [SerializeField] // [Range(0, 10.0f)] @@ -24,12 +24,13 @@ namespace UniVRM10 /// Forward /// [SerializeField] - Vector3 AimVector = Vector3.forward; + public Vector3 AimVector = Vector3.forward; [SerializeField] - Vector3 UpVector = Vector3.up; + public Vector3 UpVector = Vector3.up; - Vector3 RightVector; + [SerializeField] + public Vector3 RightVector; Quaternion m_selfInitial; Matrix4x4 m_coords; diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRM10AimConstraint.cs.meta b/Assets/VRM10/Runtime/Components/Constraint/VRM10AimConstraint.cs.meta new file mode 100644 index 000000000..2b2331d9c --- /dev/null +++ b/Assets/VRM10/Runtime/Components/Constraint/VRM10AimConstraint.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e1e8c3a00191fbd4db98fb47ddb80e8c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRMConstraint.cs b/Assets/VRM10/Runtime/Components/Constraint/VRM10Constraint.cs similarity index 66% rename from Assets/VRM10/Runtime/Components/Constraint/VRMConstraint.cs rename to Assets/VRM10/Runtime/Components/Constraint/VRM10Constraint.cs index 45e1e848e..6ff82479a 100644 --- a/Assets/VRM10/Runtime/Components/Constraint/VRMConstraint.cs +++ b/Assets/VRM10/Runtime/Components/Constraint/VRM10Constraint.cs @@ -2,7 +2,7 @@ using UnityEngine; namespace UniVRM10 { - public abstract class VRMConstraint : MonoBehaviour + public abstract class VRM10Constraint : MonoBehaviour { public virtual void Process() { diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRM10Constraint.cs.meta b/Assets/VRM10/Runtime/Components/Constraint/VRM10Constraint.cs.meta new file mode 100644 index 000000000..37ffe7564 --- /dev/null +++ b/Assets/VRM10/Runtime/Components/Constraint/VRM10Constraint.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ded8c4db12c688b46814cf0bf925cacf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRMPositionConstraint.cs b/Assets/VRM10/Runtime/Components/Constraint/VRM10PositionConstraint.cs similarity index 76% rename from Assets/VRM10/Runtime/Components/Constraint/VRMPositionConstraint.cs rename to Assets/VRM10/Runtime/Components/Constraint/VRM10PositionConstraint.cs index ef29e7a25..200222977 100644 --- a/Assets/VRM10/Runtime/Components/Constraint/VRMPositionConstraint.cs +++ b/Assets/VRM10/Runtime/Components/Constraint/VRM10PositionConstraint.cs @@ -1,4 +1,5 @@ -using UnityEngine; +using UniGLTF.Extensions.VRMC_constraints; +using UnityEngine; namespace UniVRM10 { @@ -6,26 +7,26 @@ namespace UniVRM10 /// 対象の初期位置と現在位置の差分(delta)を、自身の初期位置に対してWeightを乗算して加算する。 /// [DisallowMultipleComponent] - public class VRMPositionConstraint : VRMConstraint + public class VRM10PositionConstraint : VRM10Constraint { [SerializeField] - Transform Source = default; + public Transform Source = default; [SerializeField] - SourceCoordinates SourceCoordinate = default; + public ObjectSpace SourceCoordinate = default; [SerializeField] - DestinationCoordinates DestinationCoordinate = default; + public ObjectSpace DestinationCoordinate = default; [SerializeField] - AxesMask FreezeAxes = default; + public AxisMask FreezeAxes = default; [SerializeField] [Range(0, 10.0f)] - float Weight = 1.0f; + public float Weight = 1.0f; [SerializeField] - Transform ModelRoot = default; + public Transform ModelRoot = default; ConstraintSource m_src; diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRM10PositionConstraint.cs.meta b/Assets/VRM10/Runtime/Components/Constraint/VRM10PositionConstraint.cs.meta new file mode 100644 index 000000000..4105f28a1 --- /dev/null +++ b/Assets/VRM10/Runtime/Components/Constraint/VRM10PositionConstraint.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6fec0847a81b2124c9f67575d247b1f9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRMRotationConstraint.cs b/Assets/VRM10/Runtime/Components/Constraint/VRM10RotationConstraint.cs similarity index 81% rename from Assets/VRM10/Runtime/Components/Constraint/VRMRotationConstraint.cs rename to Assets/VRM10/Runtime/Components/Constraint/VRM10RotationConstraint.cs index 4ed4c1e07..e360904aa 100644 --- a/Assets/VRM10/Runtime/Components/Constraint/VRMRotationConstraint.cs +++ b/Assets/VRM10/Runtime/Components/Constraint/VRM10RotationConstraint.cs @@ -1,4 +1,5 @@ -using UnityEngine; +using UniGLTF.Extensions.VRMC_constraints; +using UnityEngine; namespace UniVRM10 @@ -7,26 +8,26 @@ namespace UniVRM10 /// 対象の初期回転と現在回転の差分(delta)を、自身の初期回転と自身の初期回転にdeltaを乗算したものに対してWeightでSlerpする。 /// [DisallowMultipleComponent] - public class VRMRotationConstraint : VRMConstraint + public class VRM10RotationConstraint : VRM10Constraint { [SerializeField] - Transform Source = default; + public Transform Source = default; [SerializeField] - SourceCoordinates SourceCoordinate = default; + public ObjectSpace SourceCoordinate = default; [SerializeField] - DestinationCoordinates DestinationCoordinate = default; + public ObjectSpace DestinationCoordinate = default; [SerializeField] - AxesMask FreezeAxes = default; + public AxisMask FreezeAxes = default; [SerializeField] [Range(0, 10.0f)] - float Weight = 1.0f; + public float Weight = 1.0f; [SerializeField] - Transform ModelRoot = default; + public Transform ModelRoot = default; ConstraintSource m_src; diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRM10RotationConstraint.cs.meta b/Assets/VRM10/Runtime/Components/Constraint/VRM10RotationConstraint.cs.meta new file mode 100644 index 000000000..4eaea4e14 --- /dev/null +++ b/Assets/VRM10/Runtime/Components/Constraint/VRM10RotationConstraint.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a07fbecedce41b4396f286fd7634e1d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRMAimConstraint.cs.meta b/Assets/VRM10/Runtime/Components/Constraint/VRMAimConstraint.cs.meta deleted file mode 100644 index 9b67ac4a2..000000000 --- a/Assets/VRM10/Runtime/Components/Constraint/VRMAimConstraint.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a8f13bc2bb7b6734e92bba2b204e2e49 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRMConstraint.cs.meta b/Assets/VRM10/Runtime/Components/Constraint/VRMConstraint.cs.meta deleted file mode 100644 index 73d1134e8..000000000 --- a/Assets/VRM10/Runtime/Components/Constraint/VRMConstraint.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e017e9a63d31c4e4cbcc905a0caf0605 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRMPositionConstraint.cs.meta b/Assets/VRM10/Runtime/Components/Constraint/VRMPositionConstraint.cs.meta deleted file mode 100644 index 647bb21a1..000000000 --- a/Assets/VRM10/Runtime/Components/Constraint/VRMPositionConstraint.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0f104dcf447611a4ca99f4ac41e806e8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Components/Constraint/VRMRotationConstraint.cs.meta b/Assets/VRM10/Runtime/Components/Constraint/VRMRotationConstraint.cs.meta deleted file mode 100644 index 0ccca3c7b..000000000 --- a/Assets/VRM10/Runtime/Components/Constraint/VRMRotationConstraint.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e7e95091802973e488fdcc4b3840cdc5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Components/Expression/DefaultExpressionValidator.cs b/Assets/VRM10/Runtime/Components/Expression/DefaultExpressionValidator.cs index 4f0a9850d..aa57be80d 100644 --- a/Assets/VRM10/Runtime/Components/Expression/DefaultExpressionValidator.cs +++ b/Assets/VRM10/Runtime/Components/Expression/DefaultExpressionValidator.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using UniGLTF.Extensions.VRMC_vrm; using UnityEngine; using VrmLib; @@ -88,11 +89,11 @@ namespace UniVRM10 { switch (type) { - case ExpressionOverrideType.None: + case ExpressionOverrideType.none: return 0f; - case ExpressionOverrideType.Block: + case ExpressionOverrideType.block: return weight > 0f ? 1f : 0f; - case ExpressionOverrideType.Blend: + case ExpressionOverrideType.blend: return weight; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); diff --git a/Assets/VRM10/Runtime/Components/Expression/ExpressionKey.cs b/Assets/VRM10/Runtime/Components/Expression/ExpressionKey.cs index 1b0f0a9c2..70656d225 100644 --- a/Assets/VRM10/Runtime/Components/Expression/ExpressionKey.cs +++ b/Assets/VRM10/Runtime/Components/Expression/ExpressionKey.cs @@ -9,8 +9,8 @@ namespace UniVRM10 /// /// Enum.ToString() のGC回避用キャッシュ /// - private static readonly Dictionary PresetNameDictionary = - new Dictionary(); + private static readonly Dictionary PresetNameDictionary = + new Dictionary(); /// /// ExpressionPreset と同名の名前を持つ独自に追加した Expression を区別するための prefix @@ -20,7 +20,7 @@ namespace UniVRM10 /// /// Preset of this ExpressionKey. /// - public readonly VrmLib.ExpressionPreset Preset; + public readonly UniGLTF.Extensions.VRMC_vrm.ExpressionPreset Preset; /// /// Custom Name of this ExpressionKey. @@ -39,9 +39,9 @@ namespace UniVRM10 { switch (Preset) { - case VrmLib.ExpressionPreset.Blink: - case VrmLib.ExpressionPreset.BlinkLeft: - case VrmLib.ExpressionPreset.BlinkRight: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blink: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blinkLeft: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blinkRight: return true; } return false; @@ -54,10 +54,10 @@ namespace UniVRM10 { switch (Preset) { - case VrmLib.ExpressionPreset.LookUp: - case VrmLib.ExpressionPreset.LookDown: - case VrmLib.ExpressionPreset.LookLeft: - case VrmLib.ExpressionPreset.LookRight: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookUp: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookDown: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookLeft: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookRight: return true; } return false; @@ -70,11 +70,11 @@ namespace UniVRM10 { switch (Preset) { - case VrmLib.ExpressionPreset.Aa: - case VrmLib.ExpressionPreset.Ih: - case VrmLib.ExpressionPreset.Ou: - case VrmLib.ExpressionPreset.Ee: - case VrmLib.ExpressionPreset.Oh: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.aa: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ih: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ou: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ee: + case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.oh: return true; } return false; @@ -83,11 +83,11 @@ namespace UniVRM10 public bool IsProcedual => IsBlink || IsLookAt || IsMouth; - public ExpressionKey(VrmLib.ExpressionPreset preset, string customName = null) + public ExpressionKey(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset preset, string customName = null) { Preset = preset; - if (Preset != VrmLib.ExpressionPreset.Custom) + if (Preset != UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.custom) { if (PresetNameDictionary.ContainsKey((Preset))) { @@ -103,7 +103,7 @@ namespace UniVRM10 { if (string.IsNullOrEmpty(customName)) { - throw new ArgumentException("name is required for VrmLib.ExpressionPreset.Custom"); + throw new ArgumentException("name is required for UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.Custom"); } _id = $"{UnknownPresetPrefix}{customName}"; @@ -113,10 +113,10 @@ namespace UniVRM10 public static ExpressionKey CreateCustom(String key) { - return new ExpressionKey(VrmLib.ExpressionPreset.Custom, key); + return new ExpressionKey(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.custom, key); } - public static ExpressionKey CreateFromPreset(VrmLib.ExpressionPreset preset) + public static ExpressionKey CreateFromPreset(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset preset) { return new ExpressionKey(preset); } diff --git a/Assets/VRM10/Runtime/Components/Expression/MaterialColorBinding.cs b/Assets/VRM10/Runtime/Components/Expression/MaterialColorBinding.cs index 896d78c26..2fc12cc01 100644 --- a/Assets/VRM10/Runtime/Components/Expression/MaterialColorBinding.cs +++ b/Assets/VRM10/Runtime/Components/Expression/MaterialColorBinding.cs @@ -7,7 +7,7 @@ namespace UniVRM10 public struct MaterialColorBinding : IEquatable { public String MaterialName; - public VrmLib.MaterialBindType BindType; + public UniGLTF.Extensions.VRMC_vrm.MaterialColorType BindType; public Vector4 TargetValue; public bool Equals(MaterialColorBinding other) diff --git a/Assets/VRM10/Runtime/Components/Expression/MaterialValueBindingMerger.cs b/Assets/VRM10/Runtime/Components/Expression/MaterialValueBindingMerger.cs index 3a507492e..ad0384996 100644 --- a/Assets/VRM10/Runtime/Components/Expression/MaterialValueBindingMerger.cs +++ b/Assets/VRM10/Runtime/Components/Expression/MaterialValueBindingMerger.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using UniGLTF.Extensions.VRMC_vrm; using UnityEngine; namespace UniVRM10 @@ -9,6 +10,40 @@ namespace UniVRM10 /// internal sealed class MaterialValueBindingMerger { + public const string UV_PROPERTY = "_MainTex_ST"; + public const string COLOR_PROPERTY = "_Color"; + public const string EMISSION_COLOR_PROPERTY = "_EmissionColor"; + public const string RIM_COLOR_PROPERTY = "_RimColor"; + public const string OUTLINE_COLOR_PROPERTY = "_OutlineColor"; + public const string SHADE_COLOR_PROPERTY = "_ShadeColor"; + + public static string GetProperty(MaterialColorType bindType) + { + switch (bindType) + { + // case MaterialBindType.UvOffset: + // case MaterialBindType.UvScale: + // return UV_PROPERTY; + + case MaterialColorType.color: + return COLOR_PROPERTY; + + case MaterialColorType.emissionColor: + return EMISSION_COLOR_PROPERTY; + + case MaterialColorType.shadeColor: + return SHADE_COLOR_PROPERTY; + + case MaterialColorType.rimColor: + return RIM_COLOR_PROPERTY; + + case MaterialColorType.outlineColor: + return OUTLINE_COLOR_PROPERTY; + } + + throw new NotImplementedException(); + } + #region MaterialMap /// /// MaterialValueBinding の対象になるマテリアルの情報を記録する @@ -44,7 +79,7 @@ namespace UniVRM10 item = new PreviewMaterialItem(material); m_materialMap.Add(binding.MaterialName, item); } - var propName = VrmLib.MaterialBindTypeExtensions.GetProperty(binding.BindType); + var propName = GetProperty(binding.BindType); item.PropMap.Add(binding.BindType, new PropItem { Name = propName, @@ -179,7 +214,7 @@ namespace UniVRM10 return new MaterialTarget { MaterialName = binding.MaterialName, - ValueName = VrmLib.MaterialBindTypeExtensions.GetProperty(binding.BindType), + ValueName = GetProperty(binding.BindType), }; } } diff --git a/Assets/VRM10/Runtime/Components/Expression/PreviewMaterialItem.cs b/Assets/VRM10/Runtime/Components/Expression/PreviewMaterialItem.cs index 52944f3f0..20af729b4 100644 --- a/Assets/VRM10/Runtime/Components/Expression/PreviewMaterialItem.cs +++ b/Assets/VRM10/Runtime/Components/Expression/PreviewMaterialItem.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using UnityEngine; +using UniGLTF.Extensions.VRMC_vrm; #if UNITY_EDITOR using UnityEditor; #endif @@ -57,7 +58,7 @@ namespace UniVRM10 Material = material; } - public Dictionary PropMap = new Dictionary(); + public Dictionary PropMap = new Dictionary(); public string[] PropNames { @@ -74,6 +75,35 @@ namespace UniVRM10 } #if UNITY_EDITOR + public const string UV_PROPERTY = "_MainTex_ST"; + public const string COLOR_PROPERTY = "_Color"; + public const string EMISSION_COLOR_PROPERTY = "_EmissionColor"; + public const string RIM_COLOR_PROPERTY = "_RimColor"; + public const string OUTLINE_COLOR_PROPERTY = "_OutlineColor"; + public const string SHADE_COLOR_PROPERTY = "_ShadeColor"; + public static MaterialColorType GetBindType(string property) + { + switch (property) + { + case COLOR_PROPERTY: + return MaterialColorType.color; + + case EMISSION_COLOR_PROPERTY: + return MaterialColorType.emissionColor; + + case RIM_COLOR_PROPERTY: + return MaterialColorType.rimColor; + + case SHADE_COLOR_PROPERTY: + return MaterialColorType.shadeColor; + + case OUTLINE_COLOR_PROPERTY: + return MaterialColorType.outlineColor; + } + + throw new NotImplementedException(); + } + public static PreviewMaterialItem CreateForPreview(Material material) { var item = new PreviewMaterialItem(material); @@ -89,7 +119,7 @@ namespace UniVRM10 case ShaderUtil.ShaderPropertyType.Color: // 色 { - var bindType = VrmLib.MaterialBindTypeExtensions.GetBindType(name); + var bindType = GetBindType(name); item.PropMap.Add(bindType, new PropItem { Name = name, diff --git a/Assets/VRM10/Runtime/Components/Expression/VRM10Expression.cs b/Assets/VRM10/Runtime/Components/Expression/VRM10Expression.cs index a1a8a835d..a49eda8cd 100644 --- a/Assets/VRM10/Runtime/Components/Expression/VRM10Expression.cs +++ b/Assets/VRM10/Runtime/Components/Expression/VRM10Expression.cs @@ -53,7 +53,7 @@ namespace UniVRM10 /// ExpressionPreset を識別する。 Unknown の場合は、 ExpressionName で識別する /// [SerializeField] - public VrmLib.ExpressionPreset Preset; + public UniGLTF.Extensions.VRMC_vrm.ExpressionPreset Preset; /// /// 対象メッシュの Expression を操作する @@ -83,19 +83,19 @@ namespace UniVRM10 /// この Expression と Blink(Blink, BlinkLeft, BlinkRight) が同時に有効な場合、Blink の Weight を 0 にする /// [SerializeField] - public VrmLib.ExpressionOverrideType OverrideBlink; + public UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType OverrideBlink; /// /// この Expression と LookAt(LookUp, LookDown, LookLeft, LookRight) が同時に有効な場合、LookAt の Weight を 0 にする /// [SerializeField] - public VrmLib.ExpressionOverrideType OverrideLookAt; + public UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType OverrideLookAt; /// /// この Expression と Mouth(Aa, Ih, Ou, Ee, Oh) が同時に有効な場合、Mouth の Weight を 0 にする /// [SerializeField] - public VrmLib.ExpressionOverrideType OverrideMouth; + public UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType OverrideMouth; void Reset() { @@ -104,7 +104,7 @@ namespace UniVRM10 void OnValidate() { - if (Preset == VrmLib.ExpressionPreset.Custom) + if (Preset == UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.custom) { if (string.IsNullOrEmpty(ExpressionName)) { diff --git a/Assets/VRM10/Runtime/Components/Expression/VRM10ExpressionAvatar.cs b/Assets/VRM10/Runtime/Components/Expression/VRM10ExpressionAvatar.cs index 98e5f2098..61dc328ca 100644 --- a/Assets/VRM10/Runtime/Components/Expression/VRM10ExpressionAvatar.cs +++ b/Assets/VRM10/Runtime/Components/Expression/VRM10ExpressionAvatar.cs @@ -13,6 +13,8 @@ namespace UniVRM10 [CreateAssetMenu(menuName = "VRM10/ExpressionAvatar")] public sealed class VRM10ExpressionAvatar : ScriptableObject { + public const string ExtractKey = ".ExpressionAvatar"; + [SerializeField] public List Clips = new List(); @@ -79,15 +81,15 @@ namespace UniVRM10 /// public void CreateDefaultPreset() { - foreach (var preset in ((VrmLib.ExpressionPreset[])Enum.GetValues(typeof(VrmLib.ExpressionPreset))) - .Where(x => x != VrmLib.ExpressionPreset.Custom) + foreach (var preset in ((UniGLTF.Extensions.VRMC_vrm.ExpressionPreset[])Enum.GetValues(typeof(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset))) + .Where(x => x != UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.custom) ) { CreateDefaultPreset(preset); } } - void CreateDefaultPreset(VrmLib.ExpressionPreset preset) + void CreateDefaultPreset(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset preset) { var clip = GetClip(new ExpressionKey(preset)); if (clip != null) return; diff --git a/Assets/VRM10/Runtime/Components/FirstPerson/RendererFirstPersonFlags.cs b/Assets/VRM10/Runtime/Components/FirstPerson/RendererFirstPersonFlags.cs index 7674e2a09..62d120eac 100644 --- a/Assets/VRM10/Runtime/Components/FirstPerson/RendererFirstPersonFlags.cs +++ b/Assets/VRM10/Runtime/Components/FirstPerson/RendererFirstPersonFlags.cs @@ -7,7 +7,7 @@ namespace UniVRM10 public struct RendererFirstPersonFlags { public Renderer Renderer; - public VrmLib.FirstPersonMeshType FirstPersonFlag; + public UniGLTF.Extensions.VRMC_vrm.FirstPersonType FirstPersonFlag; public Mesh SharedMesh { get diff --git a/Assets/VRM10/Runtime/Components/LookAt/CurveMapper.cs b/Assets/VRM10/Runtime/Components/LookAt/CurveMapper.cs index 60fa404fb..55dcba9ff 100644 --- a/Assets/VRM10/Runtime/Components/LookAt/CurveMapper.cs +++ b/Assets/VRM10/Runtime/Components/LookAt/CurveMapper.cs @@ -31,20 +31,6 @@ namespace UniVRM10 } } - public void Apply(VrmLib.LookAtRangeMap map) - { - CurveXRangeDegree = map.InputMaxValue; - CurveYRangeDegree = map.OutputScaling; - } - - IEnumerable ToKeys(float[] values) - { - for (int i = 0; i < values.Length; i += 4) - { - yield return new Keyframe(values[i], values[i + 1], values[i + 2], values[i + 3]); - } - } - public float Map(float src) { if (src < 0) diff --git a/Assets/VRM10/Runtime/Components/LookAt/LookAtEyeDirectionApplicableToExpression.cs b/Assets/VRM10/Runtime/Components/LookAt/LookAtEyeDirectionApplicableToExpression.cs index d6b27be14..8b46d9955 100644 --- a/Assets/VRM10/Runtime/Components/LookAt/LookAtEyeDirectionApplicableToExpression.cs +++ b/Assets/VRM10/Runtime/Components/LookAt/LookAtEyeDirectionApplicableToExpression.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; +using UniGLTF.Extensions.VRMC_vrm; using UnityEngine; -using VrmLib; namespace UniVRM10 { @@ -10,12 +10,12 @@ namespace UniVRM10 private readonly CurveMapper _horizontalInner; private readonly CurveMapper _verticalDown; private readonly CurveMapper _verticalUp; - - private readonly ExpressionKey _lookRightKey = ExpressionKey.CreateFromPreset(ExpressionPreset.LookRight); - private readonly ExpressionKey _lookLeftKey = ExpressionKey.CreateFromPreset(ExpressionPreset.LookLeft); - private readonly ExpressionKey _lookUpKey = ExpressionKey.CreateFromPreset(ExpressionPreset.LookUp); - private readonly ExpressionKey _lookDownKey = ExpressionKey.CreateFromPreset(ExpressionPreset.LookDown); - + + private readonly ExpressionKey _lookRightKey = ExpressionKey.CreateFromPreset(ExpressionPreset.lookRight); + private readonly ExpressionKey _lookLeftKey = ExpressionKey.CreateFromPreset(ExpressionPreset.lookLeft); + private readonly ExpressionKey _lookUpKey = ExpressionKey.CreateFromPreset(ExpressionPreset.lookUp); + private readonly ExpressionKey _lookDownKey = ExpressionKey.CreateFromPreset(ExpressionPreset.lookDown); + public LookAtEyeDirectionApplicableToExpression( CurveMapper horizontalOuter, CurveMapper horizontalInner, CurveMapper verticalDown, CurveMapper verticalUp) { @@ -29,7 +29,7 @@ namespace UniVRM10 { var yaw = eyeDirection.LeftYaw; var pitch = eyeDirection.LeftPitch; - + if (yaw < 0) { // Left diff --git a/Assets/VRM10/Runtime/Components/Meta/VRM10MetaObject.cs b/Assets/VRM10/Runtime/Components/Meta/VRM10MetaObject.cs index d395f1e07..8851ccc26 100644 --- a/Assets/VRM10/Runtime/Components/Meta/VRM10MetaObject.cs +++ b/Assets/VRM10/Runtime/Components/Meta/VRM10MetaObject.cs @@ -10,6 +10,8 @@ namespace UniVRM10 [CreateAssetMenu(menuName = "VRM10/MetaObject")] public class VRM10MetaObject : ScriptableObject { + public const string ExtractKey = ".Meta"; + [SerializeField] public string ExporterVersion; @@ -24,13 +26,13 @@ namespace UniVRM10 public string CopyrightInformation; [SerializeField] - public string[] Authors; + public List Authors = new List(); [SerializeField] public string ContactInformation; [SerializeField] - public string Reference; + public List References = new List(); [SerializeField] public Texture2D Thumbnail; @@ -38,7 +40,7 @@ namespace UniVRM10 #region AvatarPermission [SerializeField, Tooltip("A person who can perform with this avatar")] - public VrmLib.AvatarUsageType AllowedUser; + public UniGLTF.Extensions.VRMC_vrm.AvatarPermissionType AllowedUser; [SerializeField, Tooltip("Violent acts using this avatar")] public bool ViolentUsage; @@ -47,7 +49,7 @@ namespace UniVRM10 public bool SexualUsage; [SerializeField, Tooltip("For commercial use")] - public VrmLib.CommercialUsageType CommercialUsage; + public UniGLTF.Extensions.VRMC_vrm.CommercialUsageType CommercialUsage; [SerializeField] public bool GameUsage; @@ -61,13 +63,13 @@ namespace UniVRM10 #region Distribution License [SerializeField] - public VrmLib.CreditNotationType CreditNotation; + public UniGLTF.Extensions.VRMC_vrm.CreditNotationType CreditNotation; [SerializeField] public bool Redistribution; [SerializeField] - public VrmLib.ModificationLicenseType ModificationLicense; + public UniGLTF.Extensions.VRMC_vrm.ModificationType ModificationLicense; [SerializeField] public string OtherLicenseUrl; @@ -80,7 +82,7 @@ namespace UniVRM10 yield return Validation.Error("Require Name. "); } - if (Authors == null || Authors.Length == 0) + if (Authors == null || Authors.Count == 0) { yield return Validation.Error("Require at leaset one Author."); } @@ -99,14 +101,14 @@ namespace UniVRM10 dst.CopyrightInformation = CopyrightInformation; if (Authors != null) { - dst.Authors = Authors.Select(x => x).ToArray(); + dst.Authors = Authors.Select(x => x).ToList(); } else { - dst.Authors = new string[] { }; + dst.Authors = new List(); } dst.ContactInformation = ContactInformation; - dst.Reference = Reference; + dst.References = References; dst.Thumbnail = Thumbnail; dst.AllowedUser = AllowedUser; dst.ViolentUsage = ViolentUsage; diff --git a/Assets/VRM10/Runtime/Components/SpringBone/VRM10SpringBone.cs b/Assets/VRM10/Runtime/Components/SpringBone/VRM10SpringBone.cs index 6b57c62c6..ee75cabbe 100644 --- a/Assets/VRM10/Runtime/Components/SpringBone/VRM10SpringBone.cs +++ b/Assets/VRM10/Runtime/Components/SpringBone/VRM10SpringBone.cs @@ -13,7 +13,7 @@ namespace UniVRM10 public class VRM10SpringBone { [SerializeField] - public string m_comment; + public string Comment; [SerializeField] public List Joints = new List(); diff --git a/Assets/VRM10/Runtime/Components/VRM10Controller.cs b/Assets/VRM10/Runtime/Components/VRM10Controller.cs index 1a5dd1781..08fdaa697 100644 --- a/Assets/VRM10/Runtime/Components/VRM10Controller.cs +++ b/Assets/VRM10/Runtime/Components/VRM10Controller.cs @@ -47,27 +47,15 @@ namespace UniVRM10 [SerializeField] public VRM10SpringBoneManager SpringBone = new VRM10SpringBoneManager(); - [SerializeField] - public ModelAsset ModelAsset; - void OnDestroy() { if (Expression != null) { Expression.Restore(); } - - if (ModelAsset != null) - { -#if UNITY_EDITOR - ModelAsset.DisposeEditor(); -#else - ModelAsset.Dispose(); -#endif - } } - VRMConstraint[] m_constraints; + VRM10Constraint[] m_constraints; Transform m_head; public Transform Head @@ -103,7 +91,7 @@ namespace UniVRM10 { var animator = GetComponent(); if (animator == null) return; - + m_head = animator.GetBoneTransform(HumanBodyBones.Head); LookAt.Setup(animator, m_head); Expression.Setup(transform, LookAt, LookAt.EyeDirectionApplicable); @@ -125,7 +113,7 @@ namespace UniVRM10 // if (m_constraints == null) { - m_constraints = GetComponentsInChildren(); + m_constraints = GetComponentsInChildren(); } foreach (var constraint in m_constraints) { @@ -152,7 +140,7 @@ namespace UniVRM10 { Setup(); } - + private void Update() { if (Controller.UpdateType == VRM10ControllerImpl.UpdateTypes.Update) diff --git a/Assets/VRM10/Runtime/Components/VRM10ControllerExpression.cs b/Assets/VRM10/Runtime/Components/VRM10ControllerExpression.cs index c05bd0909..c1254b5f5 100644 --- a/Assets/VRM10/Runtime/Components/VRM10ControllerExpression.cs +++ b/Assets/VRM10/Runtime/Components/VRM10ControllerExpression.cs @@ -10,7 +10,7 @@ namespace UniVRM10 public sealed class VRM10ControllerExpression { public static IExpressionValidatorFactory ExpressionValidatorFactory = new DefaultExpressionValidator.Factory(); - + [SerializeField] public VRM10ExpressionAvatar ExpressionAvatar; @@ -30,17 +30,19 @@ namespace UniVRM10 public float BlinkOverrideRate { get; private set; } public float LookAtOverrideRate { get; private set; } public float MouthOverrideRate { get; private set; } - + internal void Setup(Transform transform, ILookAtEyeDirectionProvider eyeDirectionProvider, ILookAtEyeDirectionApplicable eyeDirectionApplicable) { if (ExpressionAvatar == null) { - Debug.LogError($"{nameof(VRM10ControllerExpression)}.{nameof(ExpressionAvatar)} is null."); +#if VRM_DEVELOP + Debug.LogWarning($"{nameof(VRM10ControllerExpression)}.{nameof(ExpressionAvatar)} is null."); +#endif return; } - + Restore(); - + _merger = new ExpressionMerger(ExpressionAvatar.Clips, transform); _keys = ExpressionAvatar.Clips.Select(ExpressionKey.CreateFromClip).ToList(); var oldInputWeights = _inputWeights; @@ -55,12 +57,12 @@ namespace UniVRM10 _eyeDirectionProvider = eyeDirectionProvider; _eyeDirectionApplicable = eyeDirectionApplicable; } - + internal void Restore() { _merger?.RestoreMaterialInitialValues(); _merger = null; - + _eyeDirectionApplicable?.Restore(); _eyeDirectionApplicable = null; } @@ -119,18 +121,18 @@ namespace UniVRM10 { // 1. Get eye direction from provider. _inputEyeDirection = _eyeDirectionProvider?.EyeDirection ?? default; - + // 2. Validate user input, and Output as actual weights. _validator.Validate(_inputWeights, _actualWeights, _inputEyeDirection, out _actualEyeDirection, out var blink, out var lookAt, out var mouth); - + // 3. Set eye direction expression weights or any other side-effects (ex. eye bone). _eyeDirectionApplicable?.Apply(_actualEyeDirection, _actualWeights); // 4. Set actual weights to raw blendshapes. _merger.SetValues(_actualWeights); - + BlinkOverrideRate = blink; LookAtOverrideRate = lookAt; MouthOverrideRate = mouth; diff --git a/Assets/VRM10/Runtime/Components/VRM10ControllerFirstPerson.cs b/Assets/VRM10/Runtime/Components/VRM10ControllerFirstPerson.cs index a4b38b189..780f049c4 100644 --- a/Assets/VRM10/Runtime/Components/VRM10ControllerFirstPerson.cs +++ b/Assets/VRM10/Runtime/Components/VRM10ControllerFirstPerson.cs @@ -92,7 +92,7 @@ namespace UniVRM10 { switch (x.FirstPersonFlag) { - case VrmLib.FirstPersonMeshType.Auto: + case UniGLTF.Extensions.VRMC_vrm.FirstPersonType.auto: { if (x.Renderer is SkinnedMeshRenderer smr) { @@ -131,17 +131,17 @@ namespace UniVRM10 } break; - case VrmLib.FirstPersonMeshType.FirstPersonOnly: + case UniGLTF.Extensions.VRMC_vrm.FirstPersonType.firstPersonOnly: // 1人称のカメラでだけ描画されるようにする x.Renderer.gameObject.layer = FIRSTPERSON_ONLY_LAYER; break; - case VrmLib.FirstPersonMeshType.ThirdPersonOnly: + case UniGLTF.Extensions.VRMC_vrm.FirstPersonType.thirdPersonOnly: // 3人称のカメラでだけ描画されるようにする x.Renderer.gameObject.layer = THIRDPERSON_ONLY_LAYER; break; - case VrmLib.FirstPersonMeshType.Both: + case UniGLTF.Extensions.VRMC_vrm.FirstPersonType.both: // 特に何もしない。すべてのカメラで描画される break; } diff --git a/Assets/VRM10/Runtime/Components/VRM10ControllerLookAt.cs b/Assets/VRM10/Runtime/Components/VRM10ControllerLookAt.cs index dff543430..8f4a67862 100644 --- a/Assets/VRM10/Runtime/Components/VRM10ControllerLookAt.cs +++ b/Assets/VRM10/Runtime/Components/VRM10ControllerLookAt.cs @@ -1,7 +1,6 @@ using System; -using System.Collections.Generic; using UnityEngine; -using VrmLib; +using UniGLTF.Extensions.VRMC_vrm; #if UNITY_EDITOR using UnityEditor; #endif @@ -11,14 +10,6 @@ namespace UniVRM10 [Serializable] public class VRM10ControllerLookAt : ILookAtEyeDirectionProvider { - public enum LookAtTypes - { - // Gaze control by bone (leftEye, rightEye) - Bone, - // Gaze control by blend shape (lookUp, lookDown, lookLeft, lookRight) - Expression, - } - public enum LookAtTargetTypes { CalcYawPitchToGaze, @@ -32,7 +23,7 @@ namespace UniVRM10 public Vector3 OffsetFromHead = new Vector3(0, 0.06f, 0); [SerializeField] - public LookAtTypes LookAtType; + public LookAtType LookAtType; [SerializeField] public CurveMapper HorizontalOuter = new CurveMapper(90.0f, 10.0f); @@ -55,7 +46,7 @@ namespace UniVRM10 private ILookAtEyeDirectionApplicable _eyeDirectionApplicable; internal ILookAtEyeDirectionApplicable EyeDirectionApplicable => _eyeDirectionApplicable; - + public LookAtEyeDirection EyeDirection { get; private set; } #region LookAtTargetTypes.CalcYawPitchToGaze @@ -150,10 +141,10 @@ namespace UniVRM10 } switch (LookAtType) { - case LookAtTypes.Bone: + case LookAtType.bone: _eyeDirectionApplicable = new LookAtEyeDirectionApplicableToBone(m_leftEye, m_rightEye, HorizontalOuter, HorizontalInner, VerticalDown, VerticalUp); break; - case LookAtTypes.Expression: + case LookAtType.expression: _eyeDirectionApplicable = new LookAtEyeDirectionApplicableToExpression(HorizontalOuter, HorizontalInner, VerticalDown, VerticalUp); break; default: diff --git a/Assets/VRM10/Runtime/IO/ArrayBytesBuffer.cs b/Assets/VRM10/Runtime/IO/ArrayBytesBuffer.cs deleted file mode 100644 index fc1dd7de6..000000000 --- a/Assets/VRM10/Runtime/IO/ArrayBytesBuffer.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using VrmLib; - -namespace UniVRM10 -{ - /// - /// for exporter - /// - public class ArrayByteBuffer10 - { - public ArraySegment Bytes - { - get - { - if (m_bytes == null) - { - return new ArraySegment(); - } - - return new ArraySegment(m_bytes, 0, m_used); - } - } - - Byte[] m_bytes; - int m_used = 0; - - public ArrayByteBuffer10(Byte[] bytes = null) - { - m_bytes = bytes ?? (new byte[] { }); - } - - public ArrayByteBuffer10(Byte[] bytes, int used) - { - m_bytes = bytes ?? (new byte[] { }); - m_used = used; - } - - - public void ExtendCapacity(int byteLength) - { - var backup = m_bytes; - m_bytes = new byte[backup.Length + byteLength]; - backup.CopyTo(m_bytes, backup.Length); - } - - public void Extend(ArraySegment array, int stride, out int offset, out int length) - { - var tmp = m_bytes; - // alignment - var padding = m_used % stride == 0 ? 0 : stride - m_used % stride; - - if (m_bytes == null || m_used + padding + array.Count > m_bytes.Length) - { - // recreate buffer - var newSize = Math.Max(m_used + padding + array.Count, m_bytes.Length * 2); - m_bytes = new Byte[newSize]; - if (m_used > 0) - { - Buffer.BlockCopy(tmp, 0, m_bytes, 0, m_used); - } - } - if (m_used + padding + array.Count > m_bytes.Length) - { - throw new ArgumentOutOfRangeException(); - } - - Buffer.BlockCopy(array.Array, array.Offset, m_bytes, m_used + padding, array.Count); - - length = array.Count; - offset = m_used + padding; - - - // var result = new GltfBufferView - // { - // buffer = 0, - // byteLength = array.Length, - // byteOffset = m_used + padding, - // target = target, - // }; - // if (target == GltfBufferTargetType.ARRAY_BUFFER) - // { - // result.byteStride = stride; - // } - - m_used = m_used + padding + array.Count; - // return result; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/Runtime/IO/ArrayBytesBuffer.cs.meta b/Assets/VRM10/Runtime/IO/ArrayBytesBuffer.cs.meta deleted file mode 100644 index 9650705da..000000000 --- a/Assets/VRM10/Runtime/IO/ArrayBytesBuffer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c700d6d6fbb38fa4d9662213c58d5725 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/ArrayExtensions.cs b/Assets/VRM10/Runtime/IO/ArrayExtensions.cs index 73b0d250d..b6a777d0d 100644 --- a/Assets/VRM10/Runtime/IO/ArrayExtensions.cs +++ b/Assets/VRM10/Runtime/IO/ArrayExtensions.cs @@ -1,23 +1,9 @@ -using System; -using System.Collections.Generic; using System.Numerics; -using VrmLib; - namespace UniVRM10 { public static class ArrayExtensions { - public static Vector2 ToVector2(this float[] src, Vector2 defaultValue = default) - { - if (src.Length != 2) return defaultValue; - - var v = new Vector2(); - v.X = src[0]; - v.Y = src[1]; - return v; - } - public static Vector3 ToVector3(this float[] src, Vector3 defaultValue = default) { if (src.Length != 3) return defaultValue; @@ -36,74 +22,5 @@ namespace UniVRM10 var v = new Quaternion(src[0], src[1], src[2], src[3]); return v; } - - public static TextureInfo GetTexture(this int? nullable, List textures) - { - if (!nullable.TryGetValidIndex(textures.Count, out int index)) - { - return null; - } - var texture = textures[index]; - return new TextureInfo(texture); - } - - public static TextureInfo GetTexture(this int index, List textures) - { - if (index < 0 || index >= textures.Count) - { - return null; - } - var texture = textures[index]; - return new TextureInfo(texture); - } - - public static int? ToIndex(this TextureInfo texture, List textures) - { - if (texture == null) - { - return default; - } - return textures.IndexOfThrow(texture.Texture); - } - - public static Vector4 ToVector4(this float[] src, Vector4 defaultValue = default) - { - switch (src.Length) - { - case 4: - return new Vector4(src[0], src[1], src[2], src[3]); - case 3: - return new Vector4(src[0], src[1], src[2], 1.0f); - case 0: - return defaultValue; - default: - throw new Exception(); - } - } - - public static LinearColor ToLinearColor(this float[] src, Vector4 defaultValue) - { - switch (src.Length) - { - case 4: - return LinearColor.FromLiner(src[0], src[1], src[2], src[3]); - case 3: - return LinearColor.FromLiner(src[0], src[1], src[2], 1.0f); - case 0: - return LinearColor.FromLiner(defaultValue); - default: - throw new Exception(); - } - } - - public static float[] ToFloat2(this System.Numerics.Vector2 value) - { - return new float[] { value.X, value.Y }; - } - - public static float[] ToFloat4(this System.Numerics.Vector4 value) - { - return new float[] { value.X, value.Y, value.Z, value.W }; - } } } diff --git a/Assets/VRM10/Runtime/IO/BufferAccessorAdapter.cs b/Assets/VRM10/Runtime/IO/BufferAccessorAdapter.cs index 39f0ae7a1..719c5b197 100644 --- a/Assets/VRM10/Runtime/IO/BufferAccessorAdapter.cs +++ b/Assets/VRM10/Runtime/IO/BufferAccessorAdapter.cs @@ -39,7 +39,7 @@ namespace UniVRM10 count = self.Count; } var slice = self.Bytes.Slice(offset * stride, count * stride); - return storage.AppendToBuffer(bufferIndex, slice, stride); + return storage.AppendToBuffer(bufferIndex, slice); } static glTFAccessor CreateGltfAccessor(this VrmLib.BufferAccessor self, @@ -116,8 +116,8 @@ namespace UniVRM10 sparseValueSpan[i] = value; } - var sparseIndexView = storage.AppendToBuffer(bufferIndex, sparseIndexBin, 4); - var sparseValueView = storage.AppendToBuffer(bufferIndex, sparseValueBin, 12); + var sparseIndexView = storage.AppendToBuffer(bufferIndex, sparseIndexBin); + var sparseValueView = storage.AppendToBuffer(bufferIndex, sparseValueBin); var accessorIndex = storage.Gltf.accessors.Count; var accessor = new glTFAccessor diff --git a/Assets/VRM10/Runtime/IO/ComponentBuilder.cs b/Assets/VRM10/Runtime/IO/ComponentBuilder.cs new file mode 100644 index 000000000..eace97c9e --- /dev/null +++ b/Assets/VRM10/Runtime/IO/ComponentBuilder.cs @@ -0,0 +1,29 @@ +using System; +using UnityEngine; +using System.Linq; +using System.Collections.Generic; + +namespace UniVRM10 +{ + public static class ComponentBuilder + { + #region Util + static (Transform, Mesh) GetTransformAndMesh(Transform t) + { + var skinnedMeshRenderer = t.GetComponent(); + if (skinnedMeshRenderer != null) + { + return (t, skinnedMeshRenderer.sharedMesh); + } + + var filter = t.GetComponent(); + if (filter != null) + { + return (t, filter.sharedMesh); + } + + return default; + } + #endregion + } +} diff --git a/Assets/VRM10/Runtime/UnityBuilder/ComponentBuilder.cs.meta b/Assets/VRM10/Runtime/IO/ComponentBuilder.cs.meta similarity index 100% rename from Assets/VRM10/Runtime/UnityBuilder/ComponentBuilder.cs.meta rename to Assets/VRM10/Runtime/IO/ComponentBuilder.cs.meta diff --git a/Assets/VRM10/Runtime/UnityBuilder/DictionaryExtensions.cs b/Assets/VRM10/Runtime/IO/DictionaryExtensions.cs similarity index 100% rename from Assets/VRM10/Runtime/UnityBuilder/DictionaryExtensions.cs rename to Assets/VRM10/Runtime/IO/DictionaryExtensions.cs diff --git a/Assets/VRM10/Runtime/UnityBuilder/DictionaryExtensions.cs.meta b/Assets/VRM10/Runtime/IO/DictionaryExtensions.cs.meta similarity index 100% rename from Assets/VRM10/Runtime/UnityBuilder/DictionaryExtensions.cs.meta rename to Assets/VRM10/Runtime/IO/DictionaryExtensions.cs.meta diff --git a/Assets/VRM10/Runtime/IO/ExpressionExtensions.cs b/Assets/VRM10/Runtime/IO/ExpressionExtensions.cs new file mode 100644 index 000000000..939207832 --- /dev/null +++ b/Assets/VRM10/Runtime/IO/ExpressionExtensions.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using UniGLTF.Extensions.VRMC_vrm; +using UnityEngine; + +namespace UniVRM10 +{ + public static class ExpressionExtensions + { + /// + /// for SubAssetName + /// + /// + public static string ExtractName(this Expression expression) + { + ExpressionKey key = + (expression.Preset == ExpressionPreset.custom) + ? ExpressionKey.CreateCustom(expression.Name) + : ExpressionKey.CreateFromPreset(expression.Preset) + ; + return $"Expression.{key}"; + } + + public static UniVRM10.MorphTargetBinding Build10(this MorphTargetBind bind, GameObject root, RuntimeUnityBuilder.ModelMap loader, VrmLib.Model model) + { + var libNode = model.Nodes[bind.Node.Value]; + var node = loader.Nodes[libNode].transform; + var mesh = loader.Meshes[libNode.MeshGroup]; + var relativePath = node.RelativePathFrom(root.transform); + // VRM-1.0 では値域は [0-1.0f] + return new UniVRM10.MorphTargetBinding(relativePath, bind.Index.Value, bind.Weight.Value * 100.0f); + } + + public static UniVRM10.MaterialColorBinding? Build10(this MaterialColorBind bind, IReadOnlyList materials) + { + var value = new Vector4(bind.TargetValue[0], bind.TargetValue[1], bind.TargetValue[2], bind.TargetValue[3]); + var material = materials[bind.Material.Value].Asset; + + var binding = default(UniVRM10.MaterialColorBinding?); + if (material != null) + { + try + { + binding = new UniVRM10.MaterialColorBinding + { + MaterialName = material.name, // 名前で持つべき? + BindType = bind.Type, + TargetValue = value, + // BaseValue = material.GetColor(kv.Key), + }; + } + catch (Exception) + { + // do nothing + } + } + return binding; + } + + public static UniVRM10.MaterialUVBinding? Build10(this TextureTransformBind bind, IReadOnlyList materials) + { + var material = materials[bind.Material.Value].Asset; + + var binding = default(UniVRM10.MaterialUVBinding?); + if (material != null) + { + try + { + binding = new UniVRM10.MaterialUVBinding + { + MaterialName = material.name, // 名前で持つべき + Scaling = new Vector2(bind.Scaling[0], bind.Scaling[1]), + Offset = new Vector2(bind.Offset[0], bind.Offset[1]), + }; + } + catch (Exception) + { + // do nothing + } + } + return binding; + } + } +} diff --git a/Assets/VRM10/Runtime/IO/ExpressionExtensions.cs.meta b/Assets/VRM10/Runtime/IO/ExpressionExtensions.cs.meta new file mode 100644 index 000000000..7cb87e6f5 --- /dev/null +++ b/Assets/VRM10/Runtime/IO/ExpressionExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c93dae149b843ca46b028b4e4d845c89 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/ImageAdapter.cs b/Assets/VRM10/Runtime/IO/ImageAdapter.cs deleted file mode 100644 index f678237d9..000000000 --- a/Assets/VRM10/Runtime/IO/ImageAdapter.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using UniGLTF; - -namespace UniVRM10 -{ - public static class ImageAdapter - { - public static VrmLib.Image FromGltf(this glTFImage x, Vrm10Storage storage) - { - if (x.bufferView == -1) - { - // 外部参照? - throw new Exception(); - } - - var view = storage.Gltf.bufferViews[x.bufferView]; - - var buffer = storage.Gltf.buffers[view.buffer]; - - // テクスチャの用途を調べる - var usage = default(VrmLib.ImageUsage); - foreach (var material in storage.Gltf.materials) - { - var colorImage = GetColorImage(storage, material); - if (colorImage == x) - { - usage |= VrmLib.ImageUsage.Color; - } - - var normalImage = GetNormalImage(storage, material); - if (normalImage == x) - { - usage |= VrmLib.ImageUsage.Normal; - } - } - - var memory = storage.GetBufferBytes(buffer); - return new VrmLib.Image(x.name, - x.mimeType, - usage, - memory.Slice(view.byteOffset, view.byteLength)); - } - - static glTFImage GetTexture(Vrm10Storage storage, int index) - { - if (index < 0 || index >= storage.Gltf.textures.Count) - { - return null; - } - var texture = storage.Gltf.textures[index]; - if (texture.source < 0 || texture.source >= storage.Gltf.images.Count) - { - return null; - } - return storage.Gltf.images[texture.source]; - } - - static glTFImage GetColorImage(Vrm10Storage storage, glTFMaterial m) - { - if (m.pbrMetallicRoughness == null) - { - return null; - } - if (m.pbrMetallicRoughness.baseColorTexture == null) - { - return null; - } - if (!m.pbrMetallicRoughness.baseColorTexture.index.TryGetValidIndex(storage.TextureCount, out int index)) - { - return null; - } - return GetTexture(storage, index); - } - - static glTFImage GetNormalImage(Vrm10Storage storage, glTFMaterial m) - { - if (m.normalTexture == null) - { - return null; - } - if (!m.normalTexture.index.TryGetValidIndex(storage.TextureCount, out int index)) - { - return null; - } - return GetTexture(storage, index); - } - - public static glTFImage ToGltf(this VrmLib.Image src, Vrm10Storage storage) - { - var viewIndex = storage.AppendToBuffer(0, src.Bytes, 1); - var gltf = storage.Gltf; - return new glTFImage - { - name = src.Name, - mimeType = src.MimeType, - bufferView = viewIndex, - }; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/Runtime/IO/ImageAdapter.cs.meta b/Assets/VRM10/Runtime/IO/ImageAdapter.cs.meta deleted file mode 100644 index efc311140..000000000 --- a/Assets/VRM10/Runtime/IO/ImageAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d48a6bb715d0d024fa5af64bb63f695e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/MToonAdapter.cs b/Assets/VRM10/Runtime/IO/MToonAdapter.cs deleted file mode 100644 index 4d4f94e00..000000000 --- a/Assets/VRM10/Runtime/IO/MToonAdapter.cs +++ /dev/null @@ -1,263 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Numerics; -using VrmLib.MToon; -using VrmLib; -using UniGLTF; -using UniGLTF.Extensions.VRMC_materials_mtoon; -using UniJSON; - -namespace UniVRM10 -{ - public static class MToonAdapter - { - // for debug - static readonly Vector4 Nan = new Vector4(float.NaN, float.NaN, float.NaN, float.NaN); - - static RenderMode GetRenderMode(string alphaMode, bool isTransparentWithZWrite) - { - switch (alphaMode) - { - case "OPAQUE": return RenderMode.Opaque; - case "MASK": return RenderMode.Cutout; - case "BLEND": - { - if (isTransparentWithZWrite) - { - return RenderMode.TransparentWithZWrite; - } - else - { - return RenderMode.Transparent; - } - } - } - - throw new NotImplementedException(); - } - - public static MToonMaterial MToonFromGltf(glTFMaterial material, List textures, VRMC_materials_mtoon extension) - { - var mtoon = new MToonMaterial(material.name); - - var Meta = new MetaDefinition - { - Implementation = "Santarh/MToon", - }; - var Color = new ColorDefinition - { - LitColor = material.pbrMetallicRoughness.baseColorFactor.ToLinearColor(Nan), - LitMultiplyTexture = material.pbrMetallicRoughness.baseColorTexture?.index.GetTexture(textures), - ShadeColor = extension.ShadeFactor.ToLinearColor(Nan), - ShadeMultiplyTexture = extension.ShadeMultiplyTexture.GetTexture(textures), - CutoutThresholdValue = material.alphaCutoff, - }; - var Outline = new OutlineDefinition - { - OutlineColorMode = (VrmLib.MToon.OutlineColorMode)extension.OutlineColorMode, - OutlineColor = extension.OutlineFactor.ToLinearColor(Nan), - OutlineLightingMixValue = extension.OutlineLightingMixFactor.Value, - OutlineScaledMaxDistanceValue = extension.OutlineScaledMaxDistanceFactor.Value, - OutlineWidthMode = (VrmLib.MToon.OutlineWidthMode)extension.OutlineWidthMode, - OutlineWidthValue = extension.OutlineWidthFactor.Value, - OutlineWidthMultiplyTexture = extension.OutlineWidthMultiplyTexture.GetTexture(textures), - }; - var Emission = new EmissionDefinition - { - EmissionColor = material.emissiveFactor.ToLinearColor(Nan), - }; - if (material.emissiveTexture != null) - { - Emission.EmissionMultiplyTexture = material.emissiveTexture.index.GetTexture(textures); - } - - var Lighting = new LightingDefinition - { - LightingInfluence = new LightingInfluenceDefinition - { - GiIntensityValue = extension.GiIntensityFactor.Value, - LightColorAttenuationValue = extension.LightColorAttenuationFactor.Value, - }, - LitAndShadeMixing = new LitAndShadeMixingDefinition - { - ShadingShiftValue = extension.ShadingShiftFactor.Value, - ShadingToonyValue = extension.ShadingToonyFactor.Value, - }, - Normal = new NormalDefinition - { - }, - }; - if (material.normalTexture != null) - { - Lighting.Normal.NormalScaleValue = material.normalTexture.scale; - Lighting.Normal.NormalTexture = material.normalTexture.index.GetTexture(textures); - } - - var MatCap = new MatCapDefinition - { - AdditiveTexture = extension.AdditiveTexture.GetTexture(textures) - }; - var Rendering = new RenderingDefinition - { - CullMode = material.doubleSided ? CullMode.Off : CullMode.Back, - RenderMode = GetRenderMode(material.alphaMode, extension.TransparentWithZWrite.Value), - RenderQueueOffsetNumber = extension.RenderQueueOffsetNumber.Value, - }; - var Rim = new RimDefinition - { - RimColor = extension.RimFactor.ToLinearColor(Nan), - RimMultiplyTexture = extension.RimMultiplyTexture.GetTexture(textures), - RimLiftValue = extension.RimLiftFactor.Value, - RimFresnelPowerValue = extension.RimFresnelPowerFactor.Value, - RimLightingMixValue = extension.RimLightingMixFactor.Value, - }; - - var TextureOption = new TextureUvCoordsDefinition - { - UvAnimationMaskTexture = extension.UvAnimationMaskTexture.GetTexture(textures), - UvAnimationRotationSpeedValue = extension.UvAnimationRotationSpeedFactor.Value, - UvAnimationScrollXSpeedValue = extension.UvAnimationScrollXSpeedFactor.Value, - UvAnimationScrollYSpeedValue = extension.UvAnimationScrollYSpeedFactor.Value, - }; - - if (glTF_KHR_texture_transform.TryGet(material.pbrMetallicRoughness.baseColorTexture, out glTF_KHR_texture_transform t)) - { - TextureOption.MainTextureLeftBottomOriginOffset = t.offset.ToVector2(); - TextureOption.MainTextureLeftBottomOriginScale = t.scale.ToVector2(); - } - - mtoon.Definition = new MToonDefinition - { - Meta = Meta, - Color = Color, - Outline = Outline, - Emission = Emission, - Lighting = Lighting, - MatCap = MatCap, - Rendering = Rendering, - Rim = Rim, - TextureOption = TextureOption, - }; - - return mtoon; - } - - static (string, bool) GetRenderMode(RenderMode mode) - { - switch (mode) - { - case RenderMode.Opaque: return ("OPAQUE", false); - case RenderMode.Cutout: return ("MASK", false); - case RenderMode.Transparent: return ("BLEND", false); - case RenderMode.TransparentWithZWrite: return ("BLEND", true); - } - - throw new NotImplementedException(); - } - - public static glTFMaterial MToonToGltf(this MToonMaterial mtoon, List textures) - { - var material = mtoon.UnlitToGltf(textures); - - var dst = new VRMC_materials_mtoon(); - - // Color - material.pbrMetallicRoughness.baseColorFactor = mtoon.Definition.Color.LitColor.ToFloat4(); - if (mtoon.Definition.Color.LitMultiplyTexture != null) - { - material.pbrMetallicRoughness.baseColorTexture = new glTFMaterialBaseColorTextureInfo - { - index = mtoon.Definition.Color.LitMultiplyTexture.ToIndex(textures).Value - }; - } - dst.ShadeFactor = mtoon.Definition.Color.ShadeColor.ToFloat3(); - dst.ShadeMultiplyTexture = mtoon.Definition.Color.ShadeMultiplyTexture.ToIndex(textures); - material.alphaCutoff = mtoon.Definition.Color.CutoutThresholdValue; - - // Outline - dst.OutlineColorMode = (UniGLTF.Extensions.VRMC_materials_mtoon.OutlineColorMode)mtoon.Definition.Outline.OutlineColorMode; - dst.OutlineFactor = mtoon.Definition.Outline.OutlineColor.ToFloat3(); - dst.OutlineLightingMixFactor = mtoon.Definition.Outline.OutlineLightingMixValue; - dst.OutlineScaledMaxDistanceFactor = mtoon.Definition.Outline.OutlineScaledMaxDistanceValue; - dst.OutlineWidthMode = (UniGLTF.Extensions.VRMC_materials_mtoon.OutlineWidthMode)mtoon.Definition.Outline.OutlineWidthMode; - dst.OutlineWidthFactor = mtoon.Definition.Outline.OutlineWidthValue; - dst.OutlineWidthMultiplyTexture = mtoon.Definition.Outline.OutlineWidthMultiplyTexture.ToIndex(textures); - - // Emission - material.emissiveFactor = mtoon.Definition.Emission.EmissionColor.ToFloat3(); - if (mtoon.Definition.Emission.EmissionMultiplyTexture != null) - { - material.emissiveTexture = new glTFMaterialEmissiveTextureInfo - { - index = textures.IndexOfNullable(mtoon.Definition.Emission.EmissionMultiplyTexture.Texture).Value - }; - } - - // Light - dst.GiIntensityFactor = mtoon.Definition.Lighting.LightingInfluence.GiIntensityValue; - dst.LightColorAttenuationFactor = mtoon.Definition.Lighting.LightingInfluence.LightColorAttenuationValue; - dst.ShadingShiftFactor = mtoon.Definition.Lighting.LitAndShadeMixing.ShadingShiftValue; - dst.ShadingToonyFactor = mtoon.Definition.Lighting.LitAndShadeMixing.ShadingToonyValue; - if (mtoon.Definition.Lighting.Normal.NormalTexture != null) - { - material.normalTexture = new glTFMaterialNormalTextureInfo - { - index = textures.IndexOfNullable(mtoon.Definition.Lighting.Normal.NormalTexture.Texture).Value, - scale = mtoon.Definition.Lighting.Normal.NormalScaleValue - }; - } - - // matcap - dst.AdditiveTexture = mtoon.Definition.MatCap.AdditiveTexture.ToIndex(textures); - - // rendering - switch (mtoon.Definition.Rendering.CullMode) - { - case CullMode.Back: - material.doubleSided = false; - break; - - case CullMode.Off: - material.doubleSided = true; - break; - - case CullMode.Front: - // GLTF not support - material.doubleSided = false; - break; - - default: - throw new NotImplementedException(); - } - (material.alphaMode, dst.TransparentWithZWrite) = GetRenderMode(mtoon.Definition.Rendering.RenderMode); - dst.RenderQueueOffsetNumber = mtoon.Definition.Rendering.RenderQueueOffsetNumber; - - // rim - dst.RimFactor = mtoon.Definition.Rim.RimColor.ToFloat3(); - dst.RimMultiplyTexture = mtoon.Definition.Rim.RimMultiplyTexture.ToIndex(textures); - dst.RimLiftFactor = mtoon.Definition.Rim.RimLiftValue; - dst.RimFresnelPowerFactor = mtoon.Definition.Rim.RimFresnelPowerValue; - dst.RimLightingMixFactor = mtoon.Definition.Rim.RimLightingMixValue; - - // texture option - dst.UvAnimationMaskTexture = mtoon.Definition.TextureOption.UvAnimationMaskTexture.ToIndex(textures); - dst.UvAnimationRotationSpeedFactor = mtoon.Definition.TextureOption.UvAnimationRotationSpeedValue; - dst.UvAnimationScrollXSpeedFactor = mtoon.Definition.TextureOption.UvAnimationScrollXSpeedValue; - dst.UvAnimationScrollYSpeedFactor = mtoon.Definition.TextureOption.UvAnimationScrollYSpeedValue; - if (material.pbrMetallicRoughness.baseColorTexture != null) - { - var offset = mtoon.Definition.TextureOption.MainTextureLeftBottomOriginOffset; - var scale = mtoon.Definition.TextureOption.MainTextureLeftBottomOriginScale; - glTF_KHR_texture_transform.Serialize( - material.pbrMetallicRoughness.baseColorTexture, - (offset.X, offset.Y), - (scale.X, scale.Y) - ); - } - - UniGLTF.Extensions.VRMC_materials_mtoon.GltfSerializer.SerializeTo(ref material.extensions, dst); - - return material; - } - } -} diff --git a/Assets/VRM10/Runtime/IO/MToonAdapter.cs.meta b/Assets/VRM10/Runtime/IO/MToonAdapter.cs.meta deleted file mode 100644 index 363b4ce47..000000000 --- a/Assets/VRM10/Runtime/IO/MToonAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: dfbed4ddbad0e1941862133ed8219c4c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/MToonUtilsFromDefinition.cs b/Assets/VRM10/Runtime/IO/MToonUtilsFromDefinition.cs deleted file mode 100644 index 06cdb74c6..000000000 --- a/Assets/VRM10/Runtime/IO/MToonUtilsFromDefinition.cs +++ /dev/null @@ -1,312 +0,0 @@ -using Color = System.Numerics.Vector4; -using Material = UniGLTF.glTFMaterial; -using System.Collections.Generic; -using VrmLib; -using VrmLib.MToon; -using System; - -namespace UniVRM10 -{ - public static partial class Utils - { - public static void ToProtobuf(this LinearColor color, Action add, bool hasAlpha) - { - add(color.RGBA.X); - add(color.RGBA.Y); - add(color.RGBA.Z); - if (hasAlpha) - { - add(color.RGBA.W); - } - } - - // public static void SetMToonParametersToMaterial(Material material, MToonDefinition parameters, List textures) - // { - // var mtoon = material.Extensions.VRMCMaterialsMtoon; - - // { - // var meta = parameters.Meta; - // mtoon.Version = meta.VersionNumber.ToString(); - // } - // // TODO: - // // { - // // var rendering = parameters.Rendering; - // // ValidateBlendMode(material, rendering.RenderMode, isChangedByUser: true); - // // ValidateCullMode(material, rendering.CullMode); - // // ValidateRenderQueue(material, offset: rendering.RenderQueueOffsetNumber); - // // } - // { - // var color = parameters.Color; - - // // SetColor(material, MToonUtils.PropColor, color.LitColor); - // color.LitColor.ToProtobuf(mtoon.LitFactor.Add, true); - - // // SetTexture(material, MToonUtils.PropMainTex, color.LitMultiplyTexture, textures); - // mtoon.LitMultiplyTexture = textures.IndexOfNullable(color.LitMultiplyTexture.Texture); - - // // SetColor(material, MToonUtils.PropShadeColor, color.ShadeColor); - // color.ShadeColor.ToProtobuf(mtoon.ShadeFactor.Add, false); - - // // SetTexture(material, MToonUtils.PropShadeTexture, color.ShadeMultiplyTexture, textures); - // mtoon.ShadeMultiplyTexture = textures.IndexOfNullable(color.ShadeMultiplyTexture.Texture); - - // // SetValue(material, MToonUtils.PropCutoff, color.CutoutThresholdValue); - // mtoon.CutoutThresholdFactor = color.CutoutThresholdValue; - // } - // { - // var lighting = parameters.Lighting; - // { - // var prop = lighting.LitAndShadeMixing; - // // SetValue(material, MToonUtils.PropShadeShift, prop.ShadingShiftValue); - // mtoon.ShadingShiftFactor = prop.ShadingShiftValue; - - // // SetValue(material, MToonUtils.PropShadeToony, prop.ShadingToonyValue); - // mtoon.ShadingToonyFactor = prop.ShadingToonyValue; - // } - // { - // var prop = lighting.LightingInfluence; - // // SetValue(material, MToonUtils.PropLightColorAttenuation, prop.LightColorAttenuationValue); - // mtoon.LightColorAttenuationFactor = prop.LightColorAttenuationValue; - - // // SetValue(material, MToonUtils.PropIndirectLightIntensity, prop.GiIntensityValue); - // mtoon.GiIntensityFactor = prop.GiIntensityValue; - // } - // { - // var prop = lighting.Normal; - // // SetTexture(material, MToonUtils.PropBumpMap, prop.NormalTexture, textures); - // mtoon.NormalTexture = textures.IndexOfNullable(prop.NormalTexture.Texture); - - // // SetValue(material, MToonUtils.PropBumpScale, prop.NormalScaleValue); - // mtoon.NormalScaleFactor = prop.NormalScaleValue; - // } - // } - // { - // var emission = parameters.Emission; - // // SetColor(material, MToonUtils.PropEmissionColor, emission.EmissionColor); - // emission.EmissionColor.ToProtobuf(mtoon.EmissionFactor.Add, false); - - // // SetTexture(material, MToonUtils.PropEmissionMap, emission.EmissionMultiplyTexture, textures); - // mtoon.EmissionMultiplyTexture = textures.IndexOfNullable(emission.EmissionMultiplyTexture.Texture); - // } - // { - // var matcap = parameters.MatCap; - // // SetTexture(material, MToonUtils.PropSphereAdd, matcap.AdditiveTexture, textures); - // mtoon.AdditiveTexture = textures.IndexOfNullable(matcap.AdditiveTexture.Texture); - // } - // { - // var rim = parameters.Rim; - // // SetColor(material, MToonUtils.PropRimColor, rim.RimColor); - // rim.RimColor.ToProtobuf(mtoon.RimFactor.Add, false); - - // // SetTexture(material, MToonUtils.PropRimTexture, rim.RimMultiplyTexture, textures); - // mtoon.RimMultiplyTexture = textures.IndexOfNullable(rim.RimMultiplyTexture.Texture); - - // // SetValue(material, MToonUtils.PropRimLightingMix, rim.RimLightingMixValue); - // mtoon.RimLightingMixFactor = rim.RimLightingMixValue; - - // // SetValue(material, MToonUtils.PropRimFresnelPower, rim.RimFresnelPowerValue); - // mtoon.RimFresnelPowerFactor = rim.RimFresnelPowerValue; - - // // SetValue(material, MToonUtils.PropRimLift, rim.RimLiftValue); - // mtoon.RimLiftFactor = rim.RimLiftValue; - // } - // { - // var outline = parameters.Outline; - // // SetValue(material, MToonUtils.PropOutlineWidth, outline.OutlineWidthValue); - // mtoon.OutlineWidthFactor = outline.OutlineWidthValue; - - // // SetTexture(material, MToonUtils.PropOutlineWidthTexture, outline.OutlineWidthMultiplyTexture, textures); - // mtoon.OutlineWidthMultiplyTexture = textures.IndexOfNullable(outline.OutlineWidthMultiplyTexture.Texture); - - // // SetValue(material, MToonUtils.PropOutlineScaledMaxDistance, outline.OutlineScaledMaxDistanceValue); - // mtoon.OutlineScaledMaxDistanceFactor = outline.OutlineScaledMaxDistanceValue; - - // // SetColor(material, MToonUtils.PropOutlineColor, outline.OutlineColor); - // outline.OutlineColor.ToProtobuf(mtoon.OutlineFactor.Add, false); - - // // SetValue(material, MToonUtils.PropOutlineLightingMix, outline.OutlineLightingMixValue); - // mtoon.OutlineLightingMixFactor = outline.OutlineLightingMixValue; - - // // ValidateOutlineMode(material, outline.OutlineWidthMode, outline.OutlineColorMode); - // } - // { - // var textureOptions = parameters.TextureOption; - // // TODO: - // // material.SetTextureScale(MToonUtils.PropMainTex, textureOptions.MainTextureLeftBottomOriginScale); - // // material.SetTextureOffset(MToonUtils.PropMainTex, textureOptions.MainTextureLeftBottomOriginOffset); - - // // material.SetTexture(MToonUtils.PropUvAnimMaskTexture, textureOptions.UvAnimationMaskTexture, textures); - // mtoon.UvAnimationMaskTexture = textures.IndexOfNullable(textureOptions.UvAnimationMaskTexture.Texture); - - // // material.SetFloat(MToonUtils.PropUvAnimScrollX, textureOptions.UvAnimationScrollXSpeedValue); - // mtoon.UvAnimationScrollXSpeedFactor = textureOptions.UvAnimationScrollXSpeedValue; - - // // material.SetFloat(MToonUtils.PropUvAnimScrollY, textureOptions.UvAnimationScrollYSpeedValue); - // mtoon.UvAnimationScrollYSpeedFactor = textureOptions.UvAnimationScrollYSpeedValue; - - // // material.SetFloat(MToonUtils.PropUvAnimRotation, textureOptions.UvAnimationRotationSpeedValue); - // mtoon.UvAnimationRotationSpeedFactor = textureOptions.UvAnimationRotationSpeedValue; - // } - // } - - // /// - // /// Validate properties and Set hidden properties, keywords. - // /// if isBlendModeChangedByUser is true, renderQueue will set specified render mode's default value. - // /// - // /// - // /// - // public static void ValidateProperties(Material material, List textures, bool isBlendModeChangedByUser = false) - // { - // ValidateBlendMode(material, (RenderMode)material.GetFloat(MToonUtils.PropBlendMode), isBlendModeChangedByUser); - // ValidateNormalMode(material, material.GetTexture(MToonUtils.PropBumpMap, textures) != null); - // ValidateOutlineMode(material, - // (OutlineWidthMode)material.GetFloat(MToonUtils.PropOutlineWidthMode), - // (OutlineColorMode)material.GetFloat(MToonUtils.PropOutlineColorMode)); - // ValidateDebugMode(material, (DebugMode)material.GetFloat(MToonUtils.PropDebugMode)); - // ValidateCullMode(material, (CullMode)material.GetFloat(MToonUtils.PropCullMode)); - - // var mainTex = material.GetTexture(MToonUtils.PropMainTex, textures); - // var shadeTex = material.GetTexture(MToonUtils.PropShadeTexture, textures); - // if (mainTex != null && shadeTex == null) - // { - // material.SetTexture(MToonUtils.PropShadeTexture, mainTex, textures); - // } - // } - - // private static void ValidateDebugMode(Material material, DebugMode debugMode) - // { - // switch (debugMode) - // { - // case DebugMode.None: - // SetKeyword(material, MToonUtils.KeyDebugNormal, false); - // SetKeyword(material, MToonUtils.KeyDebugLitShadeRate, false); - // break; - // case DebugMode.Normal: - // SetKeyword(material, MToonUtils.KeyDebugNormal, true); - // SetKeyword(material, MToonUtils.KeyDebugLitShadeRate, false); - // break; - // case DebugMode.LitShadeRate: - // SetKeyword(material, MToonUtils.KeyDebugNormal, false); - // SetKeyword(material, MToonUtils.KeyDebugLitShadeRate, true); - // break; - // } - // } - - // public static void ValidateBlendMode(Material material, RenderMode renderMode, bool isChangedByUser) - // { - // switch (renderMode) - // { - // case RenderMode.Opaque: - // material.SetOverrideTag(MToonUtils.TagRenderTypeKey, MToonUtils.TagRenderTypeValueOpaque); - // material.SetInt(MToonUtils.PropSrcBlend, BlendMode.One); - // material.SetInt(MToonUtils.PropDstBlend, BlendMode.Zero); - // material.SetInt(MToonUtils.PropZWrite, MToonUtils.EnabledIntValue); - // material.SetInt(MToonUtils.PropAlphaToMask, MToonUtils.DisabledIntValue); - // SetKeyword(material, MToonUtils.KeyAlphaTestOn, false); - // SetKeyword(material, MToonUtils.KeyAlphaBlendOn, false); - // SetKeyword(material, MToonUtils.KeyAlphaPremultiplyOn, false); - // break; - // case RenderMode.Cutout: - // material.SetOverrideTag(MToonUtils.TagRenderTypeKey, MToonUtils.TagRenderTypeValueTransparentCutout); - // material.SetInt(MToonUtils.PropSrcBlend, BlendMode.One); - // material.SetInt(MToonUtils.PropDstBlend, BlendMode.Zero); - // material.SetInt(MToonUtils.PropZWrite, MToonUtils.EnabledIntValue); - // material.SetInt(MToonUtils.PropAlphaToMask, MToonUtils.EnabledIntValue); - // SetKeyword(material, MToonUtils.KeyAlphaTestOn, true); - // SetKeyword(material, MToonUtils.KeyAlphaBlendOn, false); - // SetKeyword(material, MToonUtils.KeyAlphaPremultiplyOn, false); - // break; - // case RenderMode.Transparent: - // material.SetOverrideTag(MToonUtils.TagRenderTypeKey, MToonUtils.TagRenderTypeValueTransparent); - // material.SetInt(MToonUtils.PropSrcBlend, BlendMode.SrcAlpha); - // material.SetInt(MToonUtils.PropDstBlend, BlendMode.OneMinusSrcAlpha); - // material.SetInt(MToonUtils.PropZWrite, MToonUtils.DisabledIntValue); - // material.SetInt(MToonUtils.PropAlphaToMask, MToonUtils.DisabledIntValue); - // SetKeyword(material, MToonUtils.KeyAlphaTestOn, false); - // SetKeyword(material, MToonUtils.KeyAlphaBlendOn, true); - // SetKeyword(material, MToonUtils.KeyAlphaPremultiplyOn, false); - // break; - // case RenderMode.TransparentWithZWrite: - // material.SetOverrideTag(MToonUtils.TagRenderTypeKey, MToonUtils.TagRenderTypeValueTransparent); - // material.SetInt(MToonUtils.PropSrcBlend, BlendMode.SrcAlpha); - // material.SetInt(MToonUtils.PropDstBlend, BlendMode.OneMinusSrcAlpha); - // material.SetInt(MToonUtils.PropZWrite, MToonUtils.EnabledIntValue); - // material.SetInt(MToonUtils.PropAlphaToMask, MToonUtils.DisabledIntValue); - // SetKeyword(material, MToonUtils.KeyAlphaTestOn, false); - // SetKeyword(material, MToonUtils.KeyAlphaBlendOn, true); - // SetKeyword(material, MToonUtils.KeyAlphaPremultiplyOn, false); - // break; - // } - - // if (isChangedByUser) - // { - // // ValidateRenderQueue(material, offset: 0); - // } - // else - // { - // var requirement = MToonUtils.GetRenderQueueRequirement(renderMode); - // // ValidateRenderQueue(material, offset: material.renderQueue - requirement.DefaultValue); - // } - // } - - // private static void ValidateRenderQueue(Material material, int offset) - // { - // var requirement = MToonUtils.GetRenderQueueRequirement(GetBlendMode(material)); - // var value = Mathf.Clamp(requirement.DefaultValue + offset, requirement.MinValue, requirement.MaxValue); - // material.renderQueue = value; - // } - - // private static void ValidateOutlineMode(Material material, OutlineWidthMode outlineWidthMode, - // OutlineColorMode outlineColorMode) - // { - // var isFixed = outlineColorMode == OutlineColorMode.FixedColor; - // var isMixed = outlineColorMode == OutlineColorMode.MixedLighting; - - // switch (outlineWidthMode) - // { - // case OutlineWidthMode.None: - // SetKeyword(material, MToonUtils.KeyOutlineWidthWorld, false); - // SetKeyword(material, MToonUtils.KeyOutlineWidthScreen, false); - // SetKeyword(material, MToonUtils.KeyOutlineColorFixed, false); - // SetKeyword(material, MToonUtils.KeyOutlineColorMixed, false); - // break; - // case OutlineWidthMode.WorldCoordinates: - // SetKeyword(material, MToonUtils.KeyOutlineWidthWorld, true); - // SetKeyword(material, MToonUtils.KeyOutlineWidthScreen, false); - // SetKeyword(material, MToonUtils.KeyOutlineColorFixed, isFixed); - // SetKeyword(material, MToonUtils.KeyOutlineColorMixed, isMixed); - // break; - // case OutlineWidthMode.ScreenCoordinates: - // SetKeyword(material, MToonUtils.KeyOutlineWidthWorld, false); - // SetKeyword(material, MToonUtils.KeyOutlineWidthScreen, true); - // SetKeyword(material, MToonUtils.KeyOutlineColorFixed, isFixed); - // SetKeyword(material, MToonUtils.KeyOutlineColorMixed, isMixed); - // break; - // } - // } - - // private static void ValidateNormalMode(Material material, bool requireNormalMapping) - // { - // SetKeyword(material, MToonUtils.KeyNormalMap, requireNormalMapping); - // } - - // private static void ValidateCullMode(Material material, CullMode cullMode) - // { - // switch (cullMode) - // { - // case CullMode.Back: - // material.SetInt(MToonUtils.PropCullMode, CullMode.Back); - // material.SetInt(MToonUtils.PropOutlineCullMode, CullMode.Front); - // break; - // case CullMode.Front: - // material.SetInt(MToonUtils.PropCullMode, CullMode.Front); - // material.SetInt(MToonUtils.PropOutlineCullMode, CullMode.Back); - // break; - // case CullMode.Off: - // material.SetInt(MToonUtils.PropCullMode, CullMode.Off); - // material.SetInt(MToonUtils.PropOutlineCullMode, CullMode.Front); - // break; - // } - // } - } -} \ No newline at end of file diff --git a/Assets/VRM10/Runtime/IO/MToonUtilsFromDefinition.cs.meta b/Assets/VRM10/Runtime/IO/MToonUtilsFromDefinition.cs.meta deleted file mode 100644 index 22f9e9fba..000000000 --- a/Assets/VRM10/Runtime/IO/MToonUtilsFromDefinition.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 269eb140bd3b26043a6afac332268766 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/MaterialAdapter.cs b/Assets/VRM10/Runtime/IO/MaterialAdapter.cs deleted file mode 100644 index d931fa903..000000000 --- a/Assets/VRM10/Runtime/IO/MaterialAdapter.cs +++ /dev/null @@ -1,230 +0,0 @@ -using VrmLib; -using System.Collections.Generic; -using System.Numerics; -using UniJSON; -using UniGLTF; -using System; - -namespace UniVRM10 -{ - public static class MaterialAdapter - { - public static Material FromGltf(this glTFMaterial x, List textures) - { - if (UniGLTF.Extensions.VRMC_materials_mtoon.GltfDeserializer.TryGet(x.extensions, - out UniGLTF.Extensions.VRMC_materials_mtoon.VRMC_materials_mtoon mtoon)) - { - // mtoon - return MToonAdapter.MToonFromGltf(x, textures, mtoon); - } - - if (glTF_KHR_materials_unlit.IsEnable(x)) - { - // unlit - return UnlitFromGltf(x, textures); - } - - // PBR - return PBRFromGltf(x, textures); - } - - public static void LoadCommonParams(this Material self, glTFMaterial material, List textures) - { - var pbr = material.pbrMetallicRoughness; - if (pbr.baseColorFactor != null) - { - self.BaseColorFactor = LinearColor.FromLiner(pbr.baseColorFactor); - } - var baseColorTexture = pbr.baseColorTexture; - if (baseColorTexture != null && baseColorTexture.index.TryGetValidIndex(textures.Count, out int index)) - { - self.BaseColorTexture = new TextureInfo(textures[index]); - } - - self.AlphaMode = EnumUtil.Parse(material.alphaMode); - self.AlphaCutoff = material.alphaCutoff; - self.DoubleSided = material.doubleSided; - } - - public static PBRMaterial PBRFromGltf(glTFMaterial material, List textures) - { - var self = new PBRMaterial(material.name); - - self.LoadCommonParams(material, textures); - - // - // pbr - // - var pbr = material.pbrMetallicRoughness; - - // metallic roughness - self.MetallicFactor = pbr.metallicFactor; - self.RoughnessFactor = pbr.roughnessFactor; - var metallicRoughnessTexture = pbr.metallicRoughnessTexture; - if (metallicRoughnessTexture != null - && metallicRoughnessTexture.index.TryGetValidIndex(textures.Count, out int metallicRoughnessTextureIndex)) - { - self.MetallicRoughnessTexture = textures[metallicRoughnessTextureIndex]; - } - // - // emissive - // - if (material.emissiveFactor != null) - { - self.EmissiveFactor = new Vector3( - material.emissiveFactor[0], - material.emissiveFactor[1], - material.emissiveFactor[2]); - } - var emissiveTexture = material.emissiveTexture; - if (emissiveTexture != null - && emissiveTexture.index.TryGetValidIndex(textures.Count, out int emissiveTextureIndex)) - { - self.EmissiveTexture = textures[emissiveTextureIndex]; - } - // - // normal - // - var normalTexture = material.normalTexture; - if (normalTexture != null - && normalTexture.index.TryGetValidIndex(textures.Count, out int normalTextureIndex)) - { - self.NormalTexture = textures[normalTextureIndex]; - } - // - // occlusion - // - var occlusionTexture = material.occlusionTexture; - if (occlusionTexture != null - && occlusionTexture.index.TryGetValidIndex(textures.Count, out int occlusionTextureIndex)) - { - self.OcclusionTexture = textures[occlusionTextureIndex]; - } - - return self; - } - - public static UnlitMaterial UnlitFromGltf(glTFMaterial material, List textures) - { - var unlit = new UnlitMaterial(material.name); - unlit.LoadCommonParams(material, textures); - return unlit; - } - - static string CastAlphaMode(VrmLib.AlphaModeType alphaMode) - { - if (alphaMode == AlphaModeType.BLEND_ZWRITE) - { - return "BLEND"; - } - return alphaMode.ToString(); - } - - static glTFMaterial ToGltf(this VrmLib.Material src, List textures) - { - var material = new glTFMaterial - { - name = src.Name, - pbrMetallicRoughness = new glTFPbrMetallicRoughness - { - baseColorFactor = src.BaseColorFactor.ToFloat4(), - }, - alphaMode = CastAlphaMode(src.AlphaMode), - alphaCutoff = src.AlphaCutoff, - doubleSided = src.DoubleSided, - }; - if (src.BaseColorTexture != null) - { - material.pbrMetallicRoughness.baseColorTexture = new glTFMaterialBaseColorTextureInfo - { - index = textures.IndexOfNullable(src.BaseColorTexture.Texture).Value, - }; - } - return material; - } - - public static glTFMaterial PBRToGltf(this PBRMaterial pbr, List textures) - { - var material = pbr.ToGltf(textures); - - // MetallicRoughness - material.pbrMetallicRoughness.baseColorFactor = pbr.BaseColorFactor.ToFloat4(); - if (pbr.BaseColorTexture != null) - { - material.pbrMetallicRoughness.baseColorTexture = new glTFMaterialBaseColorTextureInfo - { - index = textures.IndexOfNullable(pbr.BaseColorTexture.Texture).Value, - }; - } - material.pbrMetallicRoughness.metallicFactor = pbr.MetallicFactor; - material.pbrMetallicRoughness.roughnessFactor = pbr.RoughnessFactor; - if (pbr.MetallicRoughnessTexture != null) - { - material.pbrMetallicRoughness.metallicRoughnessTexture = new glTFMaterialMetallicRoughnessTextureInfo - { - index = textures.IndexOfNullable(pbr.MetallicRoughnessTexture).Value, - }; - } - - // Normal - if (pbr.NormalTexture != null) - { - material.normalTexture = new glTFMaterialNormalTextureInfo - { - index = textures.IndexOfNullable(pbr.NormalTexture).Value, - scale = pbr.NormalTextureScale - }; - } - - // Occlusion - if (pbr.OcclusionTexture != null) - { - material.occlusionTexture = new glTFMaterialOcclusionTextureInfo - { - index = textures.IndexOfNullable(pbr.OcclusionTexture).Value, - strength = pbr.OcclusionTextureStrength, - }; - } - - // Emissive - if (pbr.EmissiveTexture != null) - { - material.emissiveTexture = new glTFMaterialEmissiveTextureInfo - { - index = textures.IndexOfNullable(pbr.EmissiveTexture).Value, - }; - } - material.emissiveFactor = pbr.EmissiveFactor.ToFloat3(); - - // AlphaMode - material.alphaMode = CastAlphaMode(pbr.AlphaMode); - - // AlphaCutoff - material.alphaCutoff = pbr.AlphaCutoff; - - // DoubleSided - material.doubleSided = pbr.DoubleSided; - - return material; - } - - public static glTFMaterial UnlitToGltf(this UnlitMaterial unlit, List textures) - { - var material = unlit.ToGltf(textures); - - if (!(material.extensions is glTFExtensionExport extensions)) - { - extensions = new glTFExtensionExport(); - material.extensions = extensions; - } - extensions.Add( - glTF_KHR_materials_unlit.ExtensionName, - new ArraySegment(glTF_KHR_materials_unlit.Raw)); - - material.pbrMetallicRoughness.roughnessFactor = 0.9f; - material.pbrMetallicRoughness.metallicFactor = 0.0f; - - return material; - } - } -} diff --git a/Assets/VRM10/Runtime/IO/MaterialAdapter.cs.meta b/Assets/VRM10/Runtime/IO/MaterialAdapter.cs.meta deleted file mode 100644 index 9d7888645..000000000 --- a/Assets/VRM10/Runtime/IO/MaterialAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 82c26e1eaa170df4a876714ae8e73046 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/MeshAdapter.cs b/Assets/VRM10/Runtime/IO/MeshAdapter.cs index 23f3eab66..c19ead466 100644 --- a/Assets/VRM10/Runtime/IO/MeshAdapter.cs +++ b/Assets/VRM10/Runtime/IO/MeshAdapter.cs @@ -164,8 +164,7 @@ namespace UniVRM10 return true; } - public static MeshGroup FromGltf(this glTFMesh x, - Vrm10Storage storage, List materials) + public static MeshGroup FromGltf(this glTFMesh x, Vrm10Storage storage) { var group = new MeshGroup(x.name); @@ -176,7 +175,7 @@ namespace UniVRM10 var materialIndex = primitive.material; mesh.Submeshes.Add( - new Submesh(0, mesh.IndexBuffer.Count, materials[materialIndex])); + new Submesh(0, mesh.IndexBuffer.Count, materialIndex)); group.Meshes.Add(mesh); } @@ -189,7 +188,7 @@ namespace UniVRM10 var materialIndex = primitive.material; mesh.Submeshes.Add( - new Submesh(offset, mesh.IndexBuffer.Count, materials[materialIndex])); + new Submesh(offset, mesh.IndexBuffer.Count, materialIndex)); offset += mesh.IndexBuffer.Count; group.Meshes.Add(mesh); @@ -206,7 +205,7 @@ namespace UniVRM10 var materialIndex = primitive.material; var count = storage.Gltf.accessors[primitive.indices].count; mesh.Submeshes.Add( - new Submesh(offset, count, materials[materialIndex])); + new Submesh(offset, count, materialIndex)); offset += count; } @@ -258,7 +257,7 @@ namespace UniVRM10 } } - static void ExportMesh(this Mesh mesh, List materials, Vrm10Storage storage, glTFMesh gltfMesh, ExportArgs option) + static void ExportMesh(this Mesh mesh, List materials, Vrm10Storage storage, glTFMesh gltfMesh, ExportArgs option) { // // primitive share vertex buffer @@ -383,7 +382,7 @@ namespace UniVRM10 } } - public static glTFMesh ExportMeshGroup(this MeshGroup src, List materials, Vrm10Storage storage, ExportArgs option) + public static glTFMesh ExportMeshGroup(this MeshGroup src, List materials, Vrm10Storage storage, ExportArgs option) { var mesh = new glTFMesh { diff --git a/Assets/VRM10/Runtime/UnityBuilder/MeshLoader.cs b/Assets/VRM10/Runtime/IO/MeshLoader.cs similarity index 100% rename from Assets/VRM10/Runtime/UnityBuilder/MeshLoader.cs rename to Assets/VRM10/Runtime/IO/MeshLoader.cs diff --git a/Assets/VRM10/Runtime/UnityBuilder/MeshLoader.cs.meta b/Assets/VRM10/Runtime/IO/MeshLoader.cs.meta similarity index 100% rename from Assets/VRM10/Runtime/UnityBuilder/MeshLoader.cs.meta rename to Assets/VRM10/Runtime/IO/MeshLoader.cs.meta diff --git a/Assets/VRM10/vrmlib/Runtime/ImportExport/ModelLoader.cs b/Assets/VRM10/Runtime/IO/ModelLoader.cs similarity index 52% rename from Assets/VRM10/vrmlib/Runtime/ImportExport/ModelLoader.cs rename to Assets/VRM10/Runtime/IO/ModelLoader.cs index d1aa3492c..0c283ed05 100644 --- a/Assets/VRM10/vrmlib/Runtime/ImportExport/ModelLoader.cs +++ b/Assets/VRM10/Runtime/IO/ModelLoader.cs @@ -1,11 +1,12 @@ using System; using System.Linq; +using VrmLib; -namespace VrmLib +namespace UniVRM10 { public static class ModelLoader { - public static Model Load(IVrmStorage storage, string rootName, bool estimateHumanoid = false) + public static Model Load(Vrm10Storage storage, string rootName) { if (storage == null) { @@ -18,7 +19,6 @@ namespace VrmLib AssetGenerator = storage.AssetGenerator, AssetCopyright = storage.AssetCopyright, AssetMinVersion = storage.AssetMinVersion, - OriginalJson = storage.OriginalJson, }; // node @@ -45,20 +45,11 @@ namespace VrmLib } } - // image - model.Images.AddRange(Enumerable.Range(0, storage.ImageCount).Select(x => storage.CreateImage(x))); - - // texture - model.Textures.AddRange(Enumerable.Range(0, storage.TextureCount).Select(x => storage.CreateTexture(x, model.Images))); - - // material - model.Materials.AddRange(Enumerable.Range(0, storage.MaterialCount).Select(x => storage.CreateMaterial(x, model.Textures))); - // skin model.Skins.AddRange(Enumerable.Range(0, storage.SkinCount).Select(x => storage.CreateSkin(x, model.Nodes))); // mesh - model.MeshGroups.AddRange(Enumerable.Range(0, storage.MeshCount).Select(x => storage.CreateMesh(x, model.Materials))); + model.MeshGroups.AddRange(Enumerable.Range(0, storage.MeshCount).Select(x => storage.CreateMesh(x))); // skin for (int i = 0; i < storage.NodeCount; ++i) @@ -77,47 +68,7 @@ namespace VrmLib } } - // animation - model.Animations.AddRange(Enumerable.Range(0, storage.AnimationCount).Select(x => storage.CreateAnimation(x, model.Nodes))); - - // VRM - if (!LoadVrm(model, storage) && estimateHumanoid) - { - // VRMでないときにボーン推定する - model.HumanoidBoneEstimate(); - } - return model; } - - static bool LoadVrm(Model model, IVrmStorage storage) - { - if (!storage.HasVrm) - { - return false; - } - - var meta = storage.CreateVrmMeta(model.Textures); - - var Vrm = new Vrm(meta, storage.VrmExporterVersion, storage.VrmSpecVersion); - model.Vrm = Vrm; - - storage.LoadVrmHumanoid(model.Nodes); - - if (!model.CheckVrmHumanoid()) - { - throw new Exception("CheckVrmHumanoid"); - } - - Vrm.ExpressionManager = storage.CreateVrmExpression(model.MeshGroups, model.Materials, model.Nodes); - - Vrm.SpringBone = storage.CreateVrmSpringBone(model.Nodes); - - Vrm.FirstPerson = storage.CreateVrmFirstPerson(model.Nodes, model.MeshGroups); - - Vrm.LookAt = storage.CreateVrmLookAt(); - - return true; - } } } diff --git a/Assets/VRM10/vrmlib/Runtime/ImportExport/ModelLoader.cs.meta b/Assets/VRM10/Runtime/IO/ModelLoader.cs.meta similarity index 100% rename from Assets/VRM10/vrmlib/Runtime/ImportExport/ModelLoader.cs.meta rename to Assets/VRM10/Runtime/IO/ModelLoader.cs.meta diff --git a/Assets/VRM10/Runtime/IO/RuntimeUnityBuilder.cs b/Assets/VRM10/Runtime/IO/RuntimeUnityBuilder.cs new file mode 100644 index 000000000..83ba9f8f9 --- /dev/null +++ b/Assets/VRM10/Runtime/IO/RuntimeUnityBuilder.cs @@ -0,0 +1,605 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using UniGLTF; +using UnityEngine; +using VrmLib; + + +namespace UniVRM10 +{ + /// + /// VrmLib.Model から UnityPrefab を構築する + /// + public class RuntimeUnityBuilder : UniGLTF.ImporterContext + { + readonly Model m_model; + + UniGLTF.Extensions.VRMC_vrm.VRMC_vrm m_vrm; + + public RuntimeUnityBuilder(UniGLTF.GltfParser parser, IEnumerable<(string, UnityEngine.Object)> externalObjectMap = null) : base(parser, externalObjectMap) + { + m_model = VrmLoader.CreateVrmModel(parser); + + // for `VRMC_materials_mtoon` + this.GltfMaterialImporter.GltfMaterialParamProcessors.Insert(0, Vrm10MToonMaterialImporter.TryCreateParam); + + if (!UniGLTF.Extensions.VRMC_vrm.GltfDeserializer.TryGet(parser.GLTF.extensions, out m_vrm)) + { + throw new Exception("VRMC_vrm is not found"); + } + + // assign humanoid bones + if (m_vrm.Humanoid != null) + { + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.Hips, HumanoidBones.hips); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftUpperLeg, HumanoidBones.leftUpperLeg); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightUpperLeg, HumanoidBones.rightUpperLeg); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftLowerLeg, HumanoidBones.leftLowerLeg); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightLowerLeg, HumanoidBones.rightLowerLeg); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftFoot, HumanoidBones.leftFoot); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightFoot, HumanoidBones.rightFoot); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.Spine, HumanoidBones.spine); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.Chest, HumanoidBones.chest); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.Neck, HumanoidBones.neck); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.Head, HumanoidBones.head); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftShoulder, HumanoidBones.leftShoulder); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightShoulder, HumanoidBones.rightShoulder); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftUpperArm, HumanoidBones.leftUpperArm); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightUpperArm, HumanoidBones.rightUpperArm); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftLowerArm, HumanoidBones.leftLowerArm); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightLowerArm, HumanoidBones.rightLowerArm); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftHand, HumanoidBones.leftHand); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightHand, HumanoidBones.rightHand); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftToes, HumanoidBones.leftToes); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightToes, HumanoidBones.rightToes); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftEye, HumanoidBones.leftEye); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightEye, HumanoidBones.rightEye); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.Jaw, HumanoidBones.jaw); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftThumbProximal, HumanoidBones.leftThumbProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftThumbIntermediate, HumanoidBones.leftThumbIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftThumbDistal, HumanoidBones.leftThumbDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftIndexProximal, HumanoidBones.leftIndexProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftIndexIntermediate, HumanoidBones.leftIndexIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftIndexDistal, HumanoidBones.leftIndexDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftMiddleProximal, HumanoidBones.leftMiddleProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftMiddleIntermediate, HumanoidBones.leftMiddleIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftMiddleDistal, HumanoidBones.leftMiddleDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftRingProximal, HumanoidBones.leftRingProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftRingIntermediate, HumanoidBones.leftRingIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftRingDistal, HumanoidBones.leftRingDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftLittleProximal, HumanoidBones.leftLittleProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftLittleIntermediate, HumanoidBones.leftLittleIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.LeftLittleDistal, HumanoidBones.leftLittleDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightThumbProximal, HumanoidBones.rightThumbProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightThumbIntermediate, HumanoidBones.rightThumbIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightThumbDistal, HumanoidBones.rightThumbDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightIndexProximal, HumanoidBones.rightIndexProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightIndexIntermediate, HumanoidBones.rightIndexIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightIndexDistal, HumanoidBones.rightIndexDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightMiddleProximal, HumanoidBones.rightMiddleProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightMiddleIntermediate, HumanoidBones.rightMiddleIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightMiddleDistal, HumanoidBones.rightMiddleDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightRingProximal, HumanoidBones.rightRingProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightRingIntermediate, HumanoidBones.rightRingIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightRingDistal, HumanoidBones.rightRingDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightLittleProximal, HumanoidBones.rightLittleProximal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightLittleIntermediate, HumanoidBones.rightLittleIntermediate); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.RightLittleDistal, HumanoidBones.rightLittleDistal); + AssignHumanoid(m_model.Nodes, m_vrm.Humanoid.HumanBones.UpperChest, HumanoidBones.upperChest); + } + } + + public class ModelMap + { + public readonly Dictionary Nodes = new Dictionary(); + public readonly Dictionary Meshes = new Dictionary(); + } + + /// + /// VrmLib.Model の オブジェクトと UnityEngine.Object のマッピングを記録する + /// + /// + readonly ModelMap m_map = new ModelMap(); + + static void AssignHumanoid(List nodes, UniGLTF.Extensions.VRMC_vrm.HumanBone humanBone, VrmLib.HumanoidBones key) + { + if (humanBone != null && humanBone.Node.HasValue) + { + nodes[humanBone.Node.Value].HumanoidBone = key; + } + } + + /// + /// VrmLib.Model から 構築する + /// + /// + /// + protected override async Task LoadGeometryAsync(IAwaitCaller awaitCaller, Func MeasureTime) + { + // fill assets + for (int i = 0; i < m_model.Materials.Count; ++i) + { + var src = m_model.Materials[i]; + var dst = MaterialFactory.Materials[i].Asset; + } + + await awaitCaller.NextFrame(); + + // mesh + for (int i = 0; i < m_model.MeshGroups.Count; ++i) + { + var src = m_model.MeshGroups[i]; + if (src.Meshes.Count == 1) + { + // submesh 方式 + var mesh = new UnityEngine.Mesh(); + mesh.name = src.Name; + mesh.LoadMesh(src.Meshes[0], src.Skin); + m_map.Meshes.Add(src, mesh); + Meshes.Add(new MeshWithMaterials + { + Mesh = mesh, + Materials = src.Meshes[0].Submeshes.Select(x => MaterialFactory.Materials[x.Material].Asset).ToArray(), + }); + } + else + { + // 頂点バッファの連結が必用 + throw new NotImplementedException(); + } + + await awaitCaller.NextFrame(); + } + + // node: recursive + CreateNodes(m_model.Root, null, m_map.Nodes); + for (int i = 0; i < m_model.Nodes.Count; ++i) + { + Nodes.Add(m_map.Nodes[m_model.Nodes[i]].transform); + } + await awaitCaller.NextFrame(); + + if (Root == null) + { + Root = m_map.Nodes[m_model.Root]; + } + else + { + // replace + var modelRoot = m_map.Nodes[m_model.Root]; + foreach (Transform child in modelRoot.transform) + { + child.SetParent(Root.transform, true); + } + m_map.Nodes[m_model.Root] = Root; + } + await awaitCaller.NextFrame(); + + // renderer + var map = m_map; + foreach (var (node, go) in map.Nodes) + { + if (node.MeshGroup is null) + { + continue; + } + + if (node.MeshGroup.Meshes.Count > 1) + { + throw new NotImplementedException("invalid isolated vertexbuffer"); + } + + var renderer = CreateRenderer(node, go, map, MaterialFactory.Materials); + await awaitCaller.NextFrame(); + } + } + + UnityEngine.Avatar m_humanoid; + VRM10MetaObject m_meta; + VRM10ExpressionAvatar m_exressionAvatar; + + protected override async Task OnLoadHierarchy(IAwaitCaller awaitCaller, Func MeasureTime) + { + Root.name = "VRM1"; + + // humanoid + var humanoid = Root.AddComponent(); + humanoid.AssignBones(m_map.Nodes.Select(x => (ToUnity(x.Key.HumanoidBone.GetValueOrDefault()), x.Value.transform))); + m_humanoid = humanoid.CreateAvatar(); + m_humanoid.name = "humanoid"; + var animator = Root.AddComponent(); + animator.avatar = m_humanoid; + + // VrmController + var controller = Root.AddComponent(); + + // vrm + await LoadVrmAsync(awaitCaller, controller, m_vrm); + // springBone + if (UniGLTF.Extensions.VRMC_springBone.GltfDeserializer.TryGet(Parser.GLTF.extensions, out UniGLTF.Extensions.VRMC_springBone.VRMC_springBone springBone)) + { + await LoadSpringBoneAsync(awaitCaller, controller, springBone); + } + // constraint + await LoadConstraintAsync(awaitCaller, controller); + } + + async Task LoadVrmAsync(IAwaitCaller awaitCaller, VRM10Controller controller, UniGLTF.Extensions.VRMC_vrm.VRMC_vrm vrm) + { + // meta + if (vrm.Meta != null) + { + var src = vrm.Meta; + m_meta = ScriptableObject.CreateInstance(); + m_meta.name = VRM10MetaObject.ExtractKey; + controller.Meta = m_meta; + m_meta.Name = src.Name; + m_meta.Version = src.Version; + m_meta.ContactInformation = src.ContactInformation; + // avatar + m_meta.AllowedUser = src.AvatarPermission; + m_meta.ViolentUsage = src.AllowExcessivelyViolentUsage.Value; + m_meta.SexualUsage = src.AllowExcessivelySexualUsage.Value; + m_meta.CommercialUsage = src.CommercialUsage; + m_meta.PoliticalOrReligiousUsage = src.AllowPoliticalOrReligiousUsage.Value; + // redistribution + m_meta.CreditNotation = src.CreditNotation; + m_meta.Redistribution = src.AllowRedistribution.Value; + m_meta.ModificationLicense = src.Modification; + m_meta.OtherLicenseUrl = src.OtherLicenseUrl; + // + if (src.References != null) + { + m_meta.References.AddRange(src.References); + } + if (src.Authors != null) + { + m_meta.Authors.AddRange(src.Authors); + } + if (Vrm10MToonMaterialImporter.TryGetMetaThumbnailTextureImportParam(Parser, vrm, out VRMShaders.TextureImportParam param)) + { + var texture = await TextureFactory.GetTextureAsync(param); + if (texture != null) + { + m_meta.Thumbnail = texture; + } + } + } + + // expression + if (vrm.Expressions != null) + { + controller.Expression.ExpressionAvatar = ScriptableObject.CreateInstance(); + + m_exressionAvatar = controller.Expression.ExpressionAvatar; + m_exressionAvatar.name = VRM10ExpressionAvatar.ExtractKey; + + foreach (var expression in vrm.Expressions) + { + var clip = ScriptableObject.CreateInstance(); + clip.Preset = expression.Preset; + clip.ExpressionName = expression.Name; + clip.name = expression.ExtractName(); + clip.IsBinary = expression.IsBinary.GetValueOrDefault(); + clip.OverrideBlink = expression.OverrideBlink; + clip.OverrideLookAt = expression.OverrideLookAt; + clip.OverrideMouth = expression.OverrideMouth; + + clip.MorphTargetBindings = expression.MorphTargetBinds.Select(x => x.Build10(Root, m_map, m_model)) + .ToArray(); + clip.MaterialColorBindings = expression.MaterialColorBinds.Select(x => x.Build10(MaterialFactory.Materials)) + .Where(x => x.HasValue) + .Select(x => x.Value) + .ToArray(); + clip.MaterialUVBindings = expression.TextureTransformBinds.Select(x => x.Build10(MaterialFactory.Materials)) + .Where(x => x.HasValue) + .Select(x => x.Value) + .ToArray(); + + m_exressionAvatar.Clips.Add(clip); + } + } + + // lookat + if (vrm.LookAt != null) + { + var src = vrm.LookAt; + controller.LookAt.LookAtType = src.LookAtType; + controller.LookAt.OffsetFromHead = new Vector3(src.OffsetFromHeadBone[0], src.OffsetFromHeadBone[1], src.OffsetFromHeadBone[2]); + controller.LookAt.HorizontalInner = new CurveMapper(src.LookAtHorizontalInner.InputMaxValue.Value, src.LookAtHorizontalInner.OutputScale.Value); + controller.LookAt.HorizontalOuter = new CurveMapper(src.LookAtHorizontalOuter.InputMaxValue.Value, src.LookAtHorizontalOuter.OutputScale.Value); + controller.LookAt.VerticalUp = new CurveMapper(src.LookAtVerticalUp.InputMaxValue.Value, src.LookAtHorizontalOuter.OutputScale.Value); + controller.LookAt.VerticalDown = new CurveMapper(src.LookAtVerticalDown.InputMaxValue.Value, src.LookAtHorizontalOuter.OutputScale.Value); + } + + // firstPerson + if (vrm.FirstPerson != null && vrm.FirstPerson.MeshAnnotations != null) + { + var fp = vrm.FirstPerson; + foreach (var x in fp.MeshAnnotations) + { + var node = Nodes[x.Node.Value]; + controller.FirstPerson.Renderers.Add(new RendererFirstPersonFlags + { + FirstPersonFlag = x.FirstPersonType, + Renderer = node.GetComponent() + }); + } + } + } + + async Task LoadSpringBoneAsync(IAwaitCaller awaitCaller, VRM10Controller controller, UniGLTF.Extensions.VRMC_springBone.VRMC_springBone gltfVrmSpringBone) + { + await awaitCaller.NextFrame(); + + var springBoneManager = controller.SpringBone; + + // springs + if (gltfVrmSpringBone.Springs != null) + { + foreach (var gltfSpring in gltfVrmSpringBone.Springs) + { + var springBone = new VRM10SpringBone(); + springBone.Comment = gltfSpring.Name; + + // joint + foreach (var gltfJoint in gltfSpring.Joints) + { + if (gltfJoint.Node.HasValue) + { + var index = gltfJoint.Node.Value; + if (index < 0 || index >= Nodes.Count) + { + throw new IndexOutOfRangeException($"{index} > {Nodes.Count}"); + } + var joint = new VRM10SpringJoint(Nodes[gltfJoint.Node.Value]); + joint.m_jointRadius = gltfJoint.HitRadius.Value; + joint.m_dragForce = gltfJoint.DragForce.Value; + joint.m_gravityDir = Vector3(gltfJoint.GravityDir); + joint.m_gravityPower = gltfJoint.GravityPower.Value; + joint.m_stiffnessForce = gltfJoint.Stiffness.Value; + // joint.m_exclude = gltfJoint.Exclude.GetValueOrDefault(); + springBone.Joints.Add(joint); + } + } + + // collider + springBone.ColliderGroups.AddRange(gltfSpring.Colliders.Select(colliderNode => + { + if (UniGLTF.Extensions.VRMC_node_collider.GltfDeserializer.TryGet(Parser.GLTF.nodes[colliderNode].extensions, + out UniGLTF.Extensions.VRMC_node_collider.VRMC_node_collider extension)) + { + var node = Nodes[colliderNode]; + var colliderGroup = node.gameObject.GetOrAddComponent(); + colliderGroup.Colliders.AddRange(extension.Shapes.Select(x => + { + if (x.Sphere != null) + { + return new VRM10SpringBoneCollider + { + ColliderType = VRM10SpringBoneColliderTypes.Sphere, + Offset = Vector3(x.Sphere.Offset), + Radius = x.Sphere.Radius.Value, + }; + } + else if (x.Capsule != null) + { + return new VRM10SpringBoneCollider + { + ColliderType = VRM10SpringBoneColliderTypes.Capsule, + Offset = Vector3(x.Capsule.Offset), + Radius = x.Capsule.Radius.Value, + Tail = Vector3(x.Capsule.Tail), + }; + } + else + { + throw new NotImplementedException(); + } + })); + return colliderGroup; + } + else + { + return null; + } + }).Where(x => x != null)); + + springBoneManager.Springs.Add(springBone); + } + } + } + + static AxisMask FreezeAxis(bool[] flags) + { + var mask = default(AxisMask); + if (flags != null && flags.Length == 3) + { + if (flags[0]) mask |= AxisMask.X; + if (flags[1]) mask |= AxisMask.Y; + if (flags[2]) mask |= AxisMask.Z; + } + return mask; + } + + static Vector3 Vector3(float[] f) + { + var v = default(Vector3); + if (f != null && f.Length == 3) + { + v.x = f[0]; + v.y = f[1]; + v.z = f[2]; + } + return v; + } + + async Task LoadConstraintAsync(IAwaitCaller awaitCaller, VRM10Controller controller) + { + for (int i = 0; i < Parser.GLTF.nodes.Count; ++i) + { + var gltfNode = Parser.GLTF.nodes[i]; + if (UniGLTF.Extensions.VRMC_constraints.GltfDeserializer.TryGet(gltfNode.extensions, out UniGLTF.Extensions.VRMC_constraints.VRMC_constraints constraint)) + { + var node = Nodes[i]; + if (constraint.Position != null) + { + var p = constraint.Position; + var positionConstraint = node.gameObject.AddComponent(); + positionConstraint.SourceCoordinate = p.SourceSpace; + positionConstraint.Source = Nodes[p.Source.Value]; + positionConstraint.DestinationCoordinate = p.DestinationSpace; + positionConstraint.FreezeAxes = FreezeAxis(p.FreezeAxes); + positionConstraint.Weight = p.Weight.Value; + positionConstraint.ModelRoot = Root.transform; + } + else if (constraint.Rotation != null) + { + var r = constraint.Rotation; + var rotationConstraint = node.gameObject.AddComponent(); + rotationConstraint.SourceCoordinate = r.SourceSpace; + rotationConstraint.Source = Nodes[r.Source.Value]; + rotationConstraint.DestinationCoordinate = r.DestinationSpace; + rotationConstraint.FreezeAxes = FreezeAxis(r.FreezeAxes); + rotationConstraint.Weight = r.Weight.Value; + rotationConstraint.ModelRoot = Root.transform; + } + else if (constraint.Aim != null) + { + var a = constraint.Aim; + var aimConstraint = node.gameObject.AddComponent(); + aimConstraint.Source = Nodes[a.Source.Value]; + aimConstraint.AimVector = Vector3(a.AimVector); + aimConstraint.UpVector = Vector3(a.UpVector); + } + } + } + + await awaitCaller.NextFrame(); + } + + public static HumanBodyBones ToUnity(VrmLib.HumanoidBones bone) + { + if (bone == VrmLib.HumanoidBones.unknown) + { + return HumanBodyBones.LastBone; + } + return VrmLib.EnumUtil.Cast(bone); + } + + /// + /// ヒエラルキーを再帰的に構築する + /// + public static void CreateNodes(VrmLib.Node node, GameObject parent, Dictionary nodes) + { + GameObject go = new GameObject(node.Name); + go.transform.SetPositionAndRotation(node.Translation.ToUnityVector3(), node.Rotation.ToUnityQuaternion()); + nodes.Add(node, go); + if (parent != null) + { + go.transform.SetParent(parent.transform); + } + + if (node.Children.Count > 0) + { + for (int n = 0; n < node.Children.Count; n++) + { + CreateNodes(node.Children[n], go, nodes); + } + } + } + + /// + /// MeshFilter + MeshRenderer もしくは SkinnedMeshRenderer を構築する + /// + public static Renderer CreateRenderer(VrmLib.Node node, GameObject go, ModelMap map, + IReadOnlyList materialLoadInfos) + { + var mesh = node.MeshGroup.Meshes[0]; + + Renderer renderer = null; + var hasBlendShape = mesh.MorphTargets.Any(); + if (node.MeshGroup.Skin != null || hasBlendShape) + { + var skinnedMeshRenderer = go.AddComponent(); + renderer = skinnedMeshRenderer; + skinnedMeshRenderer.sharedMesh = map.Meshes[node.MeshGroup]; + if (node.MeshGroup.Skin != null) + { + skinnedMeshRenderer.bones = node.MeshGroup.Skin.Joints.Select(x => map.Nodes[x].transform).ToArray(); + if (node.MeshGroup.Skin.Root != null) + { + skinnedMeshRenderer.rootBone = map.Nodes[node.MeshGroup.Skin.Root].transform; + } + } + } + else + { + var meshFilter = go.AddComponent(); + renderer = go.AddComponent(); + meshFilter.sharedMesh = map.Meshes[node.MeshGroup]; + } + var materials = mesh.Submeshes.Select(x => materialLoadInfos[x.Material].Asset).ToArray(); + renderer.sharedMaterials = materials; + + return renderer; + } + + public override void TransferOwnership(Func take) + { + // VRM 固有のリソース(ScriptableObject) + if (take(m_humanoid)) + { + m_humanoid = null; + } + + if (take(m_meta)) + { + m_meta = null; + } + + foreach (var x in m_exressionAvatar.Clips) + { + if (take(x)) + { + // do nothing + } + } + + if (take(m_exressionAvatar)) + { + m_exressionAvatar = null; + } + + // GLTF のリソース + base.TransferOwnership(take); + } + + public override void Dispose() + { + Action destroy = UnityResourceDestroyer.DestroyResource(); + + // VRM specific + if (m_humanoid != null) + { + destroy(m_humanoid); + } + if (m_meta != null) + { + destroy(m_meta); + } + if (m_exressionAvatar != null) + { + foreach (var clip in m_exressionAvatar.Clips) + { + destroy(clip); + } + destroy(m_exressionAvatar); + } + + base.Dispose(); + } + } +} diff --git a/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityBuilder.cs.meta b/Assets/VRM10/Runtime/IO/RuntimeUnityBuilder.cs.meta similarity index 100% rename from Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityBuilder.cs.meta rename to Assets/VRM10/Runtime/IO/RuntimeUnityBuilder.cs.meta diff --git a/Assets/VRM10/Runtime/IO/RuntimeVrmConverter.cs b/Assets/VRM10/Runtime/IO/RuntimeVrmConverter.cs new file mode 100644 index 000000000..738ef51e7 --- /dev/null +++ b/Assets/VRM10/Runtime/IO/RuntimeVrmConverter.cs @@ -0,0 +1,326 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using MeshUtility; +using UnityEngine; +using VrmLib; + +namespace UniVRM10 +{ + public class RuntimeVrmConverter + { + public VrmLib.Model Model; + + public Dictionary Nodes = new Dictionary(); + public List Materials = new List(); + public Dictionary Meshes = new Dictionary(); + + #region Export 1.0 + /// + /// metaObject が null のときは、root から取得する + /// + public VrmLib.Model ToModelFrom10(GameObject root, VRM10MetaObject metaObject = null) + { + Model = new VrmLib.Model(VrmLib.Coordinates.Unity); + + if (metaObject is null) + { + var vrmController = root.GetComponent(); + if (vrmController is null || vrmController.Meta is null) + { + throw new NullReferenceException("metaObject is null"); + } + metaObject = vrmController.Meta; + } + + ToGlbModel(root); + + // humanoid + { + var humanoid = root.GetComponent(); + if (humanoid is null) + { + humanoid = root.AddComponent(); + humanoid.AssignBonesFromAnimator(); + } + + foreach (HumanBodyBones humanBoneType in Enum.GetValues(typeof(HumanBodyBones))) + { + var transform = humanoid.GetBoneTransform(humanBoneType); + if (transform != null && Nodes.TryGetValue(transform.gameObject, out VrmLib.Node node)) + { + node.HumanoidBone = (VrmLib.HumanoidBones)Enum.Parse(typeof(VrmLib.HumanoidBones), humanBoneType.ToString(), true); + } + } + } + + return Model; + } + + public VrmLib.Model ToGlbModel(GameObject root) + { + if (Model == null) + { + Model = new VrmLib.Model(VrmLib.Coordinates.Unity); + } + + // node + { + Model.Root.Name = root.name; + CreateNodes(root.transform, Model.Root, Nodes); + Model.Nodes = Nodes + .Where(x => x.Value != Model.Root) + .Select(x => x.Value).ToList(); + } + + // material and textures + var rendererComponents = root.GetComponentsInChildren(); + { + foreach (var renderer in rendererComponents) + { + var materials = renderer.sharedMaterials; // avoid copy + foreach (var material in materials) + { + if (Materials.Contains(material)) + { + continue; + } + + Model.Materials.Add(material); + Materials.Add(material); + } + } + } + + // mesh + { + foreach (var renderer in rendererComponents) + { + if (renderer is SkinnedMeshRenderer skinnedMeshRenderer) + { + if (skinnedMeshRenderer.sharedMesh != null) + { + var mesh = CreateMesh(skinnedMeshRenderer.sharedMesh, skinnedMeshRenderer, Materials); + var skin = CreateSkin(skinnedMeshRenderer, Nodes, root); + if (skin != null) + { + // blendshape only で skinning が無いやつがある + mesh.Skin = skin; + Model.Skins.Add(mesh.Skin); + } + Model.MeshGroups.Add(mesh); + Nodes[renderer.gameObject].MeshGroup = mesh; + Meshes.Add(skinnedMeshRenderer.sharedMesh, mesh); + } + } + else if (renderer is MeshRenderer meshRenderer) + { + var filter = meshRenderer.gameObject.GetComponent(); + if (filter != null && filter.sharedMesh != null) + { + var mesh = CreateMesh(filter.sharedMesh, meshRenderer, Materials); + Model.MeshGroups.Add(mesh); + Nodes[renderer.gameObject].MeshGroup = mesh; + Meshes.Add(filter.sharedMesh, mesh); + } + } + } + } + + return Model; + } + #endregion + + + + private static void CreateNodes( + Transform parentTransform, + VrmLib.Node parentNode, + Dictionary nodes) + { + // parentNode.SetMatrix(parentTransform.localToWorldMatrix.ToNumericsMatrix4x4(), false); + parentNode.LocalTranslation = parentTransform.localPosition.ToNumericsVector3(); + parentNode.LocalRotation = parentTransform.localRotation.ToNumericsQuaternion(); + parentNode.LocalScaling = parentTransform.localScale.ToNumericsVector3(); + nodes.Add(parentTransform.gameObject, parentNode); + + foreach (Transform child in parentTransform) + { + var childNode = new VrmLib.Node(child.gameObject.name); + CreateNodes(child, childNode, nodes); + parentNode.Add(childNode); + } + } + + private static Transform GetTransformFromRelativePath(Transform root, Queue relativePath) + { + var name = relativePath.Dequeue(); + foreach (Transform node in root) + { + if (node.gameObject.name == name) + { + if (relativePath.Count == 0) + { + return node; + } + else + { + return GetTransformFromRelativePath(node, relativePath); + } + } + } + + return null; + } + + private static VrmLib.MeshGroup CreateMesh(UnityEngine.Mesh mesh, Renderer renderer, List materials) + { + var meshGroup = new VrmLib.MeshGroup(mesh.name); + var vrmMesh = new VrmLib.Mesh(); + vrmMesh.VertexBuffer = new VrmLib.VertexBuffer(); + vrmMesh.VertexBuffer.Add(VrmLib.VertexBuffer.PositionKey, ToBufferAccessor(mesh.vertices)); + + if (mesh.boneWeights.Length == mesh.vertexCount) + { + vrmMesh.VertexBuffer.Add( + VrmLib.VertexBuffer.WeightKey, + ToBufferAccessor(mesh.boneWeights.Select(x => + new Vector4(x.weight0, x.weight1, x.weight2, x.weight3)).ToArray() + )); + vrmMesh.VertexBuffer.Add( + VrmLib.VertexBuffer.JointKey, + ToBufferAccessor(mesh.boneWeights.Select(x => + new VrmLib.SkinJoints((ushort)x.boneIndex0, (ushort)x.boneIndex1, (ushort)x.boneIndex2, (ushort)x.boneIndex3)).ToArray() + )); + } + if (mesh.uv.Length == mesh.vertexCount) vrmMesh.VertexBuffer.Add(VrmLib.VertexBuffer.TexCoordKey, ToBufferAccessor(mesh.uv)); + if (mesh.normals.Length == mesh.vertexCount) vrmMesh.VertexBuffer.Add(VrmLib.VertexBuffer.NormalKey, ToBufferAccessor(mesh.normals)); + if (mesh.colors.Length == mesh.vertexCount) vrmMesh.VertexBuffer.Add(VrmLib.VertexBuffer.ColorKey, ToBufferAccessor(mesh.colors)); + vrmMesh.IndexBuffer = ToBufferAccessor(mesh.triangles); + + int offset = 0; + for (int i = 0; i < mesh.subMeshCount; i++) + { +#if UNITY_2019 + var subMesh = mesh.GetSubMesh(i); + try + { + vrmMesh.Submeshes.Add(new VrmLib.Submesh(offset, subMesh.indexCount, materials.IndexOf(renderer.sharedMaterials[i]))); + } + catch (Exception ex) + { + Debug.LogError(ex); + } + offset += subMesh.indexCount; +#else + var triangles = mesh.GetTriangles(i); + try + { + vrmMesh.Submeshes.Add(new VrmLib.Submesh(offset, triangles.Length, materials.IndexOf(renderer.sharedMaterials[i]))); + } + catch (Exception ex) + { + Debug.LogError(ex); + } + offset += triangles.Length; +#endif + } + + for (int i = 0; i < mesh.blendShapeCount; i++) + { + var blendShapeVertices = mesh.vertices; + var usePosition = blendShapeVertices != null && blendShapeVertices.Length > 0; + + var blendShapeNormals = mesh.normals; + var useNormal = usePosition && blendShapeNormals != null && blendShapeNormals.Length == blendShapeVertices.Length; + // var useNormal = usePosition && blendShapeNormals != null && blendShapeNormals.Length == blendShapeVertices.Length && !exportOnlyBlendShapePosition; + + var blendShapeTangents = mesh.tangents.Select(y => (Vector3)y).ToArray(); + //var useTangent = usePosition && blendShapeTangents != null && blendShapeTangents.Length == blendShapeVertices.Length; + // var useTangent = false; + + var frameCount = mesh.GetBlendShapeFrameCount(i); + mesh.GetBlendShapeFrameVertices(i, frameCount - 1, blendShapeVertices, blendShapeNormals, null); + + if (usePosition) + { + var morphTarget = new VrmLib.MorphTarget(mesh.GetBlendShapeName(i)); + morphTarget.VertexBuffer = new VrmLib.VertexBuffer(); + morphTarget.VertexBuffer.Add(VrmLib.VertexBuffer.PositionKey, ToBufferAccessor(blendShapeVertices)); + vrmMesh.MorphTargets.Add(morphTarget); + } + } + + meshGroup.Meshes.Add(vrmMesh); + return meshGroup; + } + + private static VrmLib.Skin CreateSkin( + SkinnedMeshRenderer skinnedMeshRenderer, + Dictionary nodes, + GameObject root) + { + if (skinnedMeshRenderer.bones == null || skinnedMeshRenderer.bones.Length == 0) + { + return null; + } + + var skin = new VrmLib.Skin(); + skin.InverseMatrices = ToBufferAccessor(skinnedMeshRenderer.sharedMesh.bindposes); + if (skinnedMeshRenderer.rootBone != null) + { + skin.Root = nodes[skinnedMeshRenderer.rootBone.gameObject]; + } + + skin.Joints = skinnedMeshRenderer.bones.Select(x => nodes[x.gameObject]).ToList(); + return skin; + } + + private static VrmLib.BufferAccessor ToBufferAccessor(VrmLib.SkinJoints[] values) + { + return ToBufferAccessor(values, VrmLib.AccessorValueType.UNSIGNED_SHORT, VrmLib.AccessorVectorType.VEC4); + } + + private static VrmLib.BufferAccessor ToBufferAccessor(Color[] colors) + { + return ToBufferAccessor(colors, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.VEC4); + } + + private static VrmLib.BufferAccessor ToBufferAccessor(Vector4[] vectors) + { + return ToBufferAccessor(vectors, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.VEC4); + } + + private static VrmLib.BufferAccessor ToBufferAccessor(Vector3[] vectors) + { + return ToBufferAccessor(vectors, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.VEC3); + } + + private static VrmLib.BufferAccessor ToBufferAccessor(Vector2[] vectors) + { + return ToBufferAccessor(vectors, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.VEC2); + } + + private static VrmLib.BufferAccessor ToBufferAccessor(int[] scalars) + { + return ToBufferAccessor(scalars, VrmLib.AccessorValueType.UNSIGNED_INT, VrmLib.AccessorVectorType.SCALAR); + } + + private static VrmLib.BufferAccessor ToBufferAccessor(Matrix4x4[] matrixes) + { + return ToBufferAccessor(matrixes, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.MAT4); + } + + private static VrmLib.BufferAccessor ToBufferAccessor(T[] value, VrmLib.AccessorValueType valueType, VrmLib.AccessorVectorType vectorType) where T : struct + { + var span = VrmLib.SpanLike.CopyFrom(value); + return new VrmLib.BufferAccessor( + span.Bytes, + valueType, + vectorType, + value.Length + ); + } + } +} diff --git a/Assets/VRM10/Runtime/VRMConverter/RuntimeVrmConverter.cs.meta b/Assets/VRM10/Runtime/IO/RuntimeVrmConverter.cs.meta similarity index 100% rename from Assets/VRM10/Runtime/VRMConverter/RuntimeVrmConverter.cs.meta rename to Assets/VRM10/Runtime/IO/RuntimeVrmConverter.cs.meta diff --git a/Assets/VRM10/Runtime/IO/TextureAdapter.cs b/Assets/VRM10/Runtime/IO/TextureAdapter.cs deleted file mode 100644 index d5c6f187c..000000000 --- a/Assets/VRM10/Runtime/IO/TextureAdapter.cs +++ /dev/null @@ -1,39 +0,0 @@ -using VrmLib; -using System; -using System.Collections.Generic; -using UniGLTF; - -namespace UniVRM10 -{ - public static class TextureAdapter - { - public static ImageTexture FromGltf(this glTFTexture x, glTFTextureSampler sampler, List images, Texture.ColorSpaceTypes colorSpace, Texture.TextureTypes textureType) - { - var image = images[x.source]; - var name = !string.IsNullOrEmpty(x.name) ? x.name : image.Name; - return new ImageTexture(name, sampler.FromGltf(), image, colorSpace, textureType); - } - - public static TextureSampler FromGltf(this glTFTextureSampler sampler) - { - return new TextureSampler - { - WrapS = (TextureWrapType)sampler.wrapS, - WrapT = (TextureWrapType)sampler.wrapT, - MinFilter = (TextureMinFilterType)sampler.minFilter, - MagFilter = (TextureMagFilterType)sampler.magFilter, - }; - } - - public static glTFTextureSampler ToGltf(this TextureSampler src) - { - return new glTFTextureSampler - { - wrapS = (glWrap)src.WrapS, - wrapT = (glWrap)src.WrapT, - minFilter = (glFilter)src.MinFilter, - magFilter = (glFilter)src.MagFilter, - }; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/Runtime/IO/TextureAdapter.cs.meta b/Assets/VRM10/Runtime/IO/TextureAdapter.cs.meta deleted file mode 100644 index f850f482d..000000000 --- a/Assets/VRM10/Runtime/IO/TextureAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7d307745b90c1da4297bba9f3ff4b325 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/UnityExtension.cs b/Assets/VRM10/Runtime/IO/UnityExtension.cs new file mode 100644 index 000000000..b0db79a14 --- /dev/null +++ b/Assets/VRM10/Runtime/IO/UnityExtension.cs @@ -0,0 +1,45 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using VrmLib; + +namespace UniVRM10 +{ + public static class UnityExtension + { + public static Vector3 ToUnityVector3(this System.Numerics.Vector3 value) + { + return new Vector3(value.X, value.Y, value.Z); + } + + public static float[] ToFloat3(this System.Numerics.Vector3 value) + { + return new[] { value.X, value.Y, value.Z }; + } + + public static Quaternion ToUnityQuaternion(this System.Numerics.Quaternion value) + { + return new Quaternion(value.X, value.Y, value.Z, value.W); + } + + public static float[] ToFloat4(this System.Numerics.Quaternion value) + { + return new float[] { value.X, value.Y, value.Z, value.W }; + } + + public static System.Numerics.Vector2 ToNumericsVector2(this Vector2 value) + { + return new System.Numerics.Vector2(value.x, value.y); + } + + public static System.Numerics.Vector3 ToNumericsVector3(this Vector3 value) + { + return new System.Numerics.Vector3(value.x, value.y, value.z); + } + + public static System.Numerics.Quaternion ToNumericsQuaternion(this Quaternion value) + { + return new System.Numerics.Quaternion(value.x, value.y, value.z, value.w); + } + } +} diff --git a/Assets/VRM10/Runtime/UnityBuilder/UnityExtension.cs.meta b/Assets/VRM10/Runtime/IO/UnityExtension.cs.meta similarity index 100% rename from Assets/VRM10/Runtime/UnityBuilder/UnityExtension.cs.meta rename to Assets/VRM10/Runtime/IO/UnityExtension.cs.meta diff --git a/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs b/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs index c0561cb56..2de6c1ae7 100644 --- a/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs +++ b/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using UniGLTF; using UniJSON; @@ -8,7 +7,7 @@ using VrmLib; namespace UniVRM10 { - public class Vrm10Exporter : IVrmExporter + public class Vrm10Exporter { public readonly Vrm10Storage Storage = new Vrm10Storage(); @@ -50,10 +49,6 @@ namespace UniVRM10 if (!string.IsNullOrEmpty(model.AssetMinVersion)) Storage.Gltf.asset.minVersion = model.AssetMinVersion; if (!string.IsNullOrEmpty(model.AssetGenerator)) Storage.Gltf.asset.generator = model.AssetGenerator; - if (model.Vrm != null && !string.IsNullOrEmpty(model.Vrm.ExporterVersion)) - { - Storage.Gltf.asset.generator = model.Vrm.ExporterVersion; - } if (!string.IsNullOrEmpty(model.AssetCopyright)) Storage.Gltf.asset.copyright = model.AssetCopyright; } @@ -63,68 +58,7 @@ namespace UniVRM10 Storage.Reserve(bytesLength); } - public void ExportImageAndTextures(List images, List textures) - { - foreach (var x in images) - { - Storage.Gltf.images.Add(x.ToGltf(Storage)); - } - foreach (var x in textures) - { - if (x is ImageTexture imageTexture) - { - var samplerIndex = Storage.Gltf.samplers.Count; - Storage.Gltf.samplers.Add(x.Sampler.ToGltf()); - Storage.Gltf.textures.Add(new glTFTexture - { - name = x.Name, - source = images.IndexOfThrow(imageTexture.Image), - sampler = samplerIndex, - // extensions - // = imageTexture.Image.MimeType.Equals("image/webp") ? new GltfTextureExtensions() { EXT_texture_webp = new EXT_texture_webp() { source = images.IndexOf(imageTexture.Image) } } - // : imageTexture.Image.MimeType.Equals("image/vnd-ms.dds") ? new GltfTextureExtensions() { MSFT_texture_dds = new MSFT_texture_dds() { source = images.IndexOf(imageTexture.Image) } } - // : null - }); - } - else - { - throw new NotImplementedException(); - } - } - } - - public void ExportMaterialPBR(Material src, PBRMaterial pbr, List textures) - { - var material = pbr.PBRToGltf(textures); - Storage.Gltf.materials.Add(material); - } - - public void ExportMaterialUnlit(Material src, UnlitMaterial unlit, List textures) - { - var material = unlit.UnlitToGltf(textures); - Storage.Gltf.materials.Add(material); - if (!Storage.Gltf.extensionsUsed.Contains(UnlitMaterial.ExtensionName)) - { - Storage.Gltf.extensionsUsed.Add(UnlitMaterial.ExtensionName); - } - } - - public void ExportMaterialMToon(Material src, MToonMaterial mtoon, List textures) - { - if (!Storage.Gltf.extensionsUsed.Contains(UnlitMaterial.ExtensionName)) - { - Storage.Gltf.extensionsUsed.Add(UnlitMaterial.ExtensionName); - } - - var material = mtoon.MToonToGltf(textures); - Storage.Gltf.materials.Add(material); - if (!Storage.Gltf.extensionsUsed.Contains(MToonMaterial.ExtensionName)) - { - Storage.Gltf.extensionsUsed.Add(MToonMaterial.ExtensionName); - } - } - - public void ExportMeshes(List groups, List materials, ExportArgs option) + public void ExportMeshes(List groups, List materials, ExportArgs option) { foreach (var group in groups) { @@ -184,140 +118,5 @@ namespace UniVRM10 nodes = root.Children.Select(child => nodes.IndexOfThrow(child)).ToArray() }); } - - public void ExportAnimations(List animations, List nodes, ExportArgs option) - { - // throw new System.NotImplementedException(); - } - - public void ExportVrmMeta(Vrm src, List textures) - { - if (!Storage.Gltf.extensionsUsed.Contains(VrmExtensionName)) - { - Storage.Gltf.extensionsUsed.Add(VrmExtensionName); - } - - if (Storage.gltfVrm == null) - { - Storage.gltfVrm = new UniGLTF.Extensions.VRMC_vrm.VRMC_vrm(); - } - - Storage.gltfVrm.SpecVersion = src.SpecVersion; - Storage.gltfVrm.Meta = src.Meta.ToGltf(textures); - } - - public void ExportVrmHumanoid(Dictionary map, List nodes) - { - Storage.gltfVrm.Humanoid = new UniGLTF.Extensions.VRMC_vrm.Humanoid() - { - HumanBones = new UniGLTF.Extensions.VRMC_vrm.HumanBones(), - }; - foreach (var kv in map.OrderBy(kv => kv.Key)) - { - var humanoidBone = new UniGLTF.Extensions.VRMC_vrm.HumanBone - { - Node = nodes.IndexOfThrow(kv.Value), - }; - - switch (kv.Key) - { - case HumanoidBones.hips: Storage.gltfVrm.Humanoid.HumanBones.Hips = humanoidBone; break; - case HumanoidBones.leftUpperLeg: Storage.gltfVrm.Humanoid.HumanBones.LeftUpperLeg = humanoidBone; break; - case HumanoidBones.rightUpperLeg: Storage.gltfVrm.Humanoid.HumanBones.RightUpperLeg = humanoidBone; break; - case HumanoidBones.leftLowerLeg: Storage.gltfVrm.Humanoid.HumanBones.LeftLowerLeg = humanoidBone; break; - case HumanoidBones.rightLowerLeg: Storage.gltfVrm.Humanoid.HumanBones.RightLowerLeg = humanoidBone; break; - case HumanoidBones.leftFoot: Storage.gltfVrm.Humanoid.HumanBones.LeftFoot = humanoidBone; break; - case HumanoidBones.rightFoot: Storage.gltfVrm.Humanoid.HumanBones.RightFoot = humanoidBone; break; - case HumanoidBones.spine: Storage.gltfVrm.Humanoid.HumanBones.Spine = humanoidBone; break; - case HumanoidBones.chest: Storage.gltfVrm.Humanoid.HumanBones.Chest = humanoidBone; break; - case HumanoidBones.neck: Storage.gltfVrm.Humanoid.HumanBones.Neck = humanoidBone; break; - case HumanoidBones.head: Storage.gltfVrm.Humanoid.HumanBones.Head = humanoidBone; break; - case HumanoidBones.leftShoulder: Storage.gltfVrm.Humanoid.HumanBones.LeftShoulder = humanoidBone; break; - case HumanoidBones.rightShoulder: Storage.gltfVrm.Humanoid.HumanBones.RightShoulder = humanoidBone; break; - case HumanoidBones.leftUpperArm: Storage.gltfVrm.Humanoid.HumanBones.LeftUpperArm = humanoidBone; break; - case HumanoidBones.rightUpperArm: Storage.gltfVrm.Humanoid.HumanBones.RightUpperArm = humanoidBone; break; - case HumanoidBones.leftLowerArm: Storage.gltfVrm.Humanoid.HumanBones.LeftLowerArm = humanoidBone; break; - case HumanoidBones.rightLowerArm: Storage.gltfVrm.Humanoid.HumanBones.RightLowerArm = humanoidBone; break; - case HumanoidBones.leftHand: Storage.gltfVrm.Humanoid.HumanBones.LeftHand = humanoidBone; break; - case HumanoidBones.rightHand: Storage.gltfVrm.Humanoid.HumanBones.RightHand = humanoidBone; break; - case HumanoidBones.leftToes: Storage.gltfVrm.Humanoid.HumanBones.LeftToes = humanoidBone; break; - case HumanoidBones.rightToes: Storage.gltfVrm.Humanoid.HumanBones.RightToes = humanoidBone; break; - case HumanoidBones.leftEye: Storage.gltfVrm.Humanoid.HumanBones.LeftEye = humanoidBone; break; - case HumanoidBones.rightEye: Storage.gltfVrm.Humanoid.HumanBones.RightEye = humanoidBone; break; - case HumanoidBones.jaw: Storage.gltfVrm.Humanoid.HumanBones.Jaw = humanoidBone; break; - case HumanoidBones.leftThumbProximal: Storage.gltfVrm.Humanoid.HumanBones.LeftThumbProximal = humanoidBone; break; - case HumanoidBones.leftThumbIntermediate: Storage.gltfVrm.Humanoid.HumanBones.LeftThumbIntermediate = humanoidBone; break; - case HumanoidBones.leftThumbDistal: Storage.gltfVrm.Humanoid.HumanBones.LeftThumbDistal = humanoidBone; break; - case HumanoidBones.leftIndexProximal: Storage.gltfVrm.Humanoid.HumanBones.LeftIndexProximal = humanoidBone; break; - case HumanoidBones.leftIndexIntermediate: Storage.gltfVrm.Humanoid.HumanBones.LeftIndexIntermediate = humanoidBone; break; - case HumanoidBones.leftIndexDistal: Storage.gltfVrm.Humanoid.HumanBones.LeftIndexDistal = humanoidBone; break; - case HumanoidBones.leftMiddleProximal: Storage.gltfVrm.Humanoid.HumanBones.LeftMiddleProximal = humanoidBone; break; - case HumanoidBones.leftMiddleIntermediate: Storage.gltfVrm.Humanoid.HumanBones.LeftMiddleIntermediate = humanoidBone; break; - case HumanoidBones.leftMiddleDistal: Storage.gltfVrm.Humanoid.HumanBones.LeftMiddleDistal = humanoidBone; break; - case HumanoidBones.leftRingProximal: Storage.gltfVrm.Humanoid.HumanBones.LeftRingProximal = humanoidBone; break; - case HumanoidBones.leftRingIntermediate: Storage.gltfVrm.Humanoid.HumanBones.LeftRingIntermediate = humanoidBone; break; - case HumanoidBones.leftRingDistal: Storage.gltfVrm.Humanoid.HumanBones.LeftRingDistal = humanoidBone; break; - case HumanoidBones.leftLittleProximal: Storage.gltfVrm.Humanoid.HumanBones.LeftLittleProximal = humanoidBone; break; - case HumanoidBones.leftLittleIntermediate: Storage.gltfVrm.Humanoid.HumanBones.LeftLittleIntermediate = humanoidBone; break; - case HumanoidBones.leftLittleDistal: Storage.gltfVrm.Humanoid.HumanBones.LeftLittleDistal = humanoidBone; break; - case HumanoidBones.rightThumbProximal: Storage.gltfVrm.Humanoid.HumanBones.RightThumbProximal = humanoidBone; break; - case HumanoidBones.rightThumbIntermediate: Storage.gltfVrm.Humanoid.HumanBones.RightThumbIntermediate = humanoidBone; break; - case HumanoidBones.rightThumbDistal: Storage.gltfVrm.Humanoid.HumanBones.RightThumbDistal = humanoidBone; break; - case HumanoidBones.rightIndexProximal: Storage.gltfVrm.Humanoid.HumanBones.RightIndexProximal = humanoidBone; break; - case HumanoidBones.rightIndexIntermediate: Storage.gltfVrm.Humanoid.HumanBones.RightIndexIntermediate = humanoidBone; break; - case HumanoidBones.rightIndexDistal: Storage.gltfVrm.Humanoid.HumanBones.RightIndexDistal = humanoidBone; break; - case HumanoidBones.rightMiddleProximal: Storage.gltfVrm.Humanoid.HumanBones.RightMiddleProximal = humanoidBone; break; - case HumanoidBones.rightMiddleIntermediate: Storage.gltfVrm.Humanoid.HumanBones.RightMiddleIntermediate = humanoidBone; break; - case HumanoidBones.rightMiddleDistal: Storage.gltfVrm.Humanoid.HumanBones.RightMiddleDistal = humanoidBone; break; - case HumanoidBones.rightRingProximal: Storage.gltfVrm.Humanoid.HumanBones.RightRingProximal = humanoidBone; break; - case HumanoidBones.rightRingIntermediate: Storage.gltfVrm.Humanoid.HumanBones.RightRingIntermediate = humanoidBone; break; - case HumanoidBones.rightRingDistal: Storage.gltfVrm.Humanoid.HumanBones.RightRingDistal = humanoidBone; break; - case HumanoidBones.rightLittleProximal: Storage.gltfVrm.Humanoid.HumanBones.RightLittleProximal = humanoidBone; break; - case HumanoidBones.rightLittleIntermediate: Storage.gltfVrm.Humanoid.HumanBones.RightLittleIntermediate = humanoidBone; break; - case HumanoidBones.rightLittleDistal: Storage.gltfVrm.Humanoid.HumanBones.RightLittleDistal = humanoidBone; break; - case HumanoidBones.upperChest: Storage.gltfVrm.Humanoid.HumanBones.UpperChest = humanoidBone; break; - } - - // gltfVrm.Humanoid.HumanBones.Add(kv.Key.ToString(), humanoidBone); - } - } - - public void ExportVrmExpression(ExpressionManager src, List _, List materials, List nodes) - { - if (Storage.gltfVrm.Expressions == null) - { - Storage.gltfVrm.Expressions = new List(); - } - foreach (var x in src.ExpressionList) - { - Storage.gltfVrm.Expressions.Add(x.ToGltf(nodes, materials)); - } - } - - public void ExportVrmSpringBone(SpringBoneManager springBone, List nodes) - { - Storage.gltfVrmSpringBone = springBone.ToGltf(nodes, Storage.Gltf.nodes); - } - - public void ExportVrmFirstPersonAndLookAt(FirstPerson firstPerson, LookAt lookat, List meshes, List nodes) - { - Storage.gltfVrm.FirstPerson = firstPerson.ToGltf(nodes); - Storage.gltfVrm.LookAt = lookat.ToGltf(); - } - - public void ExportVrmMaterialProperties(List materials, List textures) - { - // Do nothing - // see - // ExportMaterialPBR - // ExportMaterialUnlit - // ExportMaterialMToon - } - - public void ExportVrmEnd() - { - UniGLTF.Extensions.VRMC_vrm.GltfSerializer.SerializeTo(ref Storage.Gltf.extensions, Storage.gltfVrm); - UniGLTF.Extensions.VRMC_springBone.GltfSerializer.SerializeTo(ref Storage.Gltf.extensions, Storage.gltfVrmSpringBone); - } } } diff --git a/Assets/VRM10/Runtime/IO/Vrm10ExporterExtensions.cs b/Assets/VRM10/Runtime/IO/Vrm10ExporterExtensions.cs new file mode 100644 index 000000000..b16c742ac --- /dev/null +++ b/Assets/VRM10/Runtime/IO/Vrm10ExporterExtensions.cs @@ -0,0 +1,51 @@ +using System; +using VrmLib; + +namespace UniVRM10 +{ + public static class IExporterExtensions + { + public static byte[] Export(this Vrm10Exporter exporter, Model m, ExportArgs option) + { + exporter.ExportAsset(m); + + /// + /// 必要な容量を先に確保 + /// (sparseは考慮してないので大きめ) + /// + { + var reserveBytes = 0; + // mesh + foreach (var g in m.MeshGroups) + { + foreach (var mesh in g.Meshes) + { + // 頂点バッファ + reserveBytes += mesh.IndexBuffer.ByteLength; + foreach (var kv in mesh.VertexBuffer) + { + reserveBytes += kv.Value.ByteLength; + } + // morph + foreach (var morph in mesh.MorphTargets) + { + foreach (var kv in morph.VertexBuffer) + { + reserveBytes += kv.Value.ByteLength; + } + } + } + } + exporter.Reserve(reserveBytes); + } + + // mesh + exporter.ExportMeshes(m.MeshGroups, m.Materials, option); + + // node + exporter.ExportNodes(m.Root, m.Nodes, m.MeshGroups, option); + + return exporter.ToBytes(); + } + } +} diff --git a/Assets/VRM10/Runtime/IO/Vrm10ExporterExtensions.cs.meta b/Assets/VRM10/Runtime/IO/Vrm10ExporterExtensions.cs.meta new file mode 100644 index 000000000..88fdbfa52 --- /dev/null +++ b/Assets/VRM10/Runtime/IO/Vrm10ExporterExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 984cd6e6d31fcc348a71adee5a752400 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/Vrm10MToonMaterialImporter.cs b/Assets/VRM10/Runtime/IO/Vrm10MToonMaterialImporter.cs new file mode 100644 index 000000000..de563072c --- /dev/null +++ b/Assets/VRM10/Runtime/IO/Vrm10MToonMaterialImporter.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using UniGLTF; +using UnityEngine; +using VRMShaders; + + +namespace UniVRM10 +{ + public static class Vrm10MToonMaterialImporter + { + public static Color ToColor4(this float[] src, Color defaultValue = default) + { + if (src == null || src.Length != 4) + { + throw new NotImplementedException(); + } + + var v = new Vector4( + src[0], + src[1], + src[2], + src[3] + ); + return v; + } + public static Color ToColor3(this float[] src, Color defaultValue = default) + { + if (src == null || src.Length != 3) + { + throw new NotImplementedException(); + } + + var v = new Vector4( + src[0], + src[1], + src[2] + ); + return v; + } + + /// + /// VMRC_materials_mtoon の場合にマテリアル生成情報を作成する + /// + /// + /// + /// + /// + public static bool TryCreateParam(GltfParser parser, int i, out MaterialImportParam param) + { + var m = parser.GLTF.materials[i]; + if (!UniGLTF.Extensions.VRMC_materials_mtoon.GltfDeserializer.TryGet(m.extensions, + out UniGLTF.Extensions.VRMC_materials_mtoon.VRMC_materials_mtoon mtoon)) + { + // fallback to gltf + param = default; + return false; + } + + // use material.name, because material name may renamed in GltfParser. + param = new MaterialImportParam(m.name, MToon.Utils.ShaderName); + + param.Actions.Add(material => + { + // Texture 以外をここで設定。Texture は TextureSlots へ + { + // material.SetFloat(PropVersion, mtoon.Version); + } + { + // var rendering = mtoon.Rendering; + // SetRenderMode(material, rendering.RenderMode, rendering.RenderQueueOffsetNumber, + // useDefaultRenderQueue: false); + // SetCullMode(material, rendering.CullMode); + } + { + // var color = mtoon.Color; + material.SetColor(MToon.Utils.PropColor, m.pbrMetallicRoughness.baseColorFactor.ToColor4()); + material.SetColor(MToon.Utils.PropShadeColor, mtoon.ShadeFactor.ToColor3()); + material.SetFloat(MToon.Utils.PropCutoff, m.alphaCutoff); + } + { + { + material.SetFloat(MToon.Utils.PropShadeShift, mtoon.ShadingShiftFactor.Value); + material.SetFloat(MToon.Utils.PropShadeToony, mtoon.ShadingToonyFactor.Value); + // material.SetFloat(PropReceiveShadowRate, mtoon.prop.ShadowReceiveMultiplierValue); + // material.SetFloat(PropShadingGradeRate, mtoon.mix prop.LitAndShadeMixingMultiplierValue); + } + { + material.SetFloat(MToon.Utils.PropLightColorAttenuation, mtoon.LightColorAttenuationFactor.Value); + material.SetFloat(MToon.Utils.PropIndirectLightIntensity, mtoon.GiIntensityFactor.Value); + } + } + { + material.SetColor(MToon.Utils.PropEmissionColor, m.emissiveFactor.ToColor3()); + } + { + material.SetColor(MToon.Utils.PropRimColor, mtoon.RimFactor.ToColor3()); + material.SetFloat(MToon.Utils.PropRimLightingMix, mtoon.RimLightingMixFactor.Value); + material.SetFloat(MToon.Utils.PropRimFresnelPower, mtoon.RimFresnelPowerFactor.Value); + material.SetFloat(MToon.Utils.PropRimLift, mtoon.RimLiftFactor.Value); + } + { + material.SetFloat(MToon.Utils.PropOutlineWidth, mtoon.OutlineWidthFactor.Value); + material.SetFloat(MToon.Utils.PropOutlineScaledMaxDistance, mtoon.OutlineScaledMaxDistanceFactor.Value); + material.SetColor(MToon.Utils.PropOutlineColor, mtoon.OutlineFactor.ToColor3()); + material.SetFloat(MToon.Utils.PropOutlineLightingMix, mtoon.OutlineLightingMixFactor.Value); + // private + // MToon.Utils.SetOutlineMode(material, outline.OutlineWidthMode, outline.OutlineColorMode); + } + { + // material.SetTextureScale(PropMainTex, mtoon.MainTextureLeftBottomOriginScale); + // material.SetTextureOffset(PropMainTex, mtoon.MainTextureLeftBottomOriginOffset); + material.SetFloat(MToon.Utils.PropUvAnimScrollX, mtoon.UvAnimationScrollXSpeedFactor.Value); + material.SetFloat(MToon.Utils.PropUvAnimScrollY, mtoon.UvAnimationScrollYSpeedFactor.Value); + material.SetFloat(MToon.Utils.PropUvAnimRotation, mtoon.UvAnimationRotationSpeedFactor.Value); + } + + MToon.Utils.ValidateProperties(material, isBlendModeChangedByUser: false); + }); + + // SetTexture(material, PropMainTex, color.LitMultiplyTexture); + // SetNormalMapping(material, prop.NormalTexture, prop.NormalScaleValue); + // SetTexture(material, PropEmissionMap, emission.EmissionMultiplyTexture); + + if (m.pbrMetallicRoughness != null) + { + // base color + if (m.pbrMetallicRoughness?.baseColorTexture != null) + { + param.TextureSlots.Add("_MainTex", GltfPBRMaterial.BaseColorTexture(parser, m)); + } + } + + if (m.normalTexture != null && m.normalTexture.index != -1) + { + // normal map + param.Actions.Add(material => material.EnableKeyword("_NORMALMAP")); + var textureParam = GltfPBRMaterial.NormalTexture(parser, m); + param.TextureSlots.Add("_BumpMap", textureParam); + param.FloatValues.Add("_BumpScale", m.normalTexture.scale); + } + + if (m.emissiveTexture != null && m.emissiveTexture.index != -1) + { + var (offset, scale) = GltfMaterialImporter.GetTextureOffsetAndScale(m.emissiveTexture); + var textureParam = GltfTextureImporter.CreateSRGB(parser, m.emissiveTexture.index, offset, scale); + param.TextureSlots.Add("_EmissionMap", textureParam); + } + + // TODO: + if (mtoon.ShadeMultiplyTexture.HasValue) + { + var textureParam = GltfTextureImporter.CreateSRGB(parser, mtoon.ShadeMultiplyTexture.Value, Vector2.zero, Vector2.one); + param.TextureSlots.Add("_ShadeTexture", textureParam); + } + if (mtoon.OutlineWidthMultiplyTexture.HasValue) + { + var textureParam = GltfTextureImporter.CreateSRGB(parser, mtoon.OutlineWidthMultiplyTexture.Value, Vector2.zero, Vector2.one); + param.TextureSlots.Add("_OutlineWidthTexture", textureParam); + } + if (mtoon.AdditiveTexture.HasValue) + { + var textureParam = GltfTextureImporter.CreateSRGB(parser, mtoon.AdditiveTexture.Value, Vector2.zero, Vector2.one); + param.TextureSlots.Add("_SphereAdd", textureParam); + } + if (mtoon.RimMultiplyTexture.HasValue) + { + var textureParam = GltfTextureImporter.CreateSRGB(parser, mtoon.RimMultiplyTexture.Value, Vector2.zero, Vector2.one); + param.TextureSlots.Add("_RimTexture", textureParam); ; + } + if (mtoon.UvAnimationMaskTexture.HasValue) + { + var textureParam = GltfTextureImporter.CreateSRGB(parser, mtoon.UvAnimationMaskTexture.Value, Vector2.zero, Vector2.one); + param.TextureSlots.Add("_UvAnimMaskTexture", textureParam); + } + + return true; + } + + /// + /// Material一つ分のテクスチャーを列挙する。重複する場合がある + /// + /// + /// + /// + public static IEnumerable EnumerateTexturesForMaterial(GltfParser parser, int i) + { + // mtoon + if (!TryCreateParam(parser, i, out MaterialImportParam param)) + { + // unlit + if (!GltfUnlitMaterial.TryCreateParam(parser, i, out param)) + { + // pbr + GltfPBRMaterial.TryCreateParam(parser, i, out param); + } + } + + foreach (var kv in param.TextureSlots) + { + yield return kv.Value; + } + } + + /// + /// VRM-1 の thumbnail テクスチャー。gltf.textures ではなく gltf.images の参照であることに注意(sampler等の設定が無い) + /// + /// MToonとは無関係だがとりあえずここに + /// + /// + /// + /// + /// + public static bool TryGetMetaThumbnailTextureImportParam(GltfParser parser, UniGLTF.Extensions.VRMC_vrm.VRMC_vrm vrm, out TextureImportParam value) + { + if (!vrm.Meta.ThumbnailImage.HasValue) + { + value = default; + return false; + } + + // thumbnail + var imageIndex = vrm.Meta.ThumbnailImage.Value; + var gltfImage = parser.GLTF.images[imageIndex]; + var name = new TextureImportName(TextureImportTypes.sRGB, gltfImage.name, gltfImage.GetExt(), ""); + + GetTextureBytesAsync getBytesAsync = () => + { + var bytes = parser.GLTF.GetImageBytes(parser.Storage, imageIndex); + return Task.FromResult(GltfTextureImporter.ToArray(bytes)); + }; + value = new TextureImportParam(name, Vector2.zero, Vector2.one, default, TextureImportTypes.sRGB, default, default, + getBytesAsync, default, default, + default, default, default + ); + return true; + } + + /// + /// glTF 全体で使うテクスチャーをユニークになるように列挙する + /// + /// + /// + public static IEnumerable EnumerateAllTexturesDistinct(GltfParser parser) + { + if (!UniGLTF.Extensions.VRMC_vrm.GltfDeserializer.TryGet(parser.GLTF.extensions, out UniGLTF.Extensions.VRMC_vrm.VRMC_vrm vrm)) + { + throw new System.Exception("not vrm"); + } + + if (TryGetMetaThumbnailTextureImportParam(parser, vrm, out TextureImportParam thumbnail)) + { + yield return thumbnail; + } + + var used = new HashSet(); + for (int i = 0; i < parser.GLTF.materials.Count; ++i) + { + foreach (var textureInfo in EnumerateTexturesForMaterial(parser, i)) + { + if (used.Add(textureInfo.ExtractKey)) + { + yield return textureInfo; + } + } + } + } + } +} diff --git a/Assets/VRM10/Runtime/IO/Vrm10MToonMaterialImporter.cs.meta b/Assets/VRM10/Runtime/IO/Vrm10MToonMaterialImporter.cs.meta new file mode 100644 index 000000000..22b07f75f --- /dev/null +++ b/Assets/VRM10/Runtime/IO/Vrm10MToonMaterialImporter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7adf33b35bd23f2478d7c1071bc54d0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/Vrm10Storage.cs b/Assets/VRM10/Runtime/IO/Vrm10Storage.cs index 7faa0ea0c..cf055abe5 100644 --- a/Assets/VRM10/Runtime/IO/Vrm10Storage.cs +++ b/Assets/VRM10/Runtime/IO/Vrm10Storage.cs @@ -4,21 +4,16 @@ using System.Linq; using System.Numerics; using System.Runtime.InteropServices; using VrmLib; -using UniJSON; namespace UniVRM10 { - public class Vrm10Storage : IVrmStorage + public class Vrm10Storage { - public ArraySegment OriginalJson { get; private set; } - public UniGLTF.glTF Gltf - { - get; - private set; - } + UniGLTF.GltfParser m_parser; + public UniGLTF.glTF Gltf => m_parser.GLTF; - public readonly List Buffers; + public List Buffers; public UniGLTF.Extensions.VRMC_vrm.VRMC_vrm gltfVrm; @@ -29,13 +24,16 @@ namespace UniVRM10 /// public Vrm10Storage() { - Gltf = new UniGLTF.glTF() + m_parser = new UniGLTF.GltfParser { - extensionsUsed = new List(), + GLTF = new UniGLTF.glTF() + { + extensionsUsed = new List(), + } }; - Buffers = new List() + Buffers = new List() { - new ArrayByteBuffer10() + new UniGLTF.ArrayByteBuffer() }; } @@ -44,10 +42,9 @@ namespace UniVRM10 /// /// /// - public Vrm10Storage(ArraySegment json, ArraySegment bin) + public Vrm10Storage(UniGLTF.GltfParser parser) { - OriginalJson = json; - Gltf = UniGLTF.GltfDeserializer.Deserialize(json.ParseAsJson()); + m_parser = parser; if (UniGLTF.Extensions.VRMC_vrm.GltfDeserializer.TryGet(Gltf.extensions, out UniGLTF.Extensions.VRMC_vrm.VRMC_vrm vrm)) @@ -61,10 +58,9 @@ namespace UniVRM10 gltfVrmSpringBone = springBone; } - var array = bin.ToArray(); - Buffers = new List() + Buffers = new List() { - new ArrayByteBuffer10(array, bin.Count) + Gltf.buffers[0].Buffer, }; } @@ -73,16 +69,11 @@ namespace UniVRM10 Buffers[0].ExtendCapacity(bytesLength); } - public int AppendToBuffer(int bufferIndex, ArraySegment segment, int stride) + public int AppendToBuffer(int bufferIndex, ArraySegment segment) { - Buffers[bufferIndex].Extend(segment, stride, out int offset, out int length); + var gltfBufferView = Buffers[bufferIndex].Extend(segment); var viewIndex = Gltf.bufferViews.Count; - Gltf.bufferViews.Add(new UniGLTF.glTFBufferView - { - buffer = 0, - byteOffset = offset, - byteLength = length, - }); + Gltf.bufferViews.Add(gltfBufferView); return viewIndex; } @@ -327,14 +318,6 @@ namespace UniVRM10 } } - public void CreateBufferAccessorAndAdd(int? accessorIndex, VertexBuffer b, string key) - { - if (accessorIndex.HasValue) - { - CreateBufferAccessorAndAdd(accessorIndex.Value, b, key); - } - } - public void CreateBufferAccessorAndAdd(int accessorIndex, VertexBuffer b, string key) { var a = CreateAccessor(accessorIndex); @@ -381,25 +364,12 @@ namespace UniVRM10 public int NodeCount => Gltf.nodes.Count; - public int ImageCount => Gltf.images.Count; - public int TextureCount => Gltf.textures.Count; - public int MaterialCount => Gltf.materials.Count; - public int SkinCount => Gltf.skins.Count; public int MeshCount => Gltf.meshes.Count; - // TODO: - public int AnimationCount => 0; - - public string VrmExporterVersion => Gltf.asset.generator; - - public bool HasVrm => gltfVrm != null; - - public string VrmSpecVersion => gltfVrm?.SpecVersion; - public Node CreateNode(int index) { var x = Gltf.nodes[index]; @@ -449,114 +419,6 @@ namespace UniVRM10 } } - public Image CreateImage(int index) - { - return Gltf.images[index].FromGltf(this); - } - - /// - /// sRGB でないテクスチャーを検出する - /// - /// - /// - private (Texture.TextureTypes, UniGLTF.glTFMaterial) GetTextureType(int textureIndex) - { - foreach (var material in Gltf.materials) - { - if (UniGLTF.Extensions.VRMC_materials_mtoon.GltfDeserializer.TryGet(material.extensions, - out UniGLTF.Extensions.VRMC_materials_mtoon.VRMC_materials_mtoon mtoon)) - { - if (material.normalTexture?.index == textureIndex) return (Texture.TextureTypes.NormalMap, material); - } - else if (UniGLTF.glTF_KHR_materials_unlit.IsEnable(material)) - { - } - else - { - if (material.pbrMetallicRoughness?.baseColorTexture?.index == textureIndex) return (Texture.TextureTypes.Default, material); - if (material.pbrMetallicRoughness?.metallicRoughnessTexture?.index == textureIndex) return (Texture.TextureTypes.MetallicRoughness, material); - if (material.occlusionTexture?.index == textureIndex) return (Texture.TextureTypes.Occlusion, material); - if (material.emissiveTexture?.index == textureIndex) return (Texture.TextureTypes.Emissive, material); - if (material.normalTexture?.index == textureIndex) return (Texture.TextureTypes.NormalMap, material); - } - } - - return (Texture.TextureTypes.Default, null); - } - - private Texture.ColorSpaceTypes GetTextureColorSpaceType(int textureIndex) - { - foreach (var material in Gltf.materials) - { - if (UniGLTF.Extensions.VRMC_materials_mtoon.GltfDeserializer.TryGet(material.extensions, - out UniGLTF.Extensions.VRMC_materials_mtoon.VRMC_materials_mtoon mtoon)) - { - // mtoon - if (material.pbrMetallicRoughness.baseColorTexture.index == textureIndex) return Texture.ColorSpaceTypes.Srgb; - if (mtoon.ShadeMultiplyTexture == textureIndex) return Texture.ColorSpaceTypes.Srgb; - if (material.emissiveTexture?.index == textureIndex) return Texture.ColorSpaceTypes.Srgb; - if (mtoon.RimMultiplyTexture == textureIndex) return Texture.ColorSpaceTypes.Srgb; - if (mtoon.AdditiveTexture == textureIndex) return Texture.ColorSpaceTypes.Srgb; - - if (mtoon.OutlineWidthMultiplyTexture == textureIndex) return Texture.ColorSpaceTypes.Linear; - if (mtoon.UvAnimationMaskTexture == textureIndex) return Texture.ColorSpaceTypes.Linear; - - if (material.normalTexture?.index == textureIndex) return Texture.ColorSpaceTypes.Linear; - } - else if (UniGLTF.glTF_KHR_materials_unlit.IsEnable(material)) - { - // unlit - if (material.pbrMetallicRoughness.baseColorTexture?.index == textureIndex) return Texture.ColorSpaceTypes.Srgb; - } - else - { - // Pbr - if (material.pbrMetallicRoughness?.baseColorTexture?.index == textureIndex) return Texture.ColorSpaceTypes.Srgb; - if (material.pbrMetallicRoughness?.metallicRoughnessTexture?.index == textureIndex) return Texture.ColorSpaceTypes.Linear; - if (material.occlusionTexture?.index == textureIndex) return Texture.ColorSpaceTypes.Linear; - if (material.emissiveTexture?.index == textureIndex) return Texture.ColorSpaceTypes.Srgb; - if (material.normalTexture?.index == textureIndex) return Texture.ColorSpaceTypes.Linear; - } - } - - return Texture.ColorSpaceTypes.Srgb; - } - - public Texture CreateTexture(int index, List images) - { - var texture = Gltf.textures[index]; - var textureType = GetTextureType(index); - var colorSpace = GetTextureColorSpaceType(index); - - var sampler = (texture.sampler >= 0 && texture.sampler < Gltf.samplers.Count) - ? Gltf.samplers[texture.sampler] - : new UniGLTF.glTFTextureSampler() - ; - - if (textureType.Item1 == Texture.TextureTypes.MetallicRoughness && textureType.Item2.pbrMetallicRoughness != null) - { - var roughnessFactor = textureType.Item2.pbrMetallicRoughness.roughnessFactor; - var name = !string.IsNullOrEmpty(texture.name) ? texture.name : images[texture.source].Name; - return new MetallicRoughnessImageTexture( - name, - sampler.FromGltf(), - images[texture.source], - roughnessFactor, - colorSpace, - textureType.Item1); - } - else - { - return texture.FromGltf(sampler, images, colorSpace, textureType.Item1); - } - } - - public Material CreateMaterial(int index, List textures) - { - var x = Gltf.materials[index]; - return x.FromGltf(textures); - } - public Skin CreateSkin(int index, List nodes) { var x = Gltf.skins[index]; @@ -577,10 +439,10 @@ namespace UniVRM10 return skin; } - public MeshGroup CreateMesh(int index, List materials) + public MeshGroup CreateMesh(int index) { var x = Gltf.meshes[index]; - var group = x.FromGltf(this, materials); + var group = x.FromGltf(this); return group; } @@ -603,197 +465,6 @@ namespace UniVRM10 return (meshIndex, skinIndex); } - public Animation CreateAnimation(int index, List nodes) - { - throw new NotImplementedException(); - } - - public Meta CreateVrmMeta(List textures) - { - return gltfVrm.Meta.FromGltf(textures); - } - - static void AssignHumanoid(List nodes, UniGLTF.Extensions.VRMC_vrm.HumanBone humanBone, VrmLib.HumanoidBones key) - { - if (humanBone != null && humanBone.Node.HasValue) - { - nodes[humanBone.Node.Value].HumanoidBone = key; - } - } - - public void LoadVrmHumanoid(List nodes) - { - if (gltfVrm.Humanoid != null) - { - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.Hips, HumanoidBones.hips); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftUpperLeg, HumanoidBones.leftUpperLeg); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightUpperLeg, HumanoidBones.rightUpperLeg); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftLowerLeg, HumanoidBones.leftLowerLeg); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightLowerLeg, HumanoidBones.rightLowerLeg); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftFoot, HumanoidBones.leftFoot); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightFoot, HumanoidBones.rightFoot); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.Spine, HumanoidBones.spine); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.Chest, HumanoidBones.chest); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.Neck, HumanoidBones.neck); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.Head, HumanoidBones.head); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftShoulder, HumanoidBones.leftShoulder); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightShoulder, HumanoidBones.rightShoulder); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftUpperArm, HumanoidBones.leftUpperArm); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightUpperArm, HumanoidBones.rightUpperArm); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftLowerArm, HumanoidBones.leftLowerArm); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightLowerArm, HumanoidBones.rightLowerArm); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftHand, HumanoidBones.leftHand); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightHand, HumanoidBones.rightHand); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftToes, HumanoidBones.leftToes); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightToes, HumanoidBones.rightToes); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftEye, HumanoidBones.leftEye); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightEye, HumanoidBones.rightEye); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.Jaw, HumanoidBones.jaw); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftThumbProximal, HumanoidBones.leftThumbProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftThumbIntermediate, HumanoidBones.leftThumbIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftThumbDistal, HumanoidBones.leftThumbDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftIndexProximal, HumanoidBones.leftIndexProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftIndexIntermediate, HumanoidBones.leftIndexIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftIndexDistal, HumanoidBones.leftIndexDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftMiddleProximal, HumanoidBones.leftMiddleProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftMiddleIntermediate, HumanoidBones.leftMiddleIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftMiddleDistal, HumanoidBones.leftMiddleDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftRingProximal, HumanoidBones.leftRingProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftRingIntermediate, HumanoidBones.leftRingIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftRingDistal, HumanoidBones.leftRingDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftLittleProximal, HumanoidBones.leftLittleProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftLittleIntermediate, HumanoidBones.leftLittleIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.LeftLittleDistal, HumanoidBones.leftLittleDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightThumbProximal, HumanoidBones.rightThumbProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightThumbIntermediate, HumanoidBones.rightThumbIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightThumbDistal, HumanoidBones.rightThumbDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightIndexProximal, HumanoidBones.rightIndexProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightIndexIntermediate, HumanoidBones.rightIndexIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightIndexDistal, HumanoidBones.rightIndexDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightMiddleProximal, HumanoidBones.rightMiddleProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightMiddleIntermediate, HumanoidBones.rightMiddleIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightMiddleDistal, HumanoidBones.rightMiddleDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightRingProximal, HumanoidBones.rightRingProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightRingIntermediate, HumanoidBones.rightRingIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightRingDistal, HumanoidBones.rightRingDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightLittleProximal, HumanoidBones.rightLittleProximal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightLittleIntermediate, HumanoidBones.rightLittleIntermediate); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.RightLittleDistal, HumanoidBones.rightLittleDistal); - AssignHumanoid(nodes, gltfVrm.Humanoid.HumanBones.UpperChest, HumanoidBones.upperChest); - } - } - - public ExpressionManager CreateVrmExpression(List _, List materials, List nodes) - { - if (gltfVrm.Expressions != null) - { - var expressionManager = new ExpressionManager(); - foreach (var x in gltfVrm.Expressions) - { - expressionManager.ExpressionList.Add(x.FromGltf(nodes, materials)); - } - return expressionManager; - } - - return null; - } - - static VrmSpringBoneCollider CreateCollider(UniGLTF.Extensions.VRMC_node_collider.ColliderShape z) - { - if (z.Sphere != null) - { - return VrmSpringBoneCollider.CreateSphere(z.Sphere.Offset.ToVector3(), z.Sphere.Radius.Value); - } - if (z.Capsule != null) - { - return VrmSpringBoneCollider.CreateCapsule(z.Capsule.Offset.ToVector3(), z.Capsule.Radius.Value, z.Capsule.Tail.ToVector3()); - } - throw new NotImplementedException(); - } - - public SpringBoneManager CreateVrmSpringBone(List nodes) - { - if ((gltfVrmSpringBone is null)) - { - return null; - } - - var springBoneManager = new SpringBoneManager(); - - // springs - if (gltfVrmSpringBone.Springs != null) - { - foreach (var gltfSpring in gltfVrmSpringBone.Springs) - { - var springBone = new SpringBone(); - springBone.Comment = gltfSpring.Name; - - // joint - foreach (var gltfJoint in gltfSpring.Joints) - { - var joint = new SpringJoint(nodes[gltfJoint.Node.Value]); - joint.HitRadius = gltfJoint.HitRadius.Value; - joint.DragForce = gltfJoint.DragForce.Value; - joint.GravityDir = gltfJoint.GravityDir.ToVector3(); - joint.GravityPower = gltfJoint.GravityPower.Value; - joint.Stiffness = gltfJoint.Stiffness.Value; - springBone.Joints.Add(joint); - } - - // collider - springBone.Colliders.AddRange(gltfSpring.Colliders.Select(colliderNode => - { - if (UniGLTF.Extensions.VRMC_node_collider.GltfDeserializer.TryGet(Gltf.nodes[colliderNode].extensions, - out UniGLTF.Extensions.VRMC_node_collider.VRMC_node_collider extension)) - { - var collider = new SpringBoneColliderGroup(nodes[colliderNode], extension.Shapes.Select(x => - { - if (x.Sphere != null) - { - return VrmSpringBoneCollider.CreateSphere(x.Sphere.Offset.ToVector3(), x.Sphere.Radius.Value); - } - else if (x.Capsule != null) - { - return VrmSpringBoneCollider.CreateCapsule(x.Capsule.Offset.ToVector3(), x.Capsule.Radius.Value, x.Capsule.Tail.ToVector3()); - } - else - { - throw new NotImplementedException(); - } - })); - return collider; - } - else - { - return null; - } - }).Where(x => x != null)); - - springBoneManager.Springs.Add(springBone); - } - } - - return springBoneManager; - } - - public FirstPerson CreateVrmFirstPerson(List nodes, List meshGroups) - { - if (gltfVrm.FirstPerson == null) - { - return null; - } - return gltfVrm.FirstPerson.FromGltf(nodes); - } - - public LookAt CreateVrmLookAt() - { - if (gltfVrm.LookAt == null) - { - return null; - } - return gltfVrm.LookAt.FromGltf(); - } - public ArraySegment GetBufferBytes(UniGLTF.glTFBufferView bufferView) { if (!bufferView.buffer.TryGetValidIndex(Gltf.buffers.Count, out int bufferViewBufferIndex)) @@ -809,4 +480,4 @@ namespace UniVRM10 return Buffers[index].Bytes; } } -} \ No newline at end of file +} diff --git a/Assets/VRM10/Runtime/IO/VrmExpressionAdapter.cs b/Assets/VRM10/Runtime/IO/VrmExpressionAdapter.cs deleted file mode 100644 index 8a8512b67..000000000 --- a/Assets/VRM10/Runtime/IO/VrmExpressionAdapter.cs +++ /dev/null @@ -1,236 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Numerics; -using VrmLib; - -namespace UniVRM10 -{ - public static class ExpressionAdapter - { - public static VrmLib.Expression FromGltf(this UniGLTF.Extensions.VRMC_vrm.Expression x, List nodes, List materials) - { - var expression = new VrmLib.Expression(x.Preset.ToVrmFormat(), - x.Name, - x.IsBinary.HasValue && x.IsBinary.Value) - { - OverrideBlink = EnumUtil.Cast(x.OverrideBlink), - OverrideLookAt = EnumUtil.Cast(x.OverrideLookAt), - OverrideMouth = EnumUtil.Cast(x.OverrideMouth), - }; - - if (x.MorphTargetBinds != null) - { - foreach (var y in x.MorphTargetBinds) - { - var node = nodes[y.Node.Value]; - var blendShapeName = node.Mesh.MorphTargets[y.Index.Value].Name; - var blendShapeBind = new MorphTargetBind(node, blendShapeName, y.Weight.Value); - expression.MorphTargetBinds.Add(blendShapeBind); - } - } - - if (x.MaterialColorBinds != null) - { - foreach (var y in x.MaterialColorBinds) - { - var material = materials[y.Material.Value]; - var materialColorBind = new MaterialColorBind(material, EnumUtil.Cast(y.Type), y.TargetValue.ToVector4(Vector4.Zero)); - expression.MaterialColorBinds.Add(materialColorBind); - } - } - - if (x.TextureTransformBinds != null) - { - foreach (var y in x.TextureTransformBinds) - { - var material = materials[y.Material.Value]; - var materialUVBind = new TextureTransformBind(material, - y.Scaling.ToVector2(Vector2.One), - y.Offset.ToVector2(Vector2.Zero)); - expression.TextureTransformBinds.Add(materialUVBind); - } - } - - return expression; - } - // public static ExpressionManager FromGltf(this UniGLTF.VRMC_vrm.Expression master, List nodes, List materials) - // { - // var manager = new ExpressionManager(); - // foreach (var x in master.BlendShapeGroups) - // { - // VrmLib.Expression expression = FromGltf(x, nodes, materials); - - // manager.ExpressionList.Add(expression); - // }; - // return manager; - // } - - public static UniGLTF.Extensions.VRMC_vrm.MorphTargetBind ToGltf(this MorphTargetBind self, List nodes) - { - var name = self.Name; - var value = self.Value; - var index = self.Node.Mesh.MorphTargets.FindIndex(x => x.Name == name); - if (index < 0) - { - throw new IndexOutOfRangeException(string.Format("MorphTargetName {0} is not found", name)); - } - - return new UniGLTF.Extensions.VRMC_vrm.MorphTargetBind - { - Node = nodes.IndexOfThrow(self.Node), - Index = self.Node.Mesh.MorphTargets.FindIndex(x => x.Name == name), - Weight = value, - }; - } - - public static UniGLTF.Extensions.VRMC_vrm.MaterialColorBind ToGltf(this MaterialColorBind self, List materials) - { - var m = new UniGLTF.Extensions.VRMC_vrm.MaterialColorBind - { - Material = materials.IndexOfThrow(self.Material), - Type = EnumUtil.Cast(self.BindType), - TargetValue = self.Property.Value.ToFloat4() - }; - return m; - } - - public static UniGLTF.Extensions.VRMC_vrm.TextureTransformBind ToGltf(this TextureTransformBind self, List materials) - { - var m = new UniGLTF.Extensions.VRMC_vrm.TextureTransformBind - { - Material = materials.IndexOfThrow(self.Material), - Scaling = self.Scale.ToFloat2(), - Offset = self.Offset.ToFloat2(), - }; - return m; - } - - public static UniGLTF.Extensions.VRMC_vrm.Expression ToGltf(this VrmLib.Expression x, List nodes, List materials) - { - var g = new UniGLTF.Extensions.VRMC_vrm.Expression - { - Preset = x.Preset.ToGltfFormat(), - Name = x.Name, - IsBinary = x.IsBinary, - OverrideBlink = EnumUtil.Cast(x.OverrideBlink), - OverrideLookAt = EnumUtil.Cast(x.OverrideLookAt), - OverrideMouth = EnumUtil.Cast(x.OverrideMouth), - }; - - g.MorphTargetBinds = new List(); - foreach (var blendShapeBind in x.MorphTargetBinds) - { - g.MorphTargetBinds.Add(blendShapeBind.ToGltf(nodes)); - } - - g.MaterialColorBinds = new List(); - foreach (var materialColorBind in x.MaterialColorBinds) - { - g.MaterialColorBinds.Add(materialColorBind.ToGltf(materials)); - } - - g.TextureTransformBinds = new List(); - foreach (var materialUVBind in x.TextureTransformBinds) - { - g.TextureTransformBinds.Add(materialUVBind.ToGltf(materials)); - } - - return g; - } - - // public static UniGLTF.VRMC_vrm.BlendShape ToGltf(this ExpressionManager src, List nodes, List materials) - // { - // var blendShape = new UniGLTF.VRMC_vrm.BlendShape - // { - // }; - // if (src != null) - // { - // foreach (var x in src.ExpressionList) - // { - // blendShape.BlendShapeGroups.Add(x.ToGltf(nodes, materials)); - // } - // } - // return blendShape; - // } - - private static UniGLTF.Extensions.VRMC_vrm.ExpressionPreset ToGltfFormat(this VrmLib.ExpressionPreset preset) - { - switch (preset) - { - case ExpressionPreset.Custom: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.custom; - // 喜怒哀楽驚 - case ExpressionPreset.Happy: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.happy; - case ExpressionPreset.Angry: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.angry; - case ExpressionPreset.Sad: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.sad; - case ExpressionPreset.Relaxed: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.relaxed; - case ExpressionPreset.Surprised: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.surprised; - // Procedural(LipSync) - case ExpressionPreset.Aa: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.aa; - case ExpressionPreset.Ih: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ih; - case ExpressionPreset.Ou: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ou; - case ExpressionPreset.Ee: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ee; - case ExpressionPreset.Oh: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.oh; - // Procedural(Blink) - case ExpressionPreset.Blink: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blink; - case ExpressionPreset.BlinkLeft: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blinkLeft; - case ExpressionPreset.BlinkRight: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blinkRight; - // Procedural(LookAt) - case ExpressionPreset.LookUp: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookUp; - case ExpressionPreset.LookDown: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookDown; - case ExpressionPreset.LookLeft: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookLeft; - case ExpressionPreset.LookRight: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookRight; - // Other - case ExpressionPreset.Neutral: - return UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.neutral; - default: - throw new ArgumentOutOfRangeException(nameof(preset), preset, null); - } - } - - private static VrmLib.ExpressionPreset ToVrmFormat(this UniGLTF.Extensions.VRMC_vrm.ExpressionPreset preset) - { - switch (preset) - { - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.custom: return ExpressionPreset.Custom; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.aa: return ExpressionPreset.Aa; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ih: return ExpressionPreset.Ih; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ou: return ExpressionPreset.Ou; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.ee: return ExpressionPreset.Ee; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.oh: return ExpressionPreset.Oh; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blink: return ExpressionPreset.Blink; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.happy: return ExpressionPreset.Happy; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.angry: return ExpressionPreset.Angry; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.sad: return ExpressionPreset.Sad; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.relaxed: return ExpressionPreset.Relaxed; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookUp: return ExpressionPreset.LookUp; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.surprised: return ExpressionPreset.Surprised; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookDown: return ExpressionPreset.LookDown; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookLeft: return ExpressionPreset.LookLeft; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.lookRight: return ExpressionPreset.LookRight; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blinkLeft: return ExpressionPreset.BlinkLeft; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.blinkRight: return ExpressionPreset.BlinkRight; - case UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.neutral: return ExpressionPreset.Neutral; - default: - throw new ArgumentOutOfRangeException(nameof(preset), preset, null); - } - } - } -} diff --git a/Assets/VRM10/Runtime/IO/VrmExpressionAdapter.cs.meta b/Assets/VRM10/Runtime/IO/VrmExpressionAdapter.cs.meta deleted file mode 100644 index 5ec3b69eb..000000000 --- a/Assets/VRM10/Runtime/IO/VrmExpressionAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cadc48d0e68ee5847b158dcef9b7b9a8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/VrmFirstPersonAdapter.cs b/Assets/VRM10/Runtime/IO/VrmFirstPersonAdapter.cs deleted file mode 100644 index 0101e5f0f..000000000 --- a/Assets/VRM10/Runtime/IO/VrmFirstPersonAdapter.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using VrmLib; - -namespace UniVRM10 -{ - public static class FirstPersonAdapter - { - public static VrmLib.FirstPersonMeshType FromGltf(this UniGLTF.Extensions.VRMC_vrm.FirstPersonType src) - { - switch (src) - { - case UniGLTF.Extensions.VRMC_vrm.FirstPersonType.auto: return FirstPersonMeshType.Auto; - case UniGLTF.Extensions.VRMC_vrm.FirstPersonType.both: return FirstPersonMeshType.Both; - case UniGLTF.Extensions.VRMC_vrm.FirstPersonType.firstPersonOnly: return FirstPersonMeshType.FirstPersonOnly; - case UniGLTF.Extensions.VRMC_vrm.FirstPersonType.thirdPersonOnly: return FirstPersonMeshType.ThirdPersonOnly; - } - - throw new NotImplementedException(); - } - - public static FirstPerson FromGltf(this UniGLTF.Extensions.VRMC_vrm.FirstPerson fp, List nodes) - { - var self = new FirstPerson(); - - if (fp.MeshAnnotations != null) - { - self.Annotations.AddRange(fp.MeshAnnotations - .Select(x => new FirstPersonMeshAnnotation(nodes[x.Node.Value], x.FirstPersonType.FromGltf()))); - } - return self; - } - public static UniGLTF.Extensions.VRMC_vrm.FirstPerson ToGltf(this FirstPerson self, List nodes) - { - if (self == null) - { - return null; - } - - var firstPerson = new UniGLTF.Extensions.VRMC_vrm.FirstPerson - { - - }; - - foreach (var x in self.Annotations) - { - firstPerson.MeshAnnotations.Add(new UniGLTF.Extensions.VRMC_vrm.MeshAnnotation - { - Node = nodes.IndexOfThrow(x.Node), - FirstPersonType = EnumUtil.Cast(x.FirstPersonFlag), - }); - } - return firstPerson; - } - } -} diff --git a/Assets/VRM10/Runtime/IO/VrmFirstPersonAdapter.cs.meta b/Assets/VRM10/Runtime/IO/VrmFirstPersonAdapter.cs.meta deleted file mode 100644 index dd2200fb9..000000000 --- a/Assets/VRM10/Runtime/IO/VrmFirstPersonAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 32f13c918ad866647bfc8f91f3ec7815 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/VrmLoader.cs b/Assets/VRM10/Runtime/IO/VrmLoader.cs new file mode 100644 index 000000000..cc59d996d --- /dev/null +++ b/Assets/VRM10/Runtime/IO/VrmLoader.cs @@ -0,0 +1,20 @@ +using System.IO; +using VrmLib; +using UniGLTF; + +namespace UniVRM10 +{ + /// + /// utility for load VrmLib Model from byte[] + /// + public static class VrmLoader + { + public static Model CreateVrmModel(GltfParser parser) + { + var storage = new Vrm10Storage(parser); + var model = ModelLoader.Load(storage, Path.GetFileName(parser.TargetPath)); + model.ConvertCoordinate(Coordinates.Unity); + return model; + } + } +} diff --git a/Assets/VRM10/Runtime/UnityBuilder/VrmLoader.cs.meta b/Assets/VRM10/Runtime/IO/VrmLoader.cs.meta similarity index 100% rename from Assets/VRM10/Runtime/UnityBuilder/VrmLoader.cs.meta rename to Assets/VRM10/Runtime/IO/VrmLoader.cs.meta diff --git a/Assets/VRM10/Runtime/IO/VrmLookAtAdapter.cs b/Assets/VRM10/Runtime/IO/VrmLookAtAdapter.cs deleted file mode 100644 index 843c21da8..000000000 --- a/Assets/VRM10/Runtime/IO/VrmLookAtAdapter.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using VrmLib; - -namespace UniVRM10 -{ - public static class LookAtAdapter - { - public static LookAtRangeMap FromGltf(this UniGLTF.Extensions.VRMC_vrm.LookAtRangeMap map) - { - return new LookAtRangeMap - { - InputMaxValue = map.InputMaxValue.Value, - OutputScaling = map.OutputScale.Value, - }; - } - - public static LookAtType FromGltf(this UniGLTF.Extensions.VRMC_vrm.LookAtType src) - { - switch (src) - { - case UniGLTF.Extensions.VRMC_vrm.LookAtType.bone: return LookAtType.Bone; - case UniGLTF.Extensions.VRMC_vrm.LookAtType.expression: return LookAtType.Expression; - } - - throw new NotImplementedException(); - } - - public static LookAt FromGltf(this UniGLTF.Extensions.VRMC_vrm.LookAt src) - { - return new LookAt - { - OffsetFromHeadBone = src.OffsetFromHeadBone.ToVector3(), - LookAtType = src.LookAtType.FromGltf(), - HorizontalInner = src.LookAtHorizontalInner.FromGltf(), - HorizontalOuter = src.LookAtHorizontalOuter.FromGltf(), - VerticalUp = src.LookAtVerticalUp.FromGltf(), - VerticalDown = src.LookAtVerticalDown.FromGltf(), - }; - } - - public static UniGLTF.Extensions.VRMC_vrm.LookAtRangeMap ToGltf(this LookAtRangeMap map) - { - return new UniGLTF.Extensions.VRMC_vrm.LookAtRangeMap - { - InputMaxValue = map.InputMaxValue, - OutputScale = map.OutputScaling, - }; - } - - public static UniGLTF.Extensions.VRMC_vrm.LookAt ToGltf(this LookAt lookAt) - { - var dst = new UniGLTF.Extensions.VRMC_vrm.LookAt - { - LookAtType = (UniGLTF.Extensions.VRMC_vrm.LookAtType)lookAt.LookAtType, - LookAtHorizontalInner = lookAt.HorizontalInner.ToGltf(), - LookAtHorizontalOuter = lookAt.HorizontalOuter.ToGltf(), - LookAtVerticalUp = lookAt.VerticalUp.ToGltf(), - LookAtVerticalDown = lookAt.VerticalDown.ToGltf(), - OffsetFromHeadBone = lookAt.OffsetFromHeadBone.ToFloat3(), - }; - return dst; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/Runtime/IO/VrmLookAtAdapter.cs.meta b/Assets/VRM10/Runtime/IO/VrmLookAtAdapter.cs.meta deleted file mode 100644 index 636b08d80..000000000 --- a/Assets/VRM10/Runtime/IO/VrmLookAtAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 68385357d73a5a3428e68eb49742baa9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/VrmMetaAdapter.cs b/Assets/VRM10/Runtime/IO/VrmMetaAdapter.cs deleted file mode 100644 index 44da848d0..000000000 --- a/Assets/VRM10/Runtime/IO/VrmMetaAdapter.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System.Collections.Generic; -using VrmLib; - -namespace UniVRM10 -{ - public static class VrmMetaAdapter - { - public static AvatarPermission ToAvaterPermission(this UniGLTF.Extensions.VRMC_vrm.Meta self) - { - return new AvatarPermission - { - AvatarUsage = (AvatarUsageType)self.AvatarPermission, - IsAllowedViolentUsage = self.AllowExcessivelyViolentUsage.Value, - IsAllowedSexualUsage = self.AllowExcessivelySexualUsage.Value, - CommercialUsage = (CommercialUsageType)self.CommercialUsage, - // OtherPermissionUrl = self.OtherPermissionUrl, - IsAllowedPoliticalOrReligiousUsage = self.AllowPoliticalOrReligiousUsage.Value, - }; - } - - public static RedistributionLicense ToRedistributionLicense(this UniGLTF.Extensions.VRMC_vrm.Meta self) - { - return new RedistributionLicense - { - CreditNotation = (CreditNotationType)self.CreditNotation, - IsAllowRedistribution = self.AllowRedistribution.Value, - ModificationLicense = (ModificationLicenseType)self.Modification, - OtherLicenseUrl = self.OtherLicenseUrl, - }; - } - - public static Meta FromGltf(this UniGLTF.Extensions.VRMC_vrm.Meta self, List textures) - { - var meta = new Meta - { - Name = self.Name, - Version = self.Version, - ContactInformation = self.ContactInformation, - AvatarPermission = ToAvaterPermission(self), - RedistributionLicense = ToRedistributionLicense(self), - }; - if (self.References != null) - { - meta.References.AddRange(self.References); - } - if (self.Authors != null) - { - meta.Authors.AddRange(self.Authors); - } - if (self.ThumbnailImage.HasValue) - { - var texture = textures[self.ThumbnailImage.Value] as ImageTexture; - if (texture != null) - { - meta.Thumbnail = texture.Image; - } - } - - return meta; - } - - public static UniGLTF.Extensions.VRMC_vrm.Meta ToGltf(this Meta self, List textures) - { - var meta = new UniGLTF.Extensions.VRMC_vrm.Meta - { - Name = self.Name, - Version = self.Version, - ContactInformation = self.ContactInformation, - CopyrightInformation = self.CopyrightInformation, - // AvatarPermission - AvatarPermission = (UniGLTF.Extensions.VRMC_vrm.AvatarPermissionType)self.AvatarPermission.AvatarUsage, - AllowExcessivelyViolentUsage = self.AvatarPermission.IsAllowedViolentUsage, - AllowExcessivelySexualUsage = self.AvatarPermission.IsAllowedSexualUsage, - CommercialUsage = (UniGLTF.Extensions.VRMC_vrm.CommercialUsageType)self.AvatarPermission.CommercialUsage, - AllowPoliticalOrReligiousUsage = self.AvatarPermission.IsAllowedPoliticalOrReligiousUsage, - // OtherPermissionUrl = self.AvatarPermission.OtherPermissionUrl, - // RedistributionLicense - CreditNotation = (UniGLTF.Extensions.VRMC_vrm.CreditNotationType)self.RedistributionLicense.CreditNotation, - AllowRedistribution = self.RedistributionLicense.IsAllowRedistribution, - Modification = (UniGLTF.Extensions.VRMC_vrm.ModificationType)self.RedistributionLicense.ModificationLicense, - OtherLicenseUrl = self.RedistributionLicense.OtherLicenseUrl, - References = self.References, - Authors = self.Authors, - }; - if (self.Thumbnail != null) - { - for (int i = 0; i < textures.Count; ++i) - { - var texture = textures[i] as ImageTexture; - if (texture.Image == self.Thumbnail) - { - meta.ThumbnailImage = i; - break; - } - } - } - return meta; - } - } -} diff --git a/Assets/VRM10/Runtime/IO/VrmMetaAdapter.cs.meta b/Assets/VRM10/Runtime/IO/VrmMetaAdapter.cs.meta deleted file mode 100644 index 27ecfcd8b..000000000 --- a/Assets/VRM10/Runtime/IO/VrmMetaAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ba45f21a0e4c4fd488473e928f70cd98 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/IO/VrmSpringBoneAdapter.cs b/Assets/VRM10/Runtime/IO/VrmSpringBoneAdapter.cs deleted file mode 100644 index 24666b69c..000000000 --- a/Assets/VRM10/Runtime/IO/VrmSpringBoneAdapter.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UniGLTF; -using UniGLTF.Extensions.VRMC_springBone; -using UniGLTF.Extensions.VRMC_node_collider; -using VrmLib; - -namespace UniVRM10 -{ - public static class SpringBoneAdapter - { - public static VRMC_springBone ToGltf(this SpringBoneManager self, List nodes, - List gltfNodes) - { - if (self == null) - { - return null; - } - - var springBone = new VRMC_springBone - { - Springs = new List(), - }; - - // - // VRMC_node_collider - // - foreach (var nodeCollider in self.Springs.SelectMany(x => x.Colliders)) - { - var index = nodes.IndexOfThrow(nodeCollider.Node); - var gltfCollider = new VRMC_node_collider - { - Shapes = new List(), - }; - foreach (var y in nodeCollider.Colliders) - { - switch (y.ColliderType) - { - case VrmSpringBoneColliderTypes.Sphere: - { - var sphere = new ColliderShapeSphere - { - Radius = y.Radius, - Offset = y.Offset.ToFloat3(), - }; - gltfCollider.Shapes.Add(new ColliderShape - { - Sphere = sphere, - }); - break; - } - - case VrmSpringBoneColliderTypes.Capsule: - { - var capsule = new ColliderShapeCapsule - { - Radius = y.Radius, - Offset = y.Offset.ToFloat3(), - Tail = y.CapsuleTail.ToFloat3(), - }; - gltfCollider.Shapes.Add(new ColliderShape - { - Capsule = capsule, - }); - } - break; - - default: - throw new NotImplementedException(); - } - } - - // - // add to node.extensions - // - UniGLTF.Extensions.VRMC_node_collider.GltfSerializer.SerializeTo(ref gltfNodes[index].extensions, gltfCollider); - } - - // - // VRMC_springBone - // - foreach (var x in self.Springs) - { - var spring = new Spring - { - Name = x.Comment, - Colliders = x.Colliders.Select(y => nodes.IndexOfThrow(y.Node)).ToArray(), - Joints = new List(), - }; - - foreach (var y in x.Joints) - { - spring.Joints.Add(new SpringBoneJoint - { - Node = nodes.IndexOfThrow(y.Node), - HitRadius = y.HitRadius, - DragForce = y.DragForce, - GravityDir = y.GravityDir.ToFloat3(), - GravityPower = y.GravityPower, - Stiffness = y.Stiffness, - }); - } - - springBone.Springs.Add(spring); - } - - return springBone; - } - } -} diff --git a/Assets/VRM10/Runtime/IO/VrmSpringBoneAdapter.cs.meta b/Assets/VRM10/Runtime/IO/VrmSpringBoneAdapter.cs.meta deleted file mode 100644 index 5cbacdf8b..000000000 --- a/Assets/VRM10/Runtime/IO/VrmSpringBoneAdapter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3d523ab537ffdbe40ae4fbd372693cb3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Migration/MigrationMToon.cs b/Assets/VRM10/Runtime/Migration/MigrationMToon.cs new file mode 100644 index 000000000..f500548cc --- /dev/null +++ b/Assets/VRM10/Runtime/Migration/MigrationMToon.cs @@ -0,0 +1,429 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UniGLTF; +using UniGLTF.Extensions.VRMC_materials_mtoon; +using UniJSON; +using UnityEngine; + + +namespace UniVRM10 +{ + public static class MigrationMToon + { + static float[] ToFloat4(this Color color) + { + return new float[] { color.r, color.g, color.b, color.a }; + } + + static float[] ToFloat3(this Color color) + { + return new float[] { color.r, color.g, color.b }; + } + + static Color ToColor(JsonNode node) + { + return node.ArrayItems().Select(x => x.GetSingle()).ToArray().ToColor4(); + } + + static float[] ToFloat4(JsonNode node) + { + return node.ArrayItems().Select(x => x.GetSingle()).ToArray(); + } + + struct TextureIndexMap + { + // glTF + public int? MainTex; + public int? BumpMap; + public int? EmissionMap; + // VRMC_materials_mtoon + public int? ShadeTexture; + public int? ReceiveShadowTexture; + public int? ShadingGradeTexture; + public int? RimTexture; + public int? SphereAdd; + public int? OutlineWidthTexture; + public int? UvAnimMaskTexture; + } + + /// + /// vrm-0 の json から vrm-0 の MToon.Definition を生成する。 + /// + /// Texture2D は作成せずに、直接 index を操作する。 + /// + /// + struct MToonValue + { + public MToon.MToonDefinition Definition; + + // Texture の Offset/Scale + public Dictionary OffsetScale; + + // Texture の Index リスト + public TextureIndexMap TextureIndexMap; + + public static MToonValue Create(JsonNode vrmMaterial) + { + var definition = new MToon.MToonDefinition + { + Color = new MToon.ColorDefinition { }, + Lighting = new MToon.LightingDefinition + { + LightingInfluence = new MToon.LightingInfluenceDefinition { }, + LitAndShadeMixing = new MToon.LitAndShadeMixingDefinition { }, + Normal = new MToon.NormalDefinition { } + }, + Emission = new MToon.EmissionDefinition { }, + MatCap = new MToon.MatCapDefinition { }, + Meta = new MToon.MetaDefinition { }, + Outline = new MToon.OutlineDefinition { }, + Rendering = new MToon.RenderingDefinition { }, + Rim = new MToon.RimDefinition { }, + TextureOption = new MToon.TextureUvCoordsDefinition { } + }; + + var offsetScale = new Dictionary(); + foreach (var kv in vrmMaterial["vectorProperties"].ObjectItems()) + { + var key = kv.Key.GetString(); + switch (key) + { + case "_Color": + definition.Color.LitColor = ToColor(kv.Value); + break; + + case "_ShadeColor": + definition.Color.ShadeColor = ToColor(kv.Value); + break; + + case "_EmissionColor": + definition.Emission.EmissionColor = ToColor(kv.Value); + break; + + case "_OutlineColor": + definition.Outline.OutlineColor = ToColor(kv.Value); + break; + + case "_RimColor": + definition.Rim.RimColor = ToColor(kv.Value); + break; + + case "_MainTex": + case "_ShadeTexture": + case "_BumpMap": + case "_EmissionMap": + case "_OutlineWidthTexture": + case "_ReceiveShadowTexture": + case "_RimTexture": + case "_ShadingGradeTexture": + case "_SphereAdd": + case "_UvAnimMaskTexture": + // scale, offset + offsetScale.Add(key, ToFloat4(kv.Value)); + break; + + default: + throw new NotImplementedException($"{kv.Key}: {kv.Value}"); + } + } + + foreach (var kv in vrmMaterial["floatProperties"].ObjectItems()) + { + var value = kv.Value.GetSingle(); + switch (kv.Key.GetString()) + { + case "_BlendMode": + definition.Rendering.RenderMode = (MToon.RenderMode)(int)value; + break; + + case "_CullMode": + definition.Rendering.CullMode = (MToon.CullMode)(int)value; + break; + + case "_Cutoff": + definition.Color.CutoutThresholdValue = value; + break; + + case "_BumpScale": + definition.Lighting.Normal.NormalScaleValue = value; + break; + + case "_LightColorAttenuation": + definition.Lighting.LightingInfluence.LightColorAttenuationValue = value; + break; + + case "_RimFresnelPower": + definition.Rim.RimFresnelPowerValue = value; + break; + + case "_RimLift": + definition.Rim.RimLiftValue = value; + break; + + case "_RimLightingMix": + definition.Rim.RimLightingMixValue = value; + break; + + case "_ShadeShift": + definition.Lighting.LitAndShadeMixing.ShadingShiftValue = value; + break; + + case "_ShadeToony": + definition.Lighting.LitAndShadeMixing.ShadingToonyValue = value; + break; + + case "_ShadingGradeRate": + // definition.Lighting.LightingInfluence.gr + break; + + case "_OutlineColorMode": + definition.Outline.OutlineColorMode = (MToon.OutlineColorMode)value; + break; + + case "_OutlineLightingMix": + definition.Outline.OutlineLightingMixValue = value; + break; + + case "_OutlineScaledMaxDistance": + definition.Outline.OutlineScaledMaxDistanceValue = value; + break; + + case "_OutlineWidth": + definition.Outline.OutlineWidthValue = value; + break; + + case "_OutlineWidthMode": + definition.Outline.OutlineWidthMode = (MToon.OutlineWidthMode)value; + break; + + case "_OutlineCullMode": + // definition.Outline. + break; + + case "_UvAnimRotation": + definition.TextureOption.UvAnimationRotationSpeedValue = value; + break; + + case "_UvAnimScrollX": + definition.TextureOption.UvAnimationScrollXSpeedValue = value; + break; + + case "_UvAnimScrollY": + definition.TextureOption.UvAnimationScrollYSpeedValue = value; + break; + + case "_ZWrite": + break; + + case "_ReceiveShadowRate": + case "_DstBlend": + case "_SrcBlend": + case "_IndirectLightIntensity": + case "_MToonVersion": + case "_DebugMode": + break; + + default: + throw new NotImplementedException($"floatProperties: {kv.Key} is unknown"); + } + } + + var map = new TextureIndexMap(); + + foreach (var kv in vrmMaterial["textureProperties"].ObjectItems()) + { + var index = kv.Value.GetInt32(); + switch (kv.Key.GetString()) + { + case "_MainTex": map.MainTex = index; break; + case "_ShadeTexture": map.ShadeTexture = index; break; + case "_BumpMap": map.BumpMap = index; break; + case "_ReceiveShadowTexture": map.ReceiveShadowTexture = index; break; + case "_ShadingGradeTexture": map.ShadingGradeTexture = index; break; + case "_RimTexture": map.RimTexture = index; break; + case "_SphereAdd": map.SphereAdd = index; break; + case "_EmissionMap": map.EmissionMap = index; break; + case "_OutlineWidthTexture": map.OutlineWidthTexture = index; break; + case "_UvAnimMaskTexture": map.UvAnimMaskTexture = index; break; + default: + throw new NotImplementedException($"textureProperties: {kv.Key} is unknown"); + } + } + + return new MToonValue + { + Definition = definition, + OffsetScale = offsetScale, + TextureIndexMap = map, + }; + } + } + + static (string, bool) GetRenderMode(MToon.RenderMode mode) + { + switch (mode) + { + case MToon.RenderMode.Opaque: return ("OPAQUE", false); + case MToon.RenderMode.Cutout: return ("MASK", false); + case MToon.RenderMode.Transparent: return ("BLEND", false); + case MToon.RenderMode.TransparentWithZWrite: return ("BLEND", true); + } + + throw new NotImplementedException(); + } + + public static void Migrate(glTF gltf, JsonNode json) + { + for (int i = 0; i < gltf.materials.Count; ++i) + { + var vrmMaterial = json["extensions"]["VRM"]["materialProperties"][i]; + if (vrmMaterial["shader"].GetString() != "VRM/MToon") + { + continue; + } + + // VRM-0 MToon の情報 + var mtoon = MToonValue.Create(vrmMaterial); + + // KHR_materials_unlit として fallback した情報が入っている + var gltfMaterial = gltf.materials[i]; + if (!glTF_KHR_materials_unlit.IsEnable(gltfMaterial)) + { + // 古いモデルは無い場合がある + // throw new Exception($"[{i}]{gltfMaterial.name} has no extensions"); + } + + var extensions = new glTFExtensionExport(); + gltfMaterial.extensions = extensions; + extensions.Add( + glTF_KHR_materials_unlit.ExtensionName, + new ArraySegment(glTF_KHR_materials_unlit.Raw)); + + // + // definition の中身を gltfMaterial と gltfMaterial.extensions.VRMC_materials_mtoon に移し替える + // + var dst = new VRMC_materials_mtoon(); + + // Color + gltfMaterial.pbrMetallicRoughness.baseColorFactor = mtoon.Definition.Color.LitColor.ToFloat4(); + if (mtoon.TextureIndexMap.MainTex.HasValue) + { + gltfMaterial.pbrMetallicRoughness.baseColorTexture = new glTFMaterialBaseColorTextureInfo + { + index = mtoon.TextureIndexMap.MainTex.Value + }; + var value = mtoon.OffsetScale["_MainTex"]; + glTF_KHR_texture_transform.Serialize( + gltfMaterial.pbrMetallicRoughness.baseColorTexture, + (value[0], value[1]), + (value[2], value[3]) + ); + } + dst.ShadeFactor = mtoon.Definition.Color.ShadeColor.ToFloat3(); + if (mtoon.TextureIndexMap.ShadeTexture.HasValue) + { + dst.ShadeMultiplyTexture = mtoon.TextureIndexMap.ShadeTexture.Value; + } + gltfMaterial.alphaCutoff = mtoon.Definition.Color.CutoutThresholdValue; + + // Outline + dst.OutlineColorMode = (UniGLTF.Extensions.VRMC_materials_mtoon.OutlineColorMode)mtoon.Definition.Outline.OutlineColorMode; + dst.OutlineFactor = ToFloat3(mtoon.Definition.Outline.OutlineColor); + dst.OutlineLightingMixFactor = mtoon.Definition.Outline.OutlineLightingMixValue; + dst.OutlineScaledMaxDistanceFactor = mtoon.Definition.Outline.OutlineScaledMaxDistanceValue; + dst.OutlineWidthMode = (UniGLTF.Extensions.VRMC_materials_mtoon.OutlineWidthMode)mtoon.Definition.Outline.OutlineWidthMode; + dst.OutlineWidthFactor = mtoon.Definition.Outline.OutlineWidthValue; + if (mtoon.TextureIndexMap.OutlineWidthTexture.HasValue) + { + dst.OutlineWidthMultiplyTexture = mtoon.TextureIndexMap.OutlineWidthTexture.Value; + } + + // Emission + gltfMaterial.emissiveFactor = mtoon.Definition.Emission.EmissionColor.ToFloat3(); + if (mtoon.TextureIndexMap.EmissionMap.HasValue) + { + gltfMaterial.emissiveTexture = new glTFMaterialEmissiveTextureInfo + { + index = mtoon.TextureIndexMap.EmissionMap.Value + }; + var value = mtoon.OffsetScale["_EmissionMap"]; + glTF_KHR_texture_transform.Serialize( + gltfMaterial.emissiveTexture, + (value[0], value[1]), + (value[2], value[3]) + ); + } + + // Light + dst.GiIntensityFactor = mtoon.Definition.Lighting.LightingInfluence.GiIntensityValue; + dst.LightColorAttenuationFactor = mtoon.Definition.Lighting.LightingInfluence.LightColorAttenuationValue; + dst.ShadingShiftFactor = mtoon.Definition.Lighting.LitAndShadeMixing.ShadingShiftValue; + dst.ShadingToonyFactor = mtoon.Definition.Lighting.LitAndShadeMixing.ShadingToonyValue; + if (mtoon.TextureIndexMap.BumpMap.HasValue) + { + gltfMaterial.normalTexture = new glTFMaterialNormalTextureInfo + { + index = mtoon.TextureIndexMap.BumpMap.Value, + scale = mtoon.Definition.Lighting.Normal.NormalScaleValue + }; + var value = mtoon.OffsetScale["_BumpMap"]; + glTF_KHR_texture_transform.Serialize( + gltfMaterial.normalTexture, + (value[0], value[1]), + (value[2], value[3]) + ); + } + + // matcap + if (mtoon.TextureIndexMap.SphereAdd.HasValue) + { + dst.AdditiveTexture = mtoon.TextureIndexMap.SphereAdd.Value; + } + + // rendering + switch (mtoon.Definition.Rendering.CullMode) + { + case MToon.CullMode.Back: + gltfMaterial.doubleSided = false; + break; + + case MToon.CullMode.Off: + gltfMaterial.doubleSided = true; + break; + + case MToon.CullMode.Front: + // GLTF not support + gltfMaterial.doubleSided = false; + break; + + default: + throw new NotImplementedException(); + } + (gltfMaterial.alphaMode, dst.TransparentWithZWrite) = GetRenderMode(mtoon.Definition.Rendering.RenderMode); + dst.RenderQueueOffsetNumber = mtoon.Definition.Rendering.RenderQueueOffsetNumber; + + // rim + dst.RimFactor = mtoon.Definition.Rim.RimColor.ToFloat3(); + if (mtoon.TextureIndexMap.RimTexture.HasValue) + { + dst.RimMultiplyTexture = mtoon.TextureIndexMap.RimTexture.Value; + } + dst.RimLiftFactor = mtoon.Definition.Rim.RimLiftValue; + dst.RimFresnelPowerFactor = mtoon.Definition.Rim.RimFresnelPowerValue; + dst.RimLightingMixFactor = mtoon.Definition.Rim.RimLightingMixValue; + + // texture option + if (mtoon.TextureIndexMap.UvAnimMaskTexture.HasValue) + { + dst.UvAnimationMaskTexture = mtoon.TextureIndexMap.UvAnimMaskTexture.Value; + } + dst.UvAnimationRotationSpeedFactor = mtoon.Definition.TextureOption.UvAnimationRotationSpeedValue; + dst.UvAnimationScrollXSpeedFactor = mtoon.Definition.TextureOption.UvAnimationScrollXSpeedValue; + dst.UvAnimationScrollYSpeedFactor = mtoon.Definition.TextureOption.UvAnimationScrollYSpeedValue; + + UniGLTF.Extensions.VRMC_materials_mtoon.GltfSerializer.SerializeTo(ref gltfMaterial.extensions, dst); + } + } + } +} diff --git a/Assets/VRM10/Runtime/Migration/MigrationMToon.cs.meta b/Assets/VRM10/Runtime/Migration/MigrationMToon.cs.meta new file mode 100644 index 000000000..10f7f4431 --- /dev/null +++ b/Assets/VRM10/Runtime/Migration/MigrationMToon.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e48d262d503ddfd4b86aeef6512697eb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/VRM10/Runtime/Migration/MigrationVrm.cs b/Assets/VRM10/Runtime/Migration/MigrationVrm.cs index 93cb6d3e6..817bd1563 100644 --- a/Assets/VRM10/Runtime/Migration/MigrationVrm.cs +++ b/Assets/VRM10/Runtime/Migration/MigrationVrm.cs @@ -35,7 +35,9 @@ namespace UniVRM10 vrm1.Meta = MigrationVrmMeta.Migrate(vrm0["meta"]); vrm1.Humanoid = MigrationVrmHumanoid.Migrate(vrm0["humanoid"]); vrm1.Expressions = MigrationVrmExpression.Migrate(gltf, vrm0["blendShapeMaster"]).ToList(); + // lookat + // firstperson var f = new JsonFormatter(); @@ -51,10 +53,8 @@ namespace UniVRM10 extensions.Add(UniGLTF.Extensions.VRMC_springBone.VRMC_springBone.ExtensionName, f.GetStoreBytes()); } { - // MToon - } - { - // constraint + // MToon + MigrationMToon.Migrate(gltf, json); } } diff --git a/Assets/VRM10/Runtime/Migration/MigrationVrmExpression.cs b/Assets/VRM10/Runtime/Migration/MigrationVrmExpression.cs index c9605c77b..62ffee153 100644 --- a/Assets/VRM10/Runtime/Migration/MigrationVrmExpression.cs +++ b/Assets/VRM10/Runtime/Migration/MigrationVrmExpression.cs @@ -113,6 +113,7 @@ namespace UniVRM10 var targetValue = x["targetValue"].ArrayItems().Select(y => y.GetSingle()).ToArray(); if (propertyName.EndsWith("_ST")) { + var scaling = new float[] { targetValue[0], targetValue[1] }; expression.TextureTransformBinds.Add(new UniGLTF.Extensions.VRMC_vrm.TextureTransformBind { Material = materialIndex, @@ -156,14 +157,27 @@ namespace UniVRM10 foreach (var blendShapeClip in json["blendShapeGroups"].ArrayItems()) { var name = blendShapeClip["name"].GetString(); + var isBinary = false; + if (blendShapeClip.TryGet("isBinary", out JsonNode isBinaryNode)) + { + isBinary = isBinaryNode.GetBoolean(); + } var expression = new UniGLTF.Extensions.VRMC_vrm.Expression { Name = name, Preset = ToPreset(blendShapeClip["presetName"]), - IsBinary = blendShapeClip["isBinary"].GetBoolean(), + IsBinary = isBinary, + MorphTargetBinds = new List(), + MaterialColorBinds = new List(), + TextureTransformBinds = new List(), }; expression.MorphTargetBinds = ToMorphTargetBinds(gltf, blendShapeClip["binds"]).ToList(); - ToMaterialColorBinds(gltf, blendShapeClip["materialValues"], expression); + + if (blendShapeClip.TryGet("materialValues", out JsonNode materialValues)) + { + ToMaterialColorBinds(gltf, materialValues, expression); + } + yield return expression; } } diff --git a/Assets/VRM10/Runtime/Migration/RotateY180.cs b/Assets/VRM10/Runtime/Migration/RotateY180.cs index 749ddbb43..f4878cb63 100644 --- a/Assets/VRM10/Runtime/Migration/RotateY180.cs +++ b/Assets/VRM10/Runtime/Migration/RotateY180.cs @@ -4,6 +4,11 @@ using UniGLTF; namespace UniVRM10 { + public class UnNormalizedException : Exception + { + + } + /// /// x, y, z => -x, y, -z /// @@ -32,7 +37,7 @@ namespace UniVRM10 } else { - throw new NotImplementedException("not normalized !"); + throw new UnNormalizedException(); } } if (node.scale != null && node.scale.Length == 3) diff --git a/Assets/VRM10/Runtime/Scenes/Sample.cs b/Assets/VRM10/Runtime/Scenes/Sample.cs index 94ced7b0a..9bc304bb6 100644 --- a/Assets/VRM10/Runtime/Scenes/Sample.cs +++ b/Assets/VRM10/Runtime/Scenes/Sample.cs @@ -3,28 +3,24 @@ using System.IO; using UnityEngine; using VrmLib; using UniVRM10; +using UniGLTF; public class Sample : MonoBehaviour { [SerializeField] string m_vrmPath = "Tests/Models/Alicia_vrm-0.51/AliciaSolid_vrm-0.51.vrm"; - static UniVRM10.ModelAsset Import(byte[] bytes, FileInfo path) + static GameObject Import(byte[] bytes, FileInfo path) { - var model = UniVRM10.VrmLoader.CreateVrmModel(bytes, path); + var parser = new GltfParser(); + parser.Parse(path.FullName, bytes); - // UniVRM-0.XXのコンポーネントを構築する - var assets = UniVRM10.RuntimeUnityBuilder.ToUnityAsset(model, showMesh: false); - - // showRenderer = false のときに後で表示する例 - foreach (var renderer in assets.Renderers) + using (var loader = new RuntimeUnityBuilder(parser)) { - renderer.enabled = true; + loader.Load(); + loader.ShowMeshes(); + return loader.DisposeOnGameObjectDestroyed().gameObject; } - - UniVRM10.ComponentBuilder.Build10(model, assets); - - return assets; } // Start is called before the first frame update @@ -35,17 +31,17 @@ public class Sample : MonoBehaviour // Export 1.0 var exporter = new UniVRM10.RuntimeVrmConverter(); - var model = exporter.ToModelFrom10(vrm0x.Root); + var model = exporter.ToModelFrom10(vrm0x); // 右手系に変換 model.ConvertCoordinate(VrmLib.Coordinates.Vrm1); var exportedBytes = model.ToGlb(); // Import 1.0 var vrm10 = Import(exportedBytes, src); - var pos = vrm10.Root.transform.position; + var pos = vrm10.transform.position; pos.x += 1.5f; - vrm10.Root.transform.position = pos; - vrm10.Root.name = vrm10.Root.name + "_Imported_v1_0"; + vrm10.transform.position = pos; + vrm10.name = vrm10.name + "_Imported_v1_0"; // write var path = Path.GetFullPath("vrm10.vrm"); diff --git a/Assets/VRM10/Runtime/TextureConvert.meta b/Assets/VRM10/Runtime/TextureConvert.meta deleted file mode 100644 index df4eb024d..000000000 --- a/Assets/VRM10/Runtime/TextureConvert.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 525d94ed40283ed4aa4221e3d2ec77c8 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources.meta b/Assets/VRM10/Runtime/TextureConvert/Resources.meta deleted file mode 100644 index 7f47e9549..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 8e4619bbdb366814995d35796e9fe54a -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders.meta b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders.meta deleted file mode 100644 index 106573a28..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: a283f0df584c01e4d94d8ff1679481fd -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessGltfToUnity.shader b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessGltfToUnity.shader deleted file mode 100644 index a291f51a4..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessGltfToUnity.shader +++ /dev/null @@ -1,54 +0,0 @@ -Shader "UniVRM/MetallicRoughnessGltfToUnity" -{ - Properties - { - _MainTex ("Texture", 2D) = "white" {} - _Roughness("Roughness", Float) = 1.0 - } - SubShader - { - // No culling or depth - Cull Off ZWrite Off ZTest Always - - Pass - { - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - struct v2f - { - float2 uv : TEXCOORD0; - float4 vertex : SV_POSITION; - }; - - v2f vert (appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = v.uv; - return o; - } - - sampler2D _MainTex; - float _Roughness; - - float4 frag (v2f i) : SV_Target - { - float4 col = tex2D(_MainTex, i.uv); - float pixelRoughnessFactor = (col.g * _Roughness); - float pixelSmoothness = 1.0f - sqrt(pixelRoughnessFactor); - return float4(col.b, 0, 0, clamp(pixelSmoothness, 0, 1.0)); - } - ENDCG - } - } -} diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessGltfToUnity.shader.meta b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessGltfToUnity.shader.meta deleted file mode 100644 index 4b8ca61aa..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessGltfToUnity.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 003d81d58d8b22442919cc6f9f288478 -timeCreated: 1533558728 -licenseType: Free -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessUnityToGltf.shader b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessUnityToGltf.shader deleted file mode 100644 index 2ab38d79e..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessUnityToGltf.shader +++ /dev/null @@ -1,55 +0,0 @@ -Shader "UniVRM/MetallicRoughnessUnityToGltf" -{ - Properties - { - _MainTex ("Texture", 2D) = "white" {} - _Smoothness("Smoothness", Float) = 1.0 - } - SubShader - { - // No culling or depth - Cull Off ZWrite Off ZTest Always - - Pass - { - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - struct v2f - { - float2 uv : TEXCOORD0; - float4 vertex : SV_POSITION; - }; - - v2f vert (appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = v.uv; - return o; - } - - sampler2D _MainTex; - float _Smoothness; - - float4 frag (v2f i) : SV_Target - { - float4 col = tex2D(_MainTex, i.uv); - float pixelSmoothness = (col.a * _Smoothness); - float pixelRoughnessFactorSqrt = (1.0f - pixelSmoothness); - float pixelRoughnessFactor = pixelRoughnessFactorSqrt * pixelRoughnessFactorSqrt; - return float4(0, clamp(pixelRoughnessFactor, 0, 1.0), col.r, 1); - } - ENDCG - } - } -} diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessUnityToGltf.shader.meta b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessUnityToGltf.shader.meta deleted file mode 100644 index edb3ff4fc..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/MetallicRoughnessUnityToGltf.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: d2f882a5cd7d0ba479fd8e426f90c53f -timeCreated: 1533558728 -licenseType: Free -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapGltfToUnity.shader b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapGltfToUnity.shader deleted file mode 100644 index 80846f845..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapGltfToUnity.shader +++ /dev/null @@ -1,63 +0,0 @@ -Shader "UniVRM/NormalMapGltfToUnity" -{ - Properties - { - _MainTex("Texture", 2D) = "white" {} - } - SubShader - { - // No culling or depth - Cull Off ZWrite Off ZTest Always - - Pass - { - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - struct v2f - { - float2 uv : TEXCOORD0; - float4 vertex : SV_POSITION; - }; - - v2f vert(appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = v.uv; - return o; - } - - sampler2D _MainTex; - - fixed4 frag(v2f i) : SV_Target - { - half4 col = tex2D(_MainTex, i.uv); - -#if defined(UNITY_NO_DXT5nm) - // This is a trick from UnpackNormal in UnityCG.cginc !!!! - return col; -#endif - - half4 normal; - normal.x = 1.0; - normal.y = col.y; - normal.z = 1.0; - normal.w = col.x; - - return normal; - } - ENDCG - } - } -} - diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapGltfToUnity.shader.meta b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapGltfToUnity.shader.meta deleted file mode 100644 index db0717e2d..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapGltfToUnity.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: d677f9f201a86264e86825ae708b1182 -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapUnityToGltf.shader b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapUnityToGltf.shader deleted file mode 100644 index 15c3ccb24..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapUnityToGltf.shader +++ /dev/null @@ -1,54 +0,0 @@ -Shader "UniVRM/NormalMapUnityToGltf" -{ - Properties - { - _MainTex ("Texture", 2D) = "white" {} - } - SubShader - { - // No culling or depth - Cull Off ZWrite Off ZTest Always - - Pass - { - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - struct v2f - { - float2 uv : TEXCOORD0; - float4 vertex : SV_POSITION; - }; - - v2f vert (appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = v.uv; - return o; - } - - sampler2D _MainTex; - - fixed4 frag (v2f i) : SV_Target - { - half4 col = tex2D(_MainTex, i.uv); - - col.xyz = (UnpackNormal(col) + 1) * 0.5; - col.w = 1; - - return col; - } - ENDCG - } - } -} diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapUnityToGltf.shader.meta b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapUnityToGltf.shader.meta deleted file mode 100644 index 3d8fdb299..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/NormalMapUnityToGltf.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: d8e01ada382f1004b83caff6b601af85 -timeCreated: 1533558728 -licenseType: Free -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionGltfToUnity.shader b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionGltfToUnity.shader deleted file mode 100644 index dce77062c..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionGltfToUnity.shader +++ /dev/null @@ -1,50 +0,0 @@ -Shader "UniVRM/OcclusionGltfToUnity" -{ - Properties - { - _MainTex ("Texture", 2D) = "white" {} - } - SubShader - { - // No culling or depth - Cull Off ZWrite Off ZTest Always - - Pass - { - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - struct v2f - { - float2 uv : TEXCOORD0; - float4 vertex : SV_POSITION; - }; - - v2f vert (appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = v.uv; - return o; - } - - sampler2D _MainTex; - - fixed4 frag (v2f i) : SV_Target - { - half4 col = tex2D(_MainTex, i.uv); - return half4(0, col.r, 0, 1); - } - ENDCG - } - } -} diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionGltfToUnity.shader.meta b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionGltfToUnity.shader.meta deleted file mode 100644 index 4b7ac07b9..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionGltfToUnity.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 6e25a54043ee42d47a630b18f133a0bf -timeCreated: 1533558728 -licenseType: Free -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionUnityToGltf.shader b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionUnityToGltf.shader deleted file mode 100644 index c73a3bd03..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionUnityToGltf.shader +++ /dev/null @@ -1,50 +0,0 @@ -Shader "UniVRM/OcclusionUnityToGltf" -{ - Properties - { - _MainTex ("Texture", 2D) = "white" {} - } - SubShader - { - // No culling or depth - Cull Off ZWrite Off ZTest Always - - Pass - { - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata - { - float4 vertex : POSITION; - float2 uv : TEXCOORD0; - }; - - struct v2f - { - float2 uv : TEXCOORD0; - float4 vertex : SV_POSITION; - }; - - v2f vert (appdata v) - { - v2f o; - o.vertex = UnityObjectToClipPos(v.vertex); - o.uv = v.uv; - return o; - } - - sampler2D _MainTex; - - fixed4 frag (v2f i) : SV_Target - { - half4 col = tex2D(_MainTex, i.uv); - return half4(col.g, 0, 0, 1); - } - ENDCG - } - } -} diff --git a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionUnityToGltf.shader.meta b/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionUnityToGltf.shader.meta deleted file mode 100644 index ebb47371c..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/Resources/Shaders/OcclusionUnityToGltf.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: f87e9edf9bf3c364db108ff75a8730ce -timeCreated: 1533558728 -licenseType: Free -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/TextureConvert/TextureConvertMaterial.cs b/Assets/VRM10/Runtime/TextureConvert/TextureConvertMaterial.cs deleted file mode 100644 index 4a56e76fd..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/TextureConvertMaterial.cs +++ /dev/null @@ -1,56 +0,0 @@ -using UnityEngine; - -namespace UniVRM10 -{ - public static class TextureConvertMaterial - { - - #region Normalmap - // GLTF data to Unity texture - // ConvertToNormalValueFromRawColorWhenCompressionIsRequired - public static Material GetNormalMapConvertGltfToUnity() - { - return new Material(Shader.Find("UniVRM/NormalMapGltfToUnity")); - } - - // Unity texture to GLTF data - // ConvertToRawColorWhenNormalValueIsCompressed - public static Material GetNormalMapConvertUnityToGltf() - { - return new Material(Shader.Find("UniVRM/NormalMapUnityToGltf")); - } - #endregion - - #region MetallicRoughness - // GLTF data to Unity texture - public static Material GetMetallicRoughnessGltfToUnity(float roughnessFactor) - { - var material = new Material(Shader.Find("UniVRM/MetallicRoughnessGltfToUnity")); - material.SetFloat("_Roughness", roughnessFactor); - return material; - } - - // Unity texture to GLTF data - public static Material GetMetallicRoughnessUnityToGltf(float smoothness) - { - var material = new Material(Shader.Find("UniVRM/MetallicRoughnessUnityToGltf")); - material.SetFloat("_Smoothness", smoothness); - return material; - } - #endregion - - #region Occlusion - // GLTF data to Unity texture - public static Material GetOcclusionGltfToUnity() - { - return new Material(Shader.Find("UniVRM/OcclusionGltfToUnity")); - } - - // Unity texture to GLTF data - public static Material GetOcclusionUnityToGltf() - { - return new Material(Shader.Find("UniVRM/OcclusionUnityToGltf")); - } - #endregion - } -} diff --git a/Assets/VRM10/Runtime/TextureConvert/TextureConvertMaterial.cs.meta b/Assets/VRM10/Runtime/TextureConvert/TextureConvertMaterial.cs.meta deleted file mode 100644 index fd04ce24b..000000000 --- a/Assets/VRM10/Runtime/TextureConvert/TextureConvertMaterial.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4edaed230e46d9a429f9d4252f19dda3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/UnityBuilder.meta b/Assets/VRM10/Runtime/UnityBuilder.meta deleted file mode 100644 index 1c32b98dc..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 49662dd147c59e64e913f70aefd0e999 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/UnityBuilder/ComponentBuilder.cs b/Assets/VRM10/Runtime/UnityBuilder/ComponentBuilder.cs deleted file mode 100644 index 6c0d79a08..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/ComponentBuilder.cs +++ /dev/null @@ -1,319 +0,0 @@ -using System; -using UnityEngine; -using System.Linq; -using System.Collections.Generic; - -namespace UniVRM10 -{ - public static class ComponentBuilder - { - #region Util - static (Transform, Mesh) GetTransformAndMesh(Transform t) - { - var skinnedMeshRenderer = t.GetComponent(); - if (skinnedMeshRenderer != null) - { - return (t, skinnedMeshRenderer.sharedMesh); - } - - var filter = t.GetComponent(); - if (filter != null) - { - return (t, filter.sharedMesh); - } - - return default; - } - #endregion - - #region Build10 - - static UniVRM10.MorphTargetBinding Build10(this VrmLib.MorphTargetBind bind, GameObject root, ModelMap loader) - { - var node = loader.Nodes[bind.Node].transform; - var mesh = loader.Meshes[bind.Node.MeshGroup]; - // var transformMeshTable = loader.Root.transform.Traverse() - // .Select(GetTransformAndMesh) - // .Where(x => x.Item2 != null) - // .ToDictionary(x => x.Item2, x => x.Item1); - // var node = transformMeshTable[mesh]; - // var transform = loader.Nodes[node].transform; - var relativePath = node.RelativePathFrom(root.transform); - - var names = new List(); - for (int i = 0; i < mesh.blendShapeCount; ++i) - { - names.Add(mesh.GetBlendShapeName(i)); - } - - // VRM-1.0 では値域は [0-1.0f] - return new UniVRM10.MorphTargetBinding(relativePath, names.IndexOf(bind.Name), bind.Value * 100.0f); - } - - static UniVRM10.MaterialColorBinding? Build10(this VrmLib.MaterialColorBind bind, ModelMap loader) - { - var kv = bind.Property; - var value = kv.Value.ToUnityVector4(); - var material = loader.Materials[bind.Material]; - - var binding = default(UniVRM10.MaterialColorBinding?); - if (material != null) - { - try - { - binding = new UniVRM10.MaterialColorBinding - { - MaterialName = bind.Material.Name, // UniVRM-0Xの実装は名前で持っている - BindType = bind.BindType, - TargetValue = value, - // BaseValue = material.GetColor(kv.Key), - }; - } - catch (Exception) - { - // do nothing - } - } - return binding; - } - - static UniVRM10.MaterialUVBinding? Build10(this VrmLib.TextureTransformBind bind, ModelMap loader) - { - var material = loader.Materials[bind.Material]; - - var binding = default(UniVRM10.MaterialUVBinding?); - if (material != null) - { - try - { - binding = new UniVRM10.MaterialUVBinding - { - MaterialName = bind.Material.Name, // UniVRM-0Xの実装は名前で持っている - Scaling = new Vector2(bind.Scale.X, bind.Scale.Y), - Offset = new Vector2(bind.Offset.X, bind.Offset.Y), - }; - } - catch (Exception) - { - // do nothing - } - } - return binding; - } - - public static void Build10(VrmLib.Model model, ModelAsset asset) - { - // meta - var controller = asset.Root.AddComponent(); - { - var meta = model.Vrm.Meta; - controller.Meta = ScriptableObject.CreateInstance(); - controller.Meta.Name = meta.Name; - controller.Meta.Version = meta.Version; - controller.Meta.CopyrightInformation = meta.CopyrightInformation; - controller.Meta.Authors = meta.Authors.ToArray(); - controller.Meta.ContactInformation = meta.ContactInformation; - controller.Meta.Reference = meta.Reference; - var thumbnailImages = asset.Map.Textures.Where(x => ((VrmLib.ImageTexture)x.Key).Image == meta.Thumbnail); - if (meta.Thumbnail != null && thumbnailImages.Count() > 0) - { - controller.Meta.Thumbnail = thumbnailImages.First().Value; - } - else if (meta.Thumbnail != null && meta.Thumbnail.Bytes.Count > 0) - { - var thumbnail = new Texture2D(2, 2, TextureFormat.ARGB32, false, false); - thumbnail.name = "Thumbnail"; - thumbnail.LoadImage(meta.Thumbnail.Bytes.ToArray()); - controller.Meta.Thumbnail = thumbnail; - asset.Textures.Add(thumbnail); - } - // avatar permission - controller.Meta.AllowedUser = meta.AvatarPermission.AvatarUsage; - controller.Meta.ViolentUsage = meta.AvatarPermission.IsAllowedViolentUsage; - controller.Meta.SexualUsage = meta.AvatarPermission.IsAllowedSexualUsage; - controller.Meta.CommercialUsage = meta.AvatarPermission.CommercialUsage; - controller.Meta.GameUsage = meta.AvatarPermission.IsAllowedGameUsage; - controller.Meta.PoliticalOrReligiousUsage = meta.AvatarPermission.IsAllowedPoliticalOrReligiousUsage; - controller.Meta.OtherPermissionUrl = meta.AvatarPermission.OtherPermissionUrl; - - // redistribution license - controller.Meta.CreditNotation = meta.RedistributionLicense.CreditNotation; - controller.Meta.ModificationLicense = meta.RedistributionLicense.ModificationLicense; - controller.Meta.Redistribution = meta.RedistributionLicense.IsAllowRedistribution; - controller.Meta.OtherLicenseUrl = meta.RedistributionLicense.OtherLicenseUrl; - - asset.ScriptableObjects.Add(controller.Meta); - } - - // expression - { - controller.Expression.ExpressionAvatar = ScriptableObject.CreateInstance(); - asset.ScriptableObjects.Add(controller.Expression.ExpressionAvatar); - if (model.Vrm.ExpressionManager != null) - { - foreach (var expression in model.Vrm.ExpressionManager.ExpressionList) - { - var clip = ScriptableObject.CreateInstance(); - clip.Preset = expression.Preset; - clip.ExpressionName = expression.Name; - clip.IsBinary = expression.IsBinary; - clip.OverrideBlink = expression.OverrideBlink; - clip.OverrideLookAt = expression.OverrideLookAt; - clip.OverrideMouth = expression.OverrideMouth; - - clip.MorphTargetBindings = expression.MorphTargetBinds.Select(x => x.Build10(asset.Root, asset.Map)) - .ToArray(); - clip.MaterialColorBindings = expression.MaterialColorBinds.Select(x => x.Build10(asset.Map)) - .Where(x => x.HasValue) - .Select(x => x.Value) - .ToArray(); - clip.MaterialUVBindings = expression.TextureTransformBinds.Select(x => x.Build10(asset.Map)) - .Where(x => x.HasValue) - .Select(x => x.Value) - .ToArray(); - controller.Expression.ExpressionAvatar.Clips.Add(clip); - asset.ScriptableObjects.Add(clip); - } - } - } - - // firstPerson - { - // VRMFirstPerson - if (model.Vrm.FirstPerson != null) - { - controller.FirstPerson.Renderers = model.Vrm.FirstPerson.Annotations.Select(x => - new UniVRM10.RendererFirstPersonFlags() - { - Renderer = asset.Map.Renderers[x.Node], - FirstPersonFlag = x.FirstPersonFlag - } - ).ToList(); - } - - // VRMLookAtApplyer - if (model.Vrm.LookAt != null) - { - controller.LookAt.OffsetFromHead = model.Vrm.LookAt.OffsetFromHeadBone.ToUnityVector3(); - if (model.Vrm.LookAt.LookAtType == VrmLib.LookAtType.Expression) - { - var lookAtApplyer = controller; - lookAtApplyer.LookAt.LookAtType = VRM10ControllerLookAt.LookAtTypes.Expression; - lookAtApplyer.LookAt.HorizontalOuter = new UniVRM10.CurveMapper( - model.Vrm.LookAt.HorizontalOuter.InputMaxValue, - model.Vrm.LookAt.HorizontalOuter.OutputScaling); - lookAtApplyer.LookAt.VerticalUp = new UniVRM10.CurveMapper( - model.Vrm.LookAt.VerticalUp.InputMaxValue, - model.Vrm.LookAt.VerticalUp.OutputScaling); - lookAtApplyer.LookAt.VerticalDown = new UniVRM10.CurveMapper( - model.Vrm.LookAt.VerticalDown.InputMaxValue, - model.Vrm.LookAt.VerticalDown.OutputScaling); - } - else if (model.Vrm.LookAt.LookAtType == VrmLib.LookAtType.Bone) - { - var lookAtBoneApplyer = controller; - lookAtBoneApplyer.LookAt.HorizontalInner = new UniVRM10.CurveMapper( - model.Vrm.LookAt.HorizontalInner.InputMaxValue, - model.Vrm.LookAt.HorizontalInner.OutputScaling); - lookAtBoneApplyer.LookAt.HorizontalOuter = new UniVRM10.CurveMapper( - model.Vrm.LookAt.HorizontalOuter.InputMaxValue, - model.Vrm.LookAt.HorizontalOuter.OutputScaling); - lookAtBoneApplyer.LookAt.VerticalUp = new UniVRM10.CurveMapper( - model.Vrm.LookAt.VerticalUp.InputMaxValue, - model.Vrm.LookAt.VerticalUp.OutputScaling); - lookAtBoneApplyer.LookAt.VerticalDown = new UniVRM10.CurveMapper( - model.Vrm.LookAt.VerticalDown.InputMaxValue, - model.Vrm.LookAt.VerticalDown.OutputScaling); - } - else - { - throw new NotImplementedException(); - } - } - } - - // springBone - if (model.Vrm.SpringBone != null) - { - foreach (var vrmSpring in model.Vrm.SpringBone.Springs) - { - // create a spring - var springBone = new UniVRM10.VRM10SpringBone(); - springBone.m_comment = vrmSpring.Comment; - if (vrmSpring.Origin != null && asset.Map.Nodes.TryGetValue(vrmSpring.Origin, out GameObject origin)) - { - springBone.m_center = origin.transform; - } - controller.SpringBone.Springs.Add(springBone); - - // create colliders for the spring - foreach (var vrmSpringBoneCollider in vrmSpring.Colliders) - { - var go = asset.Map.Nodes[vrmSpringBoneCollider.Node]; - var springBoneColliderGroup = go.GetComponent(); - if (springBoneColliderGroup != null) - { - // already setup - } - else - { - // new collider - springBoneColliderGroup = go.AddComponent(); - - // add collider shapes - springBoneColliderGroup.Colliders.Clear(); - foreach (var x in vrmSpringBoneCollider.Colliders) - { - switch (x.ColliderType) - { - case VrmLib.VrmSpringBoneColliderTypes.Sphere: - springBoneColliderGroup.Colliders.Add(new UniVRM10.VRM10SpringBoneCollider() - { - ColliderType = VRM10SpringBoneColliderTypes.Sphere, - Offset = x.Offset.ToUnityVector3(), - Radius = x.Radius - }); - break; - - case VrmLib.VrmSpringBoneColliderTypes.Capsule: - springBoneColliderGroup.Colliders.Add(new UniVRM10.VRM10SpringBoneCollider() - { - ColliderType = VRM10SpringBoneColliderTypes.Capsule, - Offset = x.Offset.ToUnityVector3(), - Radius = x.Radius, - Tail = x.CapsuleTail.ToUnityVector3(), - }); - break; - - default: - throw new NotImplementedException(); - } - } - } - springBone.ColliderGroups.Add(springBoneColliderGroup); - } - - // create joint for the spring - foreach (var vrmJoint in vrmSpring.Joints) - { - var go = asset.Map.Nodes[vrmJoint.Node]; - var joint = new VRM10SpringJoint(go.transform); - - joint.m_stiffnessForce = vrmJoint.Stiffness; - joint.m_gravityPower = vrmJoint.GravityPower; - joint.m_gravityDir = vrmJoint.GravityDir.ToUnityVector3(); - joint.m_dragForce = vrmJoint.DragForce; - joint.m_jointRadius = vrmJoint.HitRadius; - joint.m_exclude = vrmJoint.Exclude; - - springBone.Joints.Add(joint); - } - } - } - - // Assets - controller.ModelAsset = asset; - } - #endregion - } -} diff --git a/Assets/VRM10/Runtime/UnityBuilder/MToonLoader.cs b/Assets/VRM10/Runtime/UnityBuilder/MToonLoader.cs deleted file mode 100644 index 9212dca73..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/MToonLoader.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; - - -namespace UniVRM10 -{ - public static class MToonLoader - { - public delegate Texture2D GetTextureFunc(VrmLib.TextureInfo texture); - - public static MToon.MToonDefinition ToUnity(this VrmLib.MToon.MToonDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.MToonDefinition - { - Color = src.Color.ToUnity(textures), - Emission = src.Emission.ToUnity(textures), - Lighting = src.Lighting.ToUnity(textures), - MatCap = src.MatCap.ToUnity(textures), - Meta = src.Meta.ToUnity(), - Outline = src.Outline.ToUnity(textures), - Rendering = src.Rendering.ToUnity(), - Rim = src.Rim.ToUnity(textures), - TextureOption = src.TextureOption.ToUnity(textures), - }; - } - - static Vector2 ToUnity(this System.Numerics.Vector2 src) - { - return new Vector2(src.X, src.Y); - } - - static MToon.ColorDefinition ToUnity(this VrmLib.MToon.ColorDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.ColorDefinition - { - CutoutThresholdValue = src.CutoutThresholdValue, - LitColor = src.LitColor.ToUnitySRGB(), - LitMultiplyTexture = textures.GetOrDefault(src.LitMultiplyTexture?.Texture), - ShadeColor = src.ShadeColor.ToUnitySRGB(), - ShadeMultiplyTexture = textures.GetOrDefault(src.ShadeMultiplyTexture?.Texture), - }; - } - - static MToon.EmissionDefinition ToUnity(this VrmLib.MToon.EmissionDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.EmissionDefinition - { - EmissionColor = src.EmissionColor.ToUnityLinear(), - EmissionMultiplyTexture = textures.GetOrDefault(src.EmissionMultiplyTexture?.Texture), - }; - } - - static MToon.LightingDefinition ToUnity(this VrmLib.MToon.LightingDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.LightingDefinition - { - LightingInfluence = src.LightingInfluence.ToUnity(), - LitAndShadeMixing = src.LitAndShadeMixing.ToUnity(textures), - Normal = src.Normal.ToUnity(textures), - }; - } - - static MToon.LightingInfluenceDefinition ToUnity(this VrmLib.MToon.LightingInfluenceDefinition src) - { - if (src == null) return null; - return new MToon.LightingInfluenceDefinition - { - GiIntensityValue = src.GiIntensityValue, - LightColorAttenuationValue = src.LightColorAttenuationValue, - }; - } - - static MToon.LitAndShadeMixingDefinition ToUnity(this VrmLib.MToon.LitAndShadeMixingDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.LitAndShadeMixingDefinition - { - ShadingShiftValue = src.ShadingShiftValue, - ShadingToonyValue = src.ShadingToonyValue, - }; - } - - static MToon.NormalDefinition ToUnity(this VrmLib.MToon.NormalDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.NormalDefinition - { - NormalScaleValue = src.NormalScaleValue, - NormalTexture = textures.GetOrDefault(src.NormalTexture?.Texture), - }; - } - - static MToon.MatCapDefinition ToUnity(this VrmLib.MToon.MatCapDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.MatCapDefinition - { - AdditiveTexture = textures.GetOrDefault(src.AdditiveTexture?.Texture), - }; - } - - static MToon.MetaDefinition ToUnity(this VrmLib.MToon.MetaDefinition src) - { - if (src == null) return null; - return new MToon.MetaDefinition - { - Implementation = src.Implementation, - VersionNumber = src.VersionNumber, - }; - } - - static MToon.OutlineDefinition ToUnity(this VrmLib.MToon.OutlineDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.OutlineDefinition - { - OutlineColor = src.OutlineColor.ToUnitySRGB(), - OutlineColorMode = (MToon.OutlineColorMode)src.OutlineColorMode, - OutlineLightingMixValue = src.OutlineLightingMixValue, - OutlineScaledMaxDistanceValue = src.OutlineScaledMaxDistanceValue, - OutlineWidthMode = (MToon.OutlineWidthMode)src.OutlineWidthMode, - OutlineWidthMultiplyTexture = textures.GetOrDefault(src.OutlineWidthMultiplyTexture?.Texture), - OutlineWidthValue = src.OutlineWidthValue, - }; - } - - static MToon.RenderingDefinition ToUnity(this VrmLib.MToon.RenderingDefinition src) - { - if (src == null) return null; - return new MToon.RenderingDefinition - { - CullMode = (MToon.CullMode)src.CullMode, - RenderMode = (MToon.RenderMode)src.RenderMode, - RenderQueueOffsetNumber = src.RenderQueueOffsetNumber, - }; - } - - static MToon.RimDefinition ToUnity(this VrmLib.MToon.RimDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.RimDefinition - { - RimColor = src.RimColor.ToUnityLinear(), - RimFresnelPowerValue = src.RimFresnelPowerValue, - RimLiftValue = src.RimLiftValue, - RimLightingMixValue = src.RimLightingMixValue, - RimMultiplyTexture = textures.GetOrDefault(src.RimMultiplyTexture?.Texture), - }; - } - - static MToon.TextureUvCoordsDefinition ToUnity(this VrmLib.MToon.TextureUvCoordsDefinition src, Dictionary textures) - { - if (src == null) return null; - return new MToon.TextureUvCoordsDefinition - { - MainTextureLeftBottomOriginOffset = src.MainTextureLeftBottomOriginOffset.ToUnity(), - MainTextureLeftBottomOriginScale = src.MainTextureLeftBottomOriginScale.ToUnity(), - UvAnimationMaskTexture = textures.GetOrDefault(src.UvAnimationMaskTexture?.Texture), - UvAnimationRotationSpeedValue = src.UvAnimationRotationSpeedValue, - UvAnimationScrollXSpeedValue = src.UvAnimationScrollXSpeedValue, - UvAnimationScrollYSpeedValue = src.UvAnimationScrollYSpeedValue, - }; - } - } -} diff --git a/Assets/VRM10/Runtime/UnityBuilder/MToonLoader.cs.meta b/Assets/VRM10/Runtime/UnityBuilder/MToonLoader.cs.meta deleted file mode 100644 index 2a767777d..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/MToonLoader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8fb046f799feabd48bcdf7bcaf0f0a86 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/UnityBuilder/ModelAsset.cs b/Assets/VRM10/Runtime/UnityBuilder/ModelAsset.cs deleted file mode 100644 index 57026b4db..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/ModelAsset.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -#if UNITY_EDITOR -using UnityEditor; -#endif - -namespace UniVRM10 -{ - - [Serializable] - public class ModelAsset : IDisposable - { - public GameObject Root; - public Avatar HumanoidAvatar; - public List Textures = new List(); - public List Materials = new List(); - public List Meshes = new List(); - public List Renderers = new List(); - - public readonly ModelMap Map = new ModelMap(); - public List ScriptableObjects = new List(); - - private Animator _animator; - public Animator Animator - { - get - { - if (_animator == null) - { - _animator = Root.GetComponent(); - } - return _animator; - } - } - - public void Dispose() - { - GameObject.Destroy(Root); - UnityEngine.Object.Destroy(HumanoidAvatar); - foreach (var v in Textures) - { - UnityEngine.Object.DestroyImmediate(v); - } - foreach (var v in Materials) - { - UnityEngine.Object.DestroyImmediate(v); - } - foreach (var v in Meshes) - { - UnityEngine.Object.DestroyImmediate(v); - } - foreach (var v in ScriptableObjects) - { - ScriptableObject.DestroyImmediate(v); - } - } - -#if UNITY_EDITOR - public void DisposeEditor() - { - if (!Application.isPlaying) - { - if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(Root))) - { - GameObject.DestroyImmediate(Root); - } - if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(HumanoidAvatar))) - { - UnityEngine.Object.DestroyImmediate(HumanoidAvatar); - } - - foreach (var v in Textures) - { - if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(v))) - { - UnityEngine.Object.DestroyImmediate(v); - } - } - foreach (var v in Materials) - { - if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(v))) - { - UnityEngine.Object.DestroyImmediate(v); - } - } - foreach (var v in Meshes) - { - if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(v))) - { - UnityEngine.Object.DestroyImmediate(v); - } - } - foreach (var v in ScriptableObjects) - { - if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(v))) - { - ScriptableObject.DestroyImmediate(v); - } - } - } - } -#endif - } -} diff --git a/Assets/VRM10/Runtime/UnityBuilder/ModelAsset.cs.meta b/Assets/VRM10/Runtime/UnityBuilder/ModelAsset.cs.meta deleted file mode 100644 index 84b3cb403..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/ModelAsset.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 578298355dd7ed4409b08bb8e5cc4316 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/UnityBuilder/ModelMap.cs b/Assets/VRM10/Runtime/UnityBuilder/ModelMap.cs deleted file mode 100644 index 2eae00f45..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/ModelMap.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace UniVRM10 -{ - public class ModelMap - { - public readonly Dictionary Nodes = new Dictionary(); - public readonly Dictionary Textures = new Dictionary(); - public readonly Dictionary Materials = new Dictionary(); - public readonly Dictionary Meshes = new Dictionary(); - public readonly Dictionary Renderers = new Dictionary(); - } -} diff --git a/Assets/VRM10/Runtime/UnityBuilder/ModelMap.cs.meta b/Assets/VRM10/Runtime/UnityBuilder/ModelMap.cs.meta deleted file mode 100644 index d9a7c497a..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/ModelMap.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1a93e36cc818c4f4e87cd0c1daaf16a8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityBuilder.cs b/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityBuilder.cs deleted file mode 100644 index 163f56d17..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityBuilder.cs +++ /dev/null @@ -1,235 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using MeshUtility; -using UnityEngine; -using VrmLib; - -namespace UniVRM10 -{ - /// - /// VrmLib.Model から UnityPrefab を構築する - /// - public static class RuntimeUnityBuilder - { - /// - /// モデル(Transform + Renderer)を構築する。 - /// - public static ModelAsset ToUnityAsset(VrmLib.Model model, bool showMesh = true) - { - var modelAsset = new ModelAsset(); - - // texture - for (int i = 0; i < model.Textures.Count; ++i) - { - var src = model.Textures[i]; - var name = !string.IsNullOrEmpty(src.Name) - ? src.Name - : string.Format("{0}_img{1}", model.Root.Name, i); - if (src is VrmLib.ImageTexture imageTexture) - { - var texture = CreateTexture(imageTexture); - texture.name = name; - modelAsset.Map.Textures.Add(src, texture); - modelAsset.Textures.Add(texture); - } - else - { - Debug.LogWarning($"{name} not ImageTexture"); - } - } - - // material - foreach (var src in model.Materials) - { - // TODO: material has VertexColor - var material = RuntimeUnityMaterialBuilder.CreateMaterialAsset(src, hasVertexColor: false, modelAsset.Map.Textures); - material.name = src.Name; - modelAsset.Map.Materials.Add(src, material); - modelAsset.Materials.Add(material); - } - - // mesh - for (int i = 0; i < model.MeshGroups.Count; ++i) - { - var src = model.MeshGroups[i]; - if (src.Meshes.Count == 1) - { - // submesh 方式 - var mesh = new UnityEngine.Mesh(); - mesh.name = src.Name; - mesh.LoadMesh(src.Meshes[0], src.Skin); - modelAsset.Map.Meshes.Add(src, mesh); - modelAsset.Meshes.Add(mesh); - } - else - { - // 頂点バッファの連結が必用 - throw new NotImplementedException(); - } - } - - // node: recursive - CreateNodes(model.Root, null, modelAsset.Map.Nodes); - modelAsset.Root = modelAsset.Map.Nodes[model.Root]; - - // renderer - var map = modelAsset.Map; - foreach (var (node, go) in map.Nodes) - { - if (node.MeshGroup is null) - { - continue; - } - - if (node.MeshGroup.Meshes.Count > 1) - { - throw new NotImplementedException("invalid isolated vertexbuffer"); - } - - var renderer = CreateRenderer(node, go, map); - if (!showMesh) - { - renderer.enabled = false; - } - map.Renderers.Add(node, renderer); - modelAsset.Renderers.Add(renderer); - } - - var humanoid = modelAsset.Root.AddComponent(); - humanoid.AssignBones(map.Nodes.Select(x => (x.Key.HumanoidBone.GetValueOrDefault().ToUnity(), x.Value.transform))); - modelAsset.HumanoidAvatar = humanoid.CreateAvatar(); - modelAsset.HumanoidAvatar.name = "VRM"; - - var animator = modelAsset.Root.AddComponent(); - animator.avatar = modelAsset.HumanoidAvatar; - - return modelAsset; - } - - public static HumanBodyBones ToUnity(this VrmLib.HumanoidBones bone) - { - if (bone == VrmLib.HumanoidBones.unknown) - { - return HumanBodyBones.LastBone; - } - return VrmLib.EnumUtil.Cast(bone); - } - - private static RenderTextureReadWrite GetRenderTextureReadWrite(VrmLib.Texture.ColorSpaceTypes type) - { - return (type == VrmLib.Texture.ColorSpaceTypes.Linear) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB; - } - - /// - /// 画像のバイト列からテクスチャを作成する - /// - public static Texture2D CreateTexture(VrmLib.ImageTexture imageTexture) - { - Texture2D dstTexture = null; - UnityEngine.Material convertMaterial = null; - var texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, imageTexture.ColorSpace == VrmLib.Texture.ColorSpaceTypes.Linear); - texture.LoadImage(imageTexture.Image.Bytes.ToArray()); - - // Convert Texture Gltf to Unity - if (imageTexture.TextureType == VrmLib.Texture.TextureTypes.NormalMap) - { - convertMaterial = TextureConvertMaterial.GetNormalMapConvertGltfToUnity(); - dstTexture = UnityTextureUtil.CopyTexture( - texture, - GetRenderTextureReadWrite(imageTexture.ColorSpace), - convertMaterial); - } - else if (imageTexture.TextureType == VrmLib.Texture.TextureTypes.MetallicRoughness) - { - var metallicRoughnessImage = imageTexture as VrmLib.MetallicRoughnessImageTexture; - convertMaterial = TextureConvertMaterial.GetMetallicRoughnessGltfToUnity(metallicRoughnessImage.RoughnessFactor); - dstTexture = UnityTextureUtil.CopyTexture( - texture, - GetRenderTextureReadWrite(imageTexture.ColorSpace), - convertMaterial); - } - else if (imageTexture.TextureType == VrmLib.Texture.TextureTypes.Occlusion) - { - convertMaterial = TextureConvertMaterial.GetOcclusionGltfToUnity(); - dstTexture = UnityTextureUtil.CopyTexture( - texture, - GetRenderTextureReadWrite(imageTexture.ColorSpace), - convertMaterial); - } - - if (dstTexture != null) - { - if (texture != null) - { - UnityEngine.Object.DestroyImmediate(texture); - } - texture = dstTexture; - } - - if (convertMaterial != null) - { - UnityEngine.Object.DestroyImmediate(convertMaterial); - } - - return texture; - } - - /// - /// ヒエラルキーを再帰的に構築する - /// - public static void CreateNodes(VrmLib.Node node, GameObject parent, Dictionary nodes) - { - GameObject go = new GameObject(node.Name); - go.transform.SetPositionAndRotation(node.Translation.ToUnityVector3(), node.Rotation.ToUnityQuaternion()); - nodes.Add(node, go); - if (parent != null) - { - go.transform.SetParent(parent.transform); - } - - if (node.Children.Count > 0) - { - for (int n = 0; n < node.Children.Count; n++) - { - CreateNodes(node.Children[n], go, nodes); - } - } - } - - /// - /// MeshFilter + MeshRenderer もしくは SkinnedMeshRenderer を構築する - /// - public static Renderer CreateRenderer(VrmLib.Node node, GameObject go, ModelMap map) - { - var mesh = node.MeshGroup.Meshes[0]; - - Renderer renderer = null; - var hasBlendShape = mesh.MorphTargets.Any(); - if (node.MeshGroup.Skin != null || hasBlendShape) - { - var skinnedMeshRenderer = go.AddComponent(); - renderer = skinnedMeshRenderer; - skinnedMeshRenderer.sharedMesh = map.Meshes[node.MeshGroup]; - if (node.MeshGroup.Skin != null) - { - skinnedMeshRenderer.bones = node.MeshGroup.Skin.Joints.Select(x => map.Nodes[x].transform).ToArray(); - if (node.MeshGroup.Skin.Root != null) - { - skinnedMeshRenderer.rootBone = map.Nodes[node.MeshGroup.Skin.Root].transform; - } - } - } - else - { - var meshFilter = go.AddComponent(); - renderer = go.AddComponent(); - meshFilter.sharedMesh = map.Meshes[node.MeshGroup]; - } - var materials = mesh.Submeshes.Select(x => map.Materials[x.Material]).ToArray(); - renderer.sharedMaterials = materials; - - return renderer; - } - } -} diff --git a/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityMaterialBuilder.cs b/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityMaterialBuilder.cs deleted file mode 100644 index 6bfacd2e7..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityMaterialBuilder.cs +++ /dev/null @@ -1,215 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace UniVRM10 -{ - public static class RuntimeUnityMaterialBuilder - { - public static UnityEngine.Material CreateMaterialAsset(VrmLib.Material src, bool hasVertexColor, Dictionary textures) - { - if (src is VrmLib.MToonMaterial mtoonSrc) - { - // MTOON - var material = new Material(Shader.Find(MToon.Utils.ShaderName)); - MToon.Utils.SetMToonParametersToMaterial(material, mtoonSrc.Definition.ToUnity(textures)); - return material; - } - - if (src is VrmLib.UnlitMaterial unlitSrc) - { - return CreateUnlitMaterial(unlitSrc, hasVertexColor, textures); - } - - if (src is VrmLib.PBRMaterial pbrSrc) - { - return CreateStandardMaterial(pbrSrc, textures); - } - - throw new NotImplementedException($"unknown material: {src}"); - } - - static UnityEngine.Material CreateUnlitMaterial(VrmLib.UnlitMaterial src, bool hasVertexColor, Dictionary textures) - { - var material = new Material(Shader.Find(UniGLTF.UniUnlit.Utils.ShaderName)); - - // texture - if (src.BaseColorTexture != null) - { - material.mainTexture = textures[src.BaseColorTexture.Texture]; - } - - // color - material.color = src.BaseColorFactor.ToUnitySRGB(); - - //renderMode - switch (src.AlphaMode) - { - case VrmLib.AlphaModeType.OPAQUE: - UniGLTF.UniUnlit.Utils.SetRenderMode(material, UniGLTF.UniUnlit.UniUnlitRenderMode.Opaque); - break; - - case VrmLib.AlphaModeType.BLEND: - UniGLTF.UniUnlit.Utils.SetRenderMode(material, UniGLTF.UniUnlit.UniUnlitRenderMode.Transparent); - break; - - case VrmLib.AlphaModeType.MASK: - UniGLTF.UniUnlit.Utils.SetRenderMode(material, UniGLTF.UniUnlit.UniUnlitRenderMode.Cutout); - material.SetFloat(UniGLTF.UniUnlit.Utils.PropNameCutoff, src.AlphaCutoff); - break; - - default: - UniGLTF.UniUnlit.Utils.SetRenderMode(material, UniGLTF.UniUnlit.UniUnlitRenderMode.Opaque); - break; - } - - // culling - if (src.DoubleSided) - { - UniGLTF.UniUnlit.Utils.SetCullMode(material, UniGLTF.UniUnlit.UniUnlitCullMode.Off); - } - else - { - UniGLTF.UniUnlit.Utils.SetCullMode(material, UniGLTF.UniUnlit.UniUnlitCullMode.Back); - } - - // VColor - if (hasVertexColor) - { - UniGLTF.UniUnlit.Utils.SetVColBlendMode(material, UniGLTF.UniUnlit.UniUnlitVertexColorBlendOp.Multiply); - } - - UniGLTF.UniUnlit.Utils.ValidateProperties(material, true); - - return material; - } - - // https://forum.unity.com/threads/standard-material-shader-ignoring-setfloat-property-_mode.344557/#post-2229980 - internal enum BlendMode - { - Opaque, - Cutout, - Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency - Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply - } - - static UnityEngine.Material CreateStandardMaterial(VrmLib.PBRMaterial x, Dictionary textures) - { - var material = new Material(Shader.Find("Standard")); - - material.color = x.BaseColorFactor.ToUnitySRGB(); - - if (x.BaseColorTexture != null) - { - material.mainTexture = textures[x.BaseColorTexture.Texture]; - } - - if (x.MetallicRoughnessTexture != null) - { - material.EnableKeyword("_METALLICGLOSSMAP"); - var texture = textures[x.MetallicRoughnessTexture]; - if (texture != null) - { - var prop = "_MetallicGlossMap"; - material.SetTexture(prop, texture); - } - - material.SetFloat("_Metallic", 1.0f); - // Set 1.0f as hard-coded. See: https://github.com/dwango/UniVRM/issues/212. - material.SetFloat("_GlossMapScale", 1.0f); - } - else - { - material.SetFloat("_Metallic", x.MetallicFactor); - material.SetFloat("_Glossiness", 1.0f - x.RoughnessFactor); - } - - if (x.NormalTexture != null) - { - material.EnableKeyword("_NORMALMAP"); - var texture = textures[x.NormalTexture]; - if (texture != null) - { - var prop = "_BumpMap"; - material.SetTexture(prop, texture); - material.SetFloat("_BumpScale", x.NormalTextureScale); - } - } - - if (x.OcclusionTexture != null) - { - var texture = textures[x.OcclusionTexture]; - if (texture != null) - { - var prop = "_OcclusionMap"; - material.SetTexture(prop, texture); - material.SetFloat("_OcclusionStrength", x.OcclusionTextureStrength); - } - } - - if (x.EmissiveFactor != System.Numerics.Vector3.Zero || x.EmissiveTexture != null) - { - material.EnableKeyword("_EMISSION"); - material.globalIlluminationFlags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; - - material.SetColor("_EmissionColor", x.EmissiveFactor.ToUnityColor()); - - if (x.EmissiveTexture != null) - { - var texture = textures[x.EmissiveTexture]; - if (texture != null) - { - material.SetTexture("_EmissionMap", texture); - } - } - } - - BlendMode blendMode = BlendMode.Opaque; - // https://forum.unity.com/threads/standard-material-shader-ignoring-setfloat-property-_mode.344557/#post-2229980 - switch (x.AlphaMode) - { - case VrmLib.AlphaModeType.BLEND: - blendMode = BlendMode.Fade; - material.SetOverrideTag("RenderType", "Transparent"); - material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); - material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); - material.SetInt("_ZWrite", 0); - material.DisableKeyword("_ALPHATEST_ON"); - material.EnableKeyword("_ALPHABLEND_ON"); - material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); - material.renderQueue = 3000; - break; - - case VrmLib.AlphaModeType.MASK: - blendMode = BlendMode.Cutout; - material.SetOverrideTag("RenderType", "TransparentCutout"); - material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); - material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); - material.SetInt("_ZWrite", 1); - material.SetFloat("_Cutoff", x.AlphaCutoff); - material.EnableKeyword("_ALPHATEST_ON"); - material.DisableKeyword("_ALPHABLEND_ON"); - material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); - material.renderQueue = 2450; - - break; - - default: // OPAQUE - blendMode = BlendMode.Opaque; - material.SetOverrideTag("RenderType", ""); - material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); - material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); - material.SetInt("_ZWrite", 1); - material.DisableKeyword("_ALPHATEST_ON"); - material.DisableKeyword("_ALPHABLEND_ON"); - material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); - material.renderQueue = -1; - break; - } - - material.SetFloat("_Mode", (float)blendMode); - return material; - } - - } -} diff --git a/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityMaterialBuilder.cs.meta b/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityMaterialBuilder.cs.meta deleted file mode 100644 index 49ad66594..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/RuntimeUnityMaterialBuilder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2a34b3bcd188eb54d8153527bb11d248 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/UnityBuilder/UnityExtension.cs b/Assets/VRM10/Runtime/UnityBuilder/UnityExtension.cs deleted file mode 100644 index 97e827351..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/UnityExtension.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using VrmLib; - -namespace UniVRM10 -{ - public static class UnityExtension - { - public static Vector3 ToUnityVector3(this System.Numerics.Vector3 value) - { - return new Vector3(value.X, value.Y, value.Z); - } - - public static float[] ToFloat3(this System.Numerics.Vector3 value) - { - return new[] { value.X, value.Y, value.Z }; - } - - public static Color ToUnityColor(this System.Numerics.Vector3 value) - { - return new Color(value.X, value.Y, value.Z, 1); - } - - public static Vector4 ToUnityVector4(this System.Numerics.Vector4 value) - { - return new Vector4(value.X, value.Y, value.Z, value.W); - } - - public static Color ToUnityColor(this System.Numerics.Vector4 value) - { - return new Color(value.X, value.Y, value.Z, value.W); - } - - public static Color ToUnitySRGB(this VrmLib.LinearColor value) - { - return value.RGBA.ToUnityColor().gamma; - } - - public static Color ToUnityLinear(this VrmLib.LinearColor value) - { - return value.RGBA.ToUnityColor(); - } - - public static Quaternion ToUnityQuaternion(this System.Numerics.Quaternion value) - { - return new Quaternion(value.X, value.Y, value.Z, value.W); - } - - public static float[] ToFloat4(this System.Numerics.Quaternion value) - { - return new float[] { value.X, value.Y, value.Z, value.W }; - } - - public static System.Numerics.Vector2 ToNumericsVector2(this Vector2 value) - { - return new System.Numerics.Vector2(value.x, value.y); - } - - public static System.Numerics.Vector3 ToNumericsVector3(this Vector3 value) - { - return new System.Numerics.Vector3(value.x, value.y, value.z); - } - - public static System.Numerics.Vector4 ToNumericsVector4(this Vector4 value) - { - return new System.Numerics.Vector4(value.x, value.y, value.z, value.w); - } - - /// UnityのMaterialのColor値はSRGBで格納されている - public static VrmLib.LinearColor FromUnitySrgbToLinear(this Color value) - { - value = value.linear; - return new VrmLib.LinearColor - { - RGBA = new System.Numerics.Vector4(value.r, value.g, value.b, value.a) - }; - } - - public static VrmLib.LinearColor FromUnityLinear(this Color value) - { - return new VrmLib.LinearColor - { - RGBA = new System.Numerics.Vector4(value.r, value.g, value.b, value.a) - }; - } - - public static System.Numerics.Vector4 ToVector4(this Color value) - { - return new System.Numerics.Vector4(value.r, value.g, value.b, value.a); - } - - public static System.Numerics.Quaternion ToNumericsQuaternion(this Quaternion value) - { - return new System.Numerics.Quaternion(value.x, value.y, value.z, value.w); - } - - public static System.Numerics.Matrix4x4 ToNumericsMatrix4x4(this Matrix4x4 value) - { - return new System.Numerics.Matrix4x4( - value.m00, value.m01, value.m02, value.m03, - value.m10, value.m11, value.m12, value.m13, - value.m20, value.m21, value.m22, value.m23, - value.m30, value.m31, value.m32, value.m33 - ); - } - - public static VrmLib.Image ToPngImage(this UnityEngine.Texture2D texture, VrmLib.ImageUsage imageUsage) - { - if (texture != null) - { - return new VrmLib.Image(texture.name, "image/png", imageUsage, new System.ArraySegment(texture.EncodeToPNG())); - } - else - { - return null; - } - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/Runtime/UnityBuilder/VrmLoader.cs b/Assets/VRM10/Runtime/UnityBuilder/VrmLoader.cs deleted file mode 100644 index 1c0159475..000000000 --- a/Assets/VRM10/Runtime/UnityBuilder/VrmLoader.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.IO; -using VrmLib; -using UniJSON; - -namespace UniVRM10 -{ - /// - /// utility for load VrmLib Model from byte[] - /// - public static class VrmLoader - { - // TODO: - const string VRM0X_LICENSE_URL = "https://vrm-consortium.org/"; - - /// - /// Load VRM10 or VRM0x from path - /// - public static Model CreateVrmModel(string path) - { - var bytes = File.ReadAllBytes(path); - return CreateVrmModel(bytes, new FileInfo(path)); - } - - public static Model CreateVrmModel(byte[] bytes, FileInfo path) - { - if (!UniGLTF.Glb.TryParse(bytes, out UniGLTF.Glb glb, out Exception ex)) - { - throw ex; - } - - var json = glb.Json.Bytes.ParseAsJson(); - - var extensions = json["extensions"]; - - foreach (var kv in extensions.ObjectItems()) - { - switch (kv.Key.GetString()) - { - // case "VRM": - // { - // var storage = new Vrm10Storage(glb.Json.Bytes, glb.Binary.Bytes); - // var model = ModelLoader.Load(storage, path.Name); - // model.ConvertCoordinate(Coordinates.Unity); - // return model; - // } - - case "VRMC_vrm": - { - var storage = new Vrm10Storage(glb.Json.Bytes, glb.Binary.Bytes); - var model = ModelLoader.Load(storage, path.Name); - model.ConvertCoordinate(Coordinates.Unity); - return model; - } - } - } - - // this is error - // throw new NotImplementedException(); - return null; - } - } -} diff --git a/Assets/VRM10/Runtime/VRM10.asmdef b/Assets/VRM10/Runtime/VRM10.asmdef index 8bec55972..de687fb35 100644 --- a/Assets/VRM10/Runtime/VRM10.asmdef +++ b/Assets/VRM10/Runtime/VRM10.asmdef @@ -6,7 +6,8 @@ "MToon", "MeshUtility", "MeshUtility.Editor", - "UniGLTF" + "UniGLTF", + "VRMShaders" ], "optionalUnityReferences": [], "includePlatforms": [], diff --git a/Assets/VRM10/Runtime/VRMConverter.meta b/Assets/VRM10/Runtime/VRMConverter.meta deleted file mode 100644 index 40c354149..000000000 --- a/Assets/VRM10/Runtime/VRMConverter.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: ee97e5dbbc50ad74593d5099908bc26b -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/VRMConverter/MToonExport.cs b/Assets/VRM10/Runtime/VRMConverter/MToonExport.cs deleted file mode 100644 index 0b1def87d..000000000 --- a/Assets/VRM10/Runtime/VRMConverter/MToonExport.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using UnityEngine; - -namespace UniVRM10 -{ - public static class MToonExtensions - { - public static VrmLib.TextureMagFilterType ToVrmLibMagFilter(this FilterMode mode) - { - switch (mode) - { - case FilterMode.Bilinear: - case FilterMode.Trilinear: - return VrmLib.TextureMagFilterType.LINEAR; - case FilterMode.Point: - return VrmLib.TextureMagFilterType.NEAREST; - - default: - throw new NotImplementedException(); - } - } - - public static VrmLib.TextureMinFilterType ToVrmLibMinFilter(this FilterMode mode) - { - switch (mode) - { - case FilterMode.Bilinear: - case FilterMode.Trilinear: - return VrmLib.TextureMinFilterType.LINEAR; - case FilterMode.Point: - return VrmLib.TextureMinFilterType.NEAREST; - - default: - throw new NotImplementedException(); - } - } - - public static VrmLib.TextureWrapType ToVrmLib(this TextureWrapMode mode) - { - switch (mode) - { - case TextureWrapMode.Clamp: - return VrmLib.TextureWrapType.CLAMP_TO_EDGE; - - case TextureWrapMode.Repeat: - return VrmLib.TextureWrapType.REPEAT; - - case TextureWrapMode.Mirror: - return VrmLib.TextureWrapType.MIRRORED_REPEAT; - - default: - throw new NotImplementedException(); - } - } - - /// - /// MToon.MToonDefinition(Unity) を VrmLib.MToon.MToonDefinition に変換する - /// - public static VrmLib.MToon.MToonDefinition ToVrmLib(this global::MToon.MToonDefinition unity, - Material material, - GetOrCreateTextureDelegate getOrCreateTexture) - { - return new VrmLib.MToon.MToonDefinition - { - Color = new VrmLib.MToon.ColorDefinition - { - CutoutThresholdValue = unity.Color.CutoutThresholdValue, - LitColor = unity.Color.LitColor.FromUnitySrgbToLinear(), - LitMultiplyTexture = unity.Color.LitMultiplyTexture.ToVrmLib(getOrCreateTexture, material, VrmLib.Texture.ColorSpaceTypes.Srgb), - ShadeColor = unity.Color.ShadeColor.FromUnitySrgbToLinear(), - ShadeMultiplyTexture = unity.Color.ShadeMultiplyTexture.ToVrmLib(getOrCreateTexture, material, VrmLib.Texture.ColorSpaceTypes.Srgb), - }, - Emission = new VrmLib.MToon.EmissionDefinition - { - EmissionColor = unity.Emission.EmissionColor.FromUnityLinear(), - EmissionMultiplyTexture = unity.Emission.EmissionMultiplyTexture.ToVrmLib(getOrCreateTexture, material, VrmLib.Texture.ColorSpaceTypes.Srgb), - }, - Lighting = new VrmLib.MToon.LightingDefinition - { - LightingInfluence = new VrmLib.MToon.LightingInfluenceDefinition - { - GiIntensityValue = unity.Lighting.LightingInfluence.GiIntensityValue, - LightColorAttenuationValue = unity.Lighting.LightingInfluence.LightColorAttenuationValue, - }, - LitAndShadeMixing = new VrmLib.MToon.LitAndShadeMixingDefinition - { - ShadingShiftValue = unity.Lighting.LitAndShadeMixing.ShadingShiftValue, - ShadingToonyValue = unity.Lighting.LitAndShadeMixing.ShadingToonyValue, - }, - Normal = new VrmLib.MToon.NormalDefinition - { - NormalScaleValue = unity.Lighting.Normal.NormalScaleValue, - NormalTexture = unity.Lighting.Normal.NormalTexture.ToVrmLib(getOrCreateTexture, material, VrmLib.Texture.ColorSpaceTypes.Linear, VrmLib.Texture.TextureTypes.NormalMap), - }, - }, - MatCap = new VrmLib.MToon.MatCapDefinition - { - AdditiveTexture = unity.MatCap.AdditiveTexture.ToVrmLib(getOrCreateTexture, material, VrmLib.Texture.ColorSpaceTypes.Srgb), - }, - Meta = new VrmLib.MToon.MetaDefinition - { - Implementation = unity.Meta.Implementation, - VersionNumber = unity.Meta.VersionNumber, - }, - Outline = new VrmLib.MToon.OutlineDefinition - { - OutlineColor = unity.Outline.OutlineColor.FromUnitySrgbToLinear(), - OutlineColorMode = (VrmLib.MToon.OutlineColorMode)unity.Outline.OutlineColorMode, - OutlineLightingMixValue = unity.Outline.OutlineLightingMixValue, - OutlineScaledMaxDistanceValue = unity.Outline.OutlineScaledMaxDistanceValue, - OutlineWidthMode = (VrmLib.MToon.OutlineWidthMode)unity.Outline.OutlineWidthMode, - OutlineWidthMultiplyTexture = unity.Outline.OutlineWidthMultiplyTexture.ToVrmLib(getOrCreateTexture, material, VrmLib.Texture.ColorSpaceTypes.Linear), - OutlineWidthValue = unity.Outline.OutlineWidthValue, - }, - Rendering = new VrmLib.MToon.RenderingDefinition - { - CullMode = (VrmLib.MToon.CullMode)unity.Rendering.CullMode, - RenderMode = (VrmLib.MToon.RenderMode)unity.Rendering.RenderMode, - RenderQueueOffsetNumber = unity.Rendering.RenderQueueOffsetNumber, - }, - Rim = new VrmLib.MToon.RimDefinition - { - RimColor = unity.Rim.RimColor.FromUnityLinear(), - RimFresnelPowerValue = unity.Rim.RimFresnelPowerValue, - RimLiftValue = unity.Rim.RimLiftValue, - RimLightingMixValue = unity.Rim.RimLightingMixValue, - RimMultiplyTexture = unity.Rim.RimMultiplyTexture.ToVrmLib(getOrCreateTexture, material, VrmLib.Texture.ColorSpaceTypes.Srgb), - }, - TextureOption = new VrmLib.MToon.TextureUvCoordsDefinition - { - MainTextureLeftBottomOriginOffset = unity.TextureOption.MainTextureLeftBottomOriginOffset.ToNumericsVector2(), - MainTextureLeftBottomOriginScale = unity.TextureOption.MainTextureLeftBottomOriginScale.ToNumericsVector2(), - UvAnimationMaskTexture = unity.TextureOption.UvAnimationMaskTexture.ToVrmLib(getOrCreateTexture, material, VrmLib.Texture.ColorSpaceTypes.Linear), - UvAnimationRotationSpeedValue = unity.TextureOption.UvAnimationRotationSpeedValue, - UvAnimationScrollXSpeedValue = unity.TextureOption.UvAnimationScrollXSpeedValue, - UvAnimationScrollYSpeedValue = unity.TextureOption.UvAnimationScrollYSpeedValue, - }, - }; - } - - static VrmLib.TextureInfo ToVrmLib(this Texture2D src, GetOrCreateTextureDelegate map, Material material, VrmLib.Texture.ColorSpaceTypes colorSpace, VrmLib.Texture.TextureTypes textureType = VrmLib.Texture.TextureTypes.Default) - { - return map(material, src, colorSpace, textureType); - } - } -} diff --git a/Assets/VRM10/Runtime/VRMConverter/MToonExport.cs.meta b/Assets/VRM10/Runtime/VRMConverter/MToonExport.cs.meta deleted file mode 100644 index 1498f72f5..000000000 --- a/Assets/VRM10/Runtime/VRMConverter/MToonExport.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a54f187c333215b438b2711790de1237 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Runtime/VRMConverter/RuntimeVrmConverter.cs b/Assets/VRM10/Runtime/VRMConverter/RuntimeVrmConverter.cs deleted file mode 100644 index 47c952cf1..000000000 --- a/Assets/VRM10/Runtime/VRMConverter/RuntimeVrmConverter.cs +++ /dev/null @@ -1,850 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using MeshUtility; -using UnityEngine; -using VrmLib; - -namespace UniVRM10 -{ - public delegate VrmLib.TextureInfo GetOrCreateTextureDelegate(UnityEngine.Material material, UnityEngine.Texture srcTexture, VrmLib.Texture.ColorSpaceTypes colorSpace, VrmLib.Texture.TextureTypes textureType); - public class RuntimeVrmConverter - { - public VrmLib.Model Model; - - public Dictionary Nodes = new Dictionary(); - public Dictionary Textures = new Dictionary(); - public Dictionary Materials = new Dictionary(); - public Dictionary Meshes = new Dictionary(); - - static string GetSupportedMime(string path) - { - var ext = Path.GetExtension(path).ToLower(); - switch (ext) - { - case ".png": return "image/png"; - case ".jpg": return "image/jpeg"; - } - - // .tga etc - return null; - } - - /// - /// return (bytes, mime string) - /// - static (byte[], string) GetImageEncodedBytes(UnityEngine.Texture src, RenderTextureReadWrite renderTextureReadWrite, UnityEngine.Material renderMaterial = null) - { -#if false - /// 元になるアセットがあればそれを得る(png, jpgのみ) - var assetPath = UnityEditor.AssetDatabase.GetAssetPath(src); - if (!string.IsNullOrEmpty(assetPath)) - { - var mime = GetSupportedMime(assetPath); - if (!string.IsNullOrEmpty(mime)) - { - return (File.ReadAllBytes(assetPath), GetSupportedMime(assetPath)); - } - } -#endif - - var copy = UnityTextureUtil.CopyTexture(src, renderTextureReadWrite, renderMaterial); - return (copy.EncodeToPNG(), "image/png"); - } - - public VrmLib.TextureInfo GetOrCreateTexture(UnityEngine.Material material, UnityEngine.Texture srcTexture, VrmLib.Texture.ColorSpaceTypes colorSpace, VrmLib.Texture.TextureTypes textureType) - { - var texture = srcTexture as Texture2D; - if (texture is null) - { - return null; - } - - if (!Textures.TryGetValue(texture, out VrmLib.TextureInfo info)) - { - UnityEngine.Material converter = null; - if (textureType == VrmLib.Texture.TextureTypes.NormalMap) - { - converter = TextureConvertMaterial.GetNormalMapConvertUnityToGltf(); - } - else if (textureType == VrmLib.Texture.TextureTypes.MetallicRoughness) - { - float smoothness = 0.0f; - if (material.HasProperty("_GlossMapScale")) - { - smoothness = material.GetFloat("_GlossMapScale"); - } - - converter = TextureConvertMaterial.GetMetallicRoughnessUnityToGltf(smoothness); - } - else if (textureType == VrmLib.Texture.TextureTypes.Occlusion) - { - converter = TextureConvertMaterial.GetOcclusionUnityToGltf(); - } - - var (bytes, mime) = GetImageEncodedBytes( - texture, - (colorSpace == VrmLib.Texture.ColorSpaceTypes.Linear) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB, - converter - ); - - if (converter != null) - { - UnityEngine.Object.DestroyImmediate(converter); - } - - var sampler = new VrmLib.TextureSampler - { - MagFilter = texture.filterMode.ToVrmLibMagFilter(), - MinFilter = texture.filterMode.ToVrmLibMinFilter(), - WrapS = texture.wrapMode.ToVrmLib(), - WrapT = texture.wrapMode.ToVrmLib(), - }; - var image = new VrmLib.Image(texture.name, mime, VrmLib.ImageUsage.None, new ArraySegment(bytes)); - info = new VrmLib.TextureInfo(new VrmLib.ImageTexture(texture.name, sampler, image, colorSpace, textureType)); - Textures.Add(texture, info); - - if (Model != null) - { - Model.Images.Add(image); - Model.Textures.Add(info.Texture); - } - } - - return info; - } - - #region Export 1.0 - /// - /// VRM-0.X の MaterialBindValue を VRM-1.0 仕様に変換する - /// - /// * Property名 => enum MaterialBindType - /// * 特に _MainTex_ST の場合、MaterialBindType.UvScale + MaterialBindType.UvScale 2つになりうる - /// - /// - VrmLib.Expression ToVrmLib(VRM10Expression clip, GameObject root) - { - var expression = new VrmLib.Expression(clip.Preset, clip.ExpressionName, clip.IsBinary); - expression.OverrideBlink = EnumUtil.Cast(clip.OverrideBlink); - expression.OverrideLookAt = EnumUtil.Cast(clip.OverrideLookAt); - expression.OverrideMouth = EnumUtil.Cast(clip.OverrideMouth); - - foreach (var binding in clip.MorphTargetBindings) - { - var transform = GetTransformFromRelativePath(root.transform, binding.RelativePath); - if (transform == null) - continue; - var renderer = transform.gameObject.GetComponent(); - if (renderer == null) - continue; - var mesh = renderer.sharedMesh; - if (mesh == null) - continue; - - var names = new List(); - for (int i = 0; i < mesh.blendShapeCount; ++i) - { - names.Add(mesh.GetBlendShapeName(i)); - } - - var node = Nodes[transform.gameObject]; - var blendShapeValue = new VrmLib.MorphTargetBind( - node, - names[binding.Index], - // Unity Range [0-100] to VRM-1.0 Range [0-1.0] - binding.Weight * 0.01f - ); - expression.MorphTargetBinds.Add(blendShapeValue); - } - - foreach (var binding in clip.MaterialColorBindings) - { - var materialPair = Materials.FirstOrDefault(x => x.Key.name == binding.MaterialName); - if (materialPair.Value != null) - { - var bind = new VrmLib.MaterialColorBind( - materialPair.Value, - binding.BindType, - binding.TargetValue.ToNumericsVector4() - ); - expression.MaterialColorBinds.Add(bind); - } - } - - foreach (var binding in clip.MaterialUVBindings) - { - var materialPair = Materials.FirstOrDefault(x => x.Key.name == binding.MaterialName); - if (materialPair.Value != null) - { - var bind = new VrmLib.TextureTransformBind( - materialPair.Value, - binding.Scaling.ToNumericsVector2(), - binding.Offset.ToNumericsVector2() - ); - expression.TextureTransformBinds.Add(bind); - } - } - - return expression; - } - - /// - /// metaObject が null のときは、root から取得する - /// - public VrmLib.Model ToModelFrom10(GameObject root, VRM10MetaObject metaObject = null) - { - Model = new VrmLib.Model(VrmLib.Coordinates.Unity); - - if (metaObject is null) - { - var vrmController = root.GetComponent(); - if (vrmController is null || vrmController.Meta is null) - { - throw new NullReferenceException("metaObject is null"); - } - metaObject = vrmController.Meta; - } - - ToGlbModel(root); - - // meta - var meta = new VrmLib.Meta(); - meta.Name = metaObject.Name; - meta.Version = metaObject.Version; - meta.CopyrightInformation = metaObject.CopyrightInformation; - meta.Authors.AddRange(metaObject.Authors); - meta.ContactInformation = metaObject.ContactInformation; - meta.Reference = metaObject.Reference; - meta.Thumbnail = metaObject.Thumbnail.ToPngImage(VrmLib.ImageUsage.None); - - meta.AvatarPermission = new VrmLib.AvatarPermission - { - AvatarUsage = metaObject.AllowedUser, - IsAllowedViolentUsage = metaObject.ViolentUsage, - IsAllowedSexualUsage = metaObject.SexualUsage, - CommercialUsage = metaObject.CommercialUsage, - IsAllowedGameUsage = metaObject.GameUsage, - IsAllowedPoliticalOrReligiousUsage = metaObject.PoliticalOrReligiousUsage, - OtherPermissionUrl = metaObject.OtherPermissionUrl, - }; - meta.RedistributionLicense = new VrmLib.RedistributionLicense - { - CreditNotation = metaObject.CreditNotation, - IsAllowRedistribution = metaObject.Redistribution, - ModificationLicense = metaObject.ModificationLicense, - OtherLicenseUrl = metaObject.OtherLicenseUrl, - }; - Model.Vrm = new VrmLib.Vrm(meta, UniVRM10.VRMVersion.VERSION, UniVRM10.VRMSpecVersion.Version); - - // humanoid - { - var humanoid = root.GetComponent(); - if (humanoid is null) - { - humanoid = root.AddComponent(); - humanoid.AssignBonesFromAnimator(); - } - - foreach (HumanBodyBones humanBoneType in Enum.GetValues(typeof(HumanBodyBones))) - { - var transform = humanoid.GetBoneTransform(humanBoneType); - if (transform != null && Nodes.TryGetValue(transform.gameObject, out VrmLib.Node node)) - { - node.HumanoidBone = (VrmLib.HumanoidBones)Enum.Parse(typeof(VrmLib.HumanoidBones), humanBoneType.ToString(), true); - } - } - } - - - // blendShape - var controller = root.GetComponent(); - if (controller != null) - { - { - Model.Vrm.ExpressionManager = new VrmLib.ExpressionManager(); - if (controller != null) - { - foreach (var clip in controller.Expression.ExpressionAvatar.Clips) - { - var expression = ToVrmLib(clip, root); - if (expression != null) - { - Model.Vrm.ExpressionManager.ExpressionList.Add(expression); - } - } - } - } - - // firstPerson - { - var firstPerson = new VrmLib.FirstPerson(); - if (controller != null) - { - foreach (var annotation in controller.FirstPerson.Renderers) - { - firstPerson.Annotations.Add( - new VrmLib.FirstPersonMeshAnnotation(Nodes[annotation.Renderer.gameObject], - annotation.FirstPersonFlag) - ); - } - Model.Vrm.FirstPerson = firstPerson; - } - } - - // lookAt - { - var lookAt = new VrmLib.LookAt(); - if (controller != null) - { - if (controller.LookAt.LookAtType == VRM10ControllerLookAt.LookAtTypes.Expression) - { - lookAt.HorizontalInner = new VrmLib.LookAtRangeMap(); - lookAt.HorizontalOuter = new VrmLib.LookAtRangeMap() - { - InputMaxValue = controller.LookAt.HorizontalOuter.CurveXRangeDegree, - OutputScaling = controller.LookAt.HorizontalOuter.CurveYRangeDegree - }; - lookAt.VerticalUp = new VrmLib.LookAtRangeMap() - { - InputMaxValue = controller.LookAt.VerticalUp.CurveXRangeDegree, - OutputScaling = controller.LookAt.VerticalUp.CurveYRangeDegree, - }; - lookAt.VerticalDown = new VrmLib.LookAtRangeMap() - { - InputMaxValue = controller.LookAt.VerticalDown.CurveXRangeDegree, - OutputScaling = controller.LookAt.VerticalDown.CurveYRangeDegree, - }; - } - else if (controller.LookAt.LookAtType == VRM10ControllerLookAt.LookAtTypes.Bone) - { - lookAt.HorizontalInner = new VrmLib.LookAtRangeMap() - { - InputMaxValue = controller.LookAt.HorizontalInner.CurveXRangeDegree, - OutputScaling = controller.LookAt.HorizontalInner.CurveYRangeDegree - }; - lookAt.HorizontalOuter = new VrmLib.LookAtRangeMap() - { - InputMaxValue = controller.LookAt.HorizontalOuter.CurveXRangeDegree, - OutputScaling = controller.LookAt.HorizontalOuter.CurveYRangeDegree - }; - lookAt.VerticalUp = new VrmLib.LookAtRangeMap() - { - InputMaxValue = controller.LookAt.VerticalUp.CurveXRangeDegree, - OutputScaling = controller.LookAt.VerticalUp.CurveYRangeDegree, - }; - lookAt.VerticalDown = new VrmLib.LookAtRangeMap() - { - InputMaxValue = controller.LookAt.VerticalDown.CurveXRangeDegree, - OutputScaling = controller.LookAt.VerticalDown.CurveYRangeDegree, - }; - } - lookAt.OffsetFromHeadBone = controller.LookAt.OffsetFromHead.ToNumericsVector3(); - } - Model.Vrm.LookAt = lookAt; - } - - // springBone - { - var springBoneManager = controller.SpringBone; - foreach (var springBone in springBoneManager.Springs) - { - var vrmSpringBone = new VrmLib.SpringBone() - { - Comment = springBone.m_comment, - Origin = (springBone.m_center != null) ? Nodes[springBone.m_center.gameObject] : null, - }; - - foreach (var joint in springBone.Joints) - { - vrmSpringBone.Joints.Add(new VrmLib.SpringJoint(Nodes[joint.Transform.gameObject]) - { - Stiffness = joint.m_stiffnessForce, - GravityPower = joint.m_gravityPower, - GravityDir = joint.m_gravityDir.ToNumericsVector3(), - DragForce = joint.m_dragForce, - HitRadius = joint.m_jointRadius, - Exclude = joint.m_exclude, - }); - } - - foreach (var colliderGroup in springBone.ColliderGroups) - { - var colliderGroups = colliderGroup.Colliders.Select(x => - { - switch (x.ColliderType) - { - case VRM10SpringBoneColliderTypes.Sphere: - return VrmLib.VrmSpringBoneCollider.CreateSphere(x.Offset.ToNumericsVector3(), x.Radius); - - case VRM10SpringBoneColliderTypes.Capsule: - return VrmLib.VrmSpringBoneCollider.CreateCapsule(x.Offset.ToNumericsVector3(), x.Radius, x.Tail.ToNumericsVector3()); - - default: - throw new NotImplementedException(); - } - }); - var vrmColliderGroup = new VrmLib.SpringBoneColliderGroup(Nodes[colliderGroup.gameObject], colliderGroups); - vrmSpringBone.Colliders.Add(vrmColliderGroup); - } - - Model.Vrm.SpringBone.Springs.Add(vrmSpringBone); - } - } - } - - return Model; - } - - public VrmLib.Model ToGlbModel(GameObject root) - { - if (Model == null) - { - Model = new VrmLib.Model(VrmLib.Coordinates.Unity); - } - - // node - { - Model.Root.Name = root.name; - CreateNodes(root.transform, Model.Root, Nodes); - Model.Nodes = Nodes - .Where(x => x.Value != Model.Root) - .Select(x => x.Value).ToList(); - } - - // material and textures - var rendererComponents = root.GetComponentsInChildren(); - { - foreach (var renderer in rendererComponents) - { - var materials = renderer.sharedMaterials; // avoid copy - foreach (var material in materials) - { - if (Materials.ContainsKey(material)) - { - continue; - } - - var vrmMaterial = Export10(material, GetOrCreateTexture); - Model.Materials.Add(vrmMaterial); - Materials.Add(material, vrmMaterial); - } - } - } - - // mesh - { - foreach (var renderer in rendererComponents) - { - if (renderer is SkinnedMeshRenderer skinnedMeshRenderer) - { - if (skinnedMeshRenderer.sharedMesh != null) - { - var mesh = CreateMesh(skinnedMeshRenderer.sharedMesh, skinnedMeshRenderer, Materials); - var skin = CreateSkin(skinnedMeshRenderer, Nodes, root); - if (skin != null) - { - // blendshape only で skinning が無いやつがある - mesh.Skin = skin; - Model.Skins.Add(mesh.Skin); - } - Model.MeshGroups.Add(mesh); - Nodes[renderer.gameObject].MeshGroup = mesh; - Meshes.Add(skinnedMeshRenderer.sharedMesh, mesh); - } - } - else if (renderer is MeshRenderer meshRenderer) - { - var filter = meshRenderer.gameObject.GetComponent(); - if (filter != null && filter.sharedMesh != null) - { - var mesh = CreateMesh(filter.sharedMesh, meshRenderer, Materials); - Model.MeshGroups.Add(mesh); - Nodes[renderer.gameObject].MeshGroup = mesh; - Meshes.Add(filter.sharedMesh, mesh); - } - } - } - } - - return Model; - } - #endregion - - public VrmLib.Material Export10(UnityEngine.Material src, GetOrCreateTextureDelegate map) - { - switch (src.shader.name) - { - case "VRM/MToon": - { - var def = MToon.Utils.GetMToonParametersFromMaterial(src); - return new VrmLib.MToonMaterial(src.name) - { - Definition = def.ToVrmLib(src, map), - }; - } - - case "Unlit/Color": - return new VrmLib.UnlitMaterial(src.name) - { - BaseColorFactor = src.color.FromUnitySrgbToLinear(), - }; - - case "Unlit/Texture": - return new VrmLib.UnlitMaterial(src.name) - { - BaseColorTexture = map(src, src.mainTexture as Texture2D, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default), - }; - - case "Unlit/Transparent": - return new VrmLib.UnlitMaterial(src.name) - { - BaseColorTexture = map(src, src.mainTexture as Texture2D, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default), - AlphaMode = VrmLib.AlphaModeType.BLEND, - }; - - case "Unlit/Transparent Cutout": - return new VrmLib.UnlitMaterial(src.name) - { - BaseColorTexture = map(src, src.mainTexture as Texture2D, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default), - AlphaMode = VrmLib.AlphaModeType.MASK, - AlphaCutoff = src.GetFloat("_Cutoff"), - }; - - case "UniGLTF/UniUnlit": - case "VRM/UniUnlit": - { - var material = new VrmLib.UnlitMaterial(src.name) - { - BaseColorFactor = src.color.FromUnitySrgbToLinear(), - BaseColorTexture = map(src, src.mainTexture as Texture2D, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default), - AlphaMode = GetAlphaMode(src), - DoubleSided = UniGLTF.UniUnlit.Utils.GetCullMode(src) == UniGLTF.UniUnlit.UniUnlitCullMode.Off, - }; - if (material.AlphaMode == VrmLib.AlphaModeType.MASK) - { - material.AlphaCutoff = src.GetFloat("_Cutoff"); - } - // TODO: VertexColorMode - return material; - } - - default: - return ExportStandard(src, map); - } - } - - static VrmLib.AlphaModeType GetAlphaMode(UnityEngine.Material m) - { - switch (UniGLTF.UniUnlit.Utils.GetRenderMode(m)) - { - case UniGLTF.UniUnlit.UniUnlitRenderMode.Opaque: return VrmLib.AlphaModeType.OPAQUE; - case UniGLTF.UniUnlit.UniUnlitRenderMode.Cutout: return VrmLib.AlphaModeType.MASK; - case UniGLTF.UniUnlit.UniUnlitRenderMode.Transparent: return VrmLib.AlphaModeType.BLEND; - } - throw new NotImplementedException(); - } - - static VrmLib.PBRMaterial ExportStandard(UnityEngine.Material src, GetOrCreateTextureDelegate map) - { - var material = new VrmLib.PBRMaterial(src.name) - { - }; - - switch (src.GetTag("RenderType", true)) - { - case "Transparent": - material.AlphaMode = VrmLib.AlphaModeType.BLEND; - break; - - case "TransparentCutout": - material.AlphaMode = VrmLib.AlphaModeType.MASK; - material.AlphaCutoff = src.GetFloat("_Cutoff"); - break; - - default: - material.AlphaMode = VrmLib.AlphaModeType.OPAQUE; - break; - } - - if (src.HasProperty("_Color")) - { - material.BaseColorFactor = src.color.linear.FromUnitySrgbToLinear(); - } - - if (src.HasProperty("_MainTex")) - { - material.BaseColorTexture = map(src, src.GetTexture("_MainTex"), VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default); - } - - if (src.HasProperty("_MetallicGlossMap")) - { - // float smoothness = 0.0f; - // if (m.HasProperty("_GlossMapScale")) - // { - // smoothness = m.GetFloat("_GlossMapScale"); - // } - - material.MetallicRoughnessTexture = map( - src, - src.GetTexture("_MetallicGlossMap"), - VrmLib.Texture.ColorSpaceTypes.Linear, - VrmLib.Texture.TextureTypes.MetallicRoughness)?.Texture; - if (material.MetallicRoughnessTexture != null) - { - material.MetallicFactor = 1.0f; - // Set 1.0f as hard-coded. See: https://github.com/vrm-c/UniVRM/issues/212. - material.RoughnessFactor = 1.0f; - } - } - - if (material.MetallicRoughnessTexture == null) - { - if (src.HasProperty("_Metallic")) - { - material.MetallicFactor = src.GetFloat("_Metallic"); - } - - if (src.HasProperty("_Glossiness")) - { - material.RoughnessFactor = 1.0f - src.GetFloat("_Glossiness"); - } - } - - if (src.HasProperty("_BumpMap")) - { - material.NormalTexture = map(src, src.GetTexture("_BumpMap"), VrmLib.Texture.ColorSpaceTypes.Linear, VrmLib.Texture.TextureTypes.NormalMap)?.Texture; - - if (src.HasProperty("_BumpScale")) - { - material.NormalTextureScale = src.GetFloat("_BumpScale"); - } - } - - if (src.HasProperty("_OcclusionMap")) - { - material.OcclusionTexture = map(src, src.GetTexture("_OcclusionMap"), VrmLib.Texture.ColorSpaceTypes.Linear, VrmLib.Texture.TextureTypes.Occlusion)?.Texture; - - if (src.HasProperty("_OcclusionStrength")) - { - material.OcclusionTextureStrength = src.GetFloat("_OcclusionStrength"); - } - } - - if (src.IsKeywordEnabled("_EMISSION")) - { - if (src.HasProperty("_EmissionColor")) - { - var color = src.GetColor("_EmissionColor"); - if (color.maxColorComponent > 1) - { - color /= color.maxColorComponent; - } - material.EmissiveFactor = new System.Numerics.Vector3(color.r, color.g, color.b); - } - - if (src.HasProperty("_EmissionMap")) - { - material.EmissiveTexture = map(src, src.GetTexture("_EmissionMap"), VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Emissive)?.Texture; - } - } - - return material; - } - - private static void CreateNodes( - Transform parentTransform, - VrmLib.Node parentNode, - Dictionary nodes) - { - // parentNode.SetMatrix(parentTransform.localToWorldMatrix.ToNumericsMatrix4x4(), false); - parentNode.LocalTranslation = parentTransform.localPosition.ToNumericsVector3(); - parentNode.LocalRotation = parentTransform.localRotation.ToNumericsQuaternion(); - parentNode.LocalScaling = parentTransform.localScale.ToNumericsVector3(); - nodes.Add(parentTransform.gameObject, parentNode); - - foreach (Transform child in parentTransform) - { - var childNode = new VrmLib.Node(child.gameObject.name); - CreateNodes(child, childNode, nodes); - parentNode.Add(childNode); - } - } - - private static Transform GetTransformFromRelativePath(Transform root, string relativePath) - { - var paths = new Queue(relativePath.Split('/')); - return GetTransformFromRelativePath(root, paths); - } - - private static Transform GetTransformFromRelativePath(Transform root, Queue relativePath) - { - var name = relativePath.Dequeue(); - foreach (Transform node in root) - { - if (node.gameObject.name == name) - { - if (relativePath.Count == 0) - { - return node; - } - else - { - return GetTransformFromRelativePath(node, relativePath); - } - } - } - - return null; - } - - private static VrmLib.MeshGroup CreateMesh(UnityEngine.Mesh mesh, Renderer renderer, Dictionary materials) - { - var meshGroup = new VrmLib.MeshGroup(mesh.name); - var vrmMesh = new VrmLib.Mesh(); - vrmMesh.VertexBuffer = new VrmLib.VertexBuffer(); - vrmMesh.VertexBuffer.Add(VrmLib.VertexBuffer.PositionKey, ToBufferAccessor(mesh.vertices)); - - if (mesh.boneWeights.Length == mesh.vertexCount) - { - vrmMesh.VertexBuffer.Add( - VrmLib.VertexBuffer.WeightKey, - ToBufferAccessor(mesh.boneWeights.Select(x => - new Vector4(x.weight0, x.weight1, x.weight2, x.weight3)).ToArray() - )); - vrmMesh.VertexBuffer.Add( - VrmLib.VertexBuffer.JointKey, - ToBufferAccessor(mesh.boneWeights.Select(x => - new VrmLib.SkinJoints((ushort)x.boneIndex0, (ushort)x.boneIndex1, (ushort)x.boneIndex2, (ushort)x.boneIndex3)).ToArray() - )); - } - if (mesh.uv.Length == mesh.vertexCount) vrmMesh.VertexBuffer.Add(VrmLib.VertexBuffer.TexCoordKey, ToBufferAccessor(mesh.uv)); - if (mesh.normals.Length == mesh.vertexCount) vrmMesh.VertexBuffer.Add(VrmLib.VertexBuffer.NormalKey, ToBufferAccessor(mesh.normals)); - if (mesh.colors.Length == mesh.vertexCount) vrmMesh.VertexBuffer.Add(VrmLib.VertexBuffer.ColorKey, ToBufferAccessor(mesh.colors)); - vrmMesh.IndexBuffer = ToBufferAccessor(mesh.triangles); - - int offset = 0; - for (int i = 0; i < mesh.subMeshCount; i++) - { -#if UNITY_2019 - var subMesh = mesh.GetSubMesh(i); - try - { - vrmMesh.Submeshes.Add(new VrmLib.Submesh(offset, subMesh.indexCount, materials[renderer.sharedMaterials[i]])); - } - catch (Exception ex) - { - Debug.LogError(ex); - } - offset += subMesh.indexCount; -#else - var triangles = mesh.GetTriangles(i); - try - { - vrmMesh.Submeshes.Add(new VrmLib.Submesh(offset, triangles.Length, materials[renderer.sharedMaterials[i]])); - } - catch (Exception ex) - { - Debug.LogError(ex); - } - offset += triangles.Length; -#endif - } - - for (int i = 0; i < mesh.blendShapeCount; i++) - { - var blendShapeVertices = mesh.vertices; - var usePosition = blendShapeVertices != null && blendShapeVertices.Length > 0; - - var blendShapeNormals = mesh.normals; - var useNormal = usePosition && blendShapeNormals != null && blendShapeNormals.Length == blendShapeVertices.Length; - // var useNormal = usePosition && blendShapeNormals != null && blendShapeNormals.Length == blendShapeVertices.Length && !exportOnlyBlendShapePosition; - - var blendShapeTangents = mesh.tangents.Select(y => (Vector3)y).ToArray(); - //var useTangent = usePosition && blendShapeTangents != null && blendShapeTangents.Length == blendShapeVertices.Length; - // var useTangent = false; - - var frameCount = mesh.GetBlendShapeFrameCount(i); - mesh.GetBlendShapeFrameVertices(i, frameCount - 1, blendShapeVertices, blendShapeNormals, null); - - if (usePosition) - { - var morphTarget = new VrmLib.MorphTarget(mesh.GetBlendShapeName(i)); - morphTarget.VertexBuffer = new VrmLib.VertexBuffer(); - morphTarget.VertexBuffer.Add(VrmLib.VertexBuffer.PositionKey, ToBufferAccessor(blendShapeVertices)); - vrmMesh.MorphTargets.Add(morphTarget); - } - } - - meshGroup.Meshes.Add(vrmMesh); - return meshGroup; - } - - private static VrmLib.Skin CreateSkin( - SkinnedMeshRenderer skinnedMeshRenderer, - Dictionary nodes, - GameObject root) - { - if (skinnedMeshRenderer.bones == null || skinnedMeshRenderer.bones.Length == 0) - { - return null; - } - - var skin = new VrmLib.Skin(); - skin.InverseMatrices = ToBufferAccessor(skinnedMeshRenderer.sharedMesh.bindposes); - if (skinnedMeshRenderer.rootBone != null) - { - skin.Root = nodes[skinnedMeshRenderer.rootBone.gameObject]; - } - - skin.Joints = skinnedMeshRenderer.bones.Select(x => nodes[x.gameObject]).ToList(); - return skin; - } - - private static VrmLib.BufferAccessor ToBufferAccessor(VrmLib.SkinJoints[] values) - { - return ToBufferAccessor(values, VrmLib.AccessorValueType.UNSIGNED_SHORT, VrmLib.AccessorVectorType.VEC4); - } - - private static VrmLib.BufferAccessor ToBufferAccessor(Color[] colors) - { - return ToBufferAccessor(colors, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.VEC4); - } - - private static VrmLib.BufferAccessor ToBufferAccessor(Vector4[] vectors) - { - return ToBufferAccessor(vectors, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.VEC4); - } - - private static VrmLib.BufferAccessor ToBufferAccessor(Vector3[] vectors) - { - return ToBufferAccessor(vectors, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.VEC3); - } - - private static VrmLib.BufferAccessor ToBufferAccessor(Vector2[] vectors) - { - return ToBufferAccessor(vectors, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.VEC2); - } - - private static VrmLib.BufferAccessor ToBufferAccessor(int[] scalars) - { - return ToBufferAccessor(scalars, VrmLib.AccessorValueType.UNSIGNED_INT, VrmLib.AccessorVectorType.SCALAR); - } - - private static VrmLib.BufferAccessor ToBufferAccessor(Matrix4x4[] matrixes) - { - return ToBufferAccessor(matrixes, VrmLib.AccessorValueType.FLOAT, VrmLib.AccessorVectorType.MAT4); - } - - private static VrmLib.BufferAccessor ToBufferAccessor(T[] value, VrmLib.AccessorValueType valueType, VrmLib.AccessorVectorType vectorType) where T : struct - { - var span = VrmLib.SpanLike.CopyFrom(value); - return new VrmLib.BufferAccessor( - span.Bytes, - valueType, - vectorType, - value.Length - ); - } - } -} diff --git a/Assets/VRM10/Runtime/VRMConverter/UnityTextureUtil.cs b/Assets/VRM10/Runtime/VRMConverter/UnityTextureUtil.cs deleted file mode 100644 index 4603f3bde..000000000 --- a/Assets/VRM10/Runtime/VRMConverter/UnityTextureUtil.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using UnityEngine; - -namespace UniVRM10 -{ - public static class UnityTextureUtil - { - struct ColorSpaceScope : IDisposable - { - bool m_sRGBWrite; - - public ColorSpaceScope(RenderTextureReadWrite dstColorSpace) - { - m_sRGBWrite = GL.sRGBWrite; - switch (dstColorSpace) - { - 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; - } - } - - /// - /// Copy texture for export. - /// Use when source texture is not Texture2D or isReadable==false. - /// - public static Texture2D CopyTexture(Texture src, RenderTextureReadWrite dstColorSpace, Material material = null) - { - Texture2D dst = null; - - var renderTexture = new RenderTexture(src.width, src.height, 0, RenderTextureFormat.ARGB32, dstColorSpace); - - using (var scope = new ColorSpaceScope(dstColorSpace)) - { - if (material != null) - { - Graphics.Blit(src, renderTexture, material); - } - else - { - Graphics.Blit(src, renderTexture); - } - } - - dst = new Texture2D(src.width, src.height, TextureFormat.ARGB32, false, dstColorSpace == 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; - dst.wrapModeU = src.wrapModeU; - dst.wrapModeV = src.wrapModeV; - dst.wrapModeW = src.wrapModeW; - dst.Apply(); - - RenderTexture.active = null; - if (Application.isEditor) - { - GameObject.DestroyImmediate(renderTexture); - } - else - { - GameObject.Destroy(renderTexture); - } - return dst; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/Runtime/VRMConverter/UnityTextureUtil.cs.meta b/Assets/VRM10/Runtime/VRMConverter/UnityTextureUtil.cs.meta deleted file mode 100644 index 26e18cfdb..000000000 --- a/Assets/VRM10/Runtime/VRMConverter/UnityTextureUtil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 09e01588153da3641a905b8f76d91568 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/Tests.PlayMode/MaterialTests.cs b/Assets/VRM10/Tests.PlayMode/MaterialTests.cs index fa1a679e4..5b67dc155 100644 --- a/Assets/VRM10/Tests.PlayMode/MaterialTests.cs +++ b/Assets/VRM10/Tests.PlayMode/MaterialTests.cs @@ -1,13 +1,14 @@ using System; using System.Collections; +using System.Collections.Generic; using System.IO; using System.Linq; using NUnit.Framework; +using UniGLTF; using UnityEngine; using UnityEngine.TestTools; using UniVRM10; using VrmLib; -using VrmLib.Diff; namespace UniVRM10.Test { @@ -15,21 +16,7 @@ namespace UniVRM10.Test { const string _vrmPath = "Tests/Models/Alicia_vrm-0.51/AliciaSolid_vrm-0.51.vrm"; - string[] _mtooSrgbTextureProperties = { - VrmLib.MToon.Utils.PropMainTex, - VrmLib.MToon.Utils.PropShadeTexture, - VrmLib.MToon.Utils.PropEmissionMap, - VrmLib.MToon.Utils.PropSphereAdd, - VrmLib.MToon.Utils.PropRimTexture, - }; - - string[] _mtoonLinearTextureProperties = { - VrmLib.MToon.Utils.PropBumpMap, - VrmLib.MToon.Utils.PropOutlineWidthTexture, - VrmLib.MToon.Utils.PropUvAnimMaskTexture - }; - - private ModelAsset ToUnity(string path) + private (GameObject, IReadOnlyList) ToUnity(string path) { var fi = new FileInfo(_vrmPath); var bytes = File.ReadAllBytes(fi.FullName); @@ -40,21 +27,24 @@ namespace UniVRM10.Test return ToUnity(bytes); } - private ModelAsset ToUnity(byte[] bytes) + private (GameObject, IReadOnlyList) ToUnity(byte[] bytes) { // Vrm => Model - var model = VrmLoader.CreateVrmModel(bytes, new FileInfo("tmp.vrm")); - model.RemoveSecondary(); + var parser = new UniGLTF.GltfParser(); + parser.Parse("tmp.vrm", bytes); - return ToUnity(model); + return ToUnity(parser); } - private ModelAsset ToUnity(Model model) + private (GameObject, IReadOnlyList) ToUnity(GltfParser parser) { // Model => Unity - var assets = RuntimeUnityBuilder.ToUnityAsset(model); - UniVRM10.ComponentBuilder.Build10(model, assets); - return assets; + using (var loader = new RuntimeUnityBuilder(parser)) + { + loader.Load(); + loader.DisposeOnGameObjectDestroyed(); + return (loader.Root, loader.MaterialFactory.Materials); + } } private Model ToVrmModel(GameObject root) @@ -87,232 +77,231 @@ namespace UniVRM10.Test [UnityTest] public IEnumerator ColorSpace_UnityBaseColorToLiner() { - var assets = ToUnity(_vrmPath); - var srcMaterial = assets.Map.Materials.First(); - var key = srcMaterial.Key; + var (root, materials) = ToUnity(_vrmPath); + var srcMaterial = materials.First(); var srcColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); var srcGammaColor = srcColor; var srclinerColor = srcColor.linear; - srcMaterial.Value.color = srcColor; + srcMaterial.Asset.color = srcColor; - var model = ToVrmModel(assets.Root); - var dstMaterial = model.Materials.First(x => x.Name == key.Name); + var model = ToVrmModel(root); + var dstMaterial = model.Materials.First(x => x is UnityEngine.Material m && m.name == srcMaterial.Asset.name) as UnityEngine.Material; - EqualColor(srclinerColor, dstMaterial.BaseColorFactor.RGBA.ToUnityColor()); + EqualColor(srclinerColor, dstMaterial.color); yield return null; } - [UnityTest] - public IEnumerator ColorSpace_GltfBaseColorToGamma() - { - var assets = ToUnity(_vrmPath); - var srcMaterial = assets.Map.Materials.First(); - var key = srcMaterial.Key; - var srcColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); - var srclinerColor = srcColor.ToVector4(); - var srcGammaColor = srcColor.gamma.ToVector4(); + // [UnityTest] + // public IEnumerator ColorSpace_GltfBaseColorToGamma() + // { + // var assets = ToUnity(_vrmPath); + // var srcMaterial = assets.Map.Materials.First(); + // var key = srcMaterial.Key; + // var srcColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); + // var srclinerColor = srcColor.ToVector4(); + // var srcGammaColor = srcColor.gamma.ToVector4(); - var model = ToVrmModel(assets.Root); - var gltfMaterial = model.Materials.First(x => x.Name == key.Name); - gltfMaterial.BaseColorFactor = new LinearColor - { - RGBA = srclinerColor - }; + // var model = ToVrmModel(assets.Root); + // var gltfMaterial = model.Materials.First(x => x.Name == key.Name); + // gltfMaterial.BaseColorFactor = new LinearColor + // { + // RGBA = srclinerColor + // }; - var bytes = model.ToGlb(); + // var bytes = model.ToGlb(); - var dstAssets = ToUnity(bytes); - var dstMaterial = dstAssets.Map.Materials.First(x => x.Value.name == key.Name); + // var dstAssets = ToUnity(bytes); + // var dstMaterial = dstAssets.Map.Materials.First(x => x.Value.name == key.Name); - EqualColor(srcGammaColor.ToUnityColor(), dstMaterial.Value.color); + // EqualColor(srcGammaColor.ToUnityColor(), dstMaterial.Value.color); - yield return null; - } + // yield return null; + // } - [UnityTest] - public IEnumerator MToonUnityColorToGltf() - { - var assets = ToUnity(_vrmPath); - var srcMaterial = assets.Map.Materials.First(); - var key = srcMaterial.Key; - var srcColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); - var srcGammaColor = srcColor; - var srclinerColor = srcColor.linear; + // [UnityTest] + // public IEnumerator MToonUnityColorToGltf() + // { + // var assets = ToUnity(_vrmPath); + // var srcMaterial = assets.Map.Materials.First(); + // var key = srcMaterial.Key; + // var srcColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); + // var srcGammaColor = srcColor; + // var srclinerColor = srcColor.linear; - srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropColor, srcColor); - srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropShadeColor, srcColor); - srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropEmissionColor, srcColor); - srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropRimColor, srcColor); - srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropOutlineColor, srcColor); + // srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropColor, srcColor); + // srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropShadeColor, srcColor); + // srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropEmissionColor, srcColor); + // srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropRimColor, srcColor); + // srcMaterial.Value.SetColor(VrmLib.MToon.Utils.PropOutlineColor, srcColor); - var model = ToVrmModel(assets.Root); - var dstMaterial = model.Materials.First(x => x.Name == key.Name) as VrmLib.MToonMaterial; + // var model = ToVrmModel(assets.Root); + // var dstMaterial = model.Materials.First(x => x.Name == key.Name) as VrmLib.MToonMaterial; - // sRGB - EqualColor(srclinerColor, dstMaterial.Definition.Color.LitColor.RGBA.ToUnityColor()); - EqualColor(srclinerColor, dstMaterial.Definition.Color.ShadeColor.RGBA.ToUnityColor()); - EqualColor(srclinerColor, dstMaterial.Definition.Outline.OutlineColor.RGBA.ToUnityColor()); - // HDR Color - EqualColor(srcColor, dstMaterial.Definition.Emission.EmissionColor.RGBA.ToUnityColor()); - EqualColor(srcColor, dstMaterial.Definition.Rim.RimColor.RGBA.ToUnityColor()); + // // sRGB + // EqualColor(srclinerColor, dstMaterial.Definition.Color.LitColor.RGBA.ToUnityColor()); + // EqualColor(srclinerColor, dstMaterial.Definition.Color.ShadeColor.RGBA.ToUnityColor()); + // EqualColor(srclinerColor, dstMaterial.Definition.Outline.OutlineColor.RGBA.ToUnityColor()); + // // HDR Color + // EqualColor(srcColor, dstMaterial.Definition.Emission.EmissionColor.RGBA.ToUnityColor()); + // EqualColor(srcColor, dstMaterial.Definition.Rim.RimColor.RGBA.ToUnityColor()); - yield return null; - } + // yield return null; + // } - [UnityTest] - public IEnumerator MtoonGltfColorToUnity() - { - var assets = ToUnity(_vrmPath); - var srcMaterial = assets.Map.Materials.First(); - var key = srcMaterial.Key; - var srcColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); - var srclinerColor = srcColor.ToVector4(); - var srcGammaColor = srcColor.gamma.ToVector4(); + // [UnityTest] + // public IEnumerator MtoonGltfColorToUnity() + // { + // var assets = ToUnity(_vrmPath); + // var srcMaterial = assets.Map.Materials.First(); + // var key = srcMaterial.Key; + // var srcColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); + // var srclinerColor = srcColor.ToVector4(); + // var srcGammaColor = srcColor.gamma.ToVector4(); - var model = ToVrmModel(assets.Root); - var gltfMaterial = model.Materials.First(x => x.Name == key.Name) as VrmLib.MToonMaterial; - if (gltfMaterial == null) - { - throw new NotImplementedException(); - } + // var model = ToVrmModel(assets.Root); + // var gltfMaterial = model.Materials.First(x => x.Name == key.Name) as VrmLib.MToonMaterial; + // if (gltfMaterial == null) + // { + // throw new NotImplementedException(); + // } - gltfMaterial.Definition = new VrmLib.MToon.MToonDefinition - { - Color = new VrmLib.MToon.ColorDefinition - { - LitColor = new LinearColor { RGBA = srclinerColor }, - ShadeColor = new LinearColor { RGBA = srclinerColor }, - }, - Outline = new VrmLib.MToon.OutlineDefinition - { - OutlineColor = new LinearColor { RGBA = srclinerColor }, - }, - Emission = new VrmLib.MToon.EmissionDefinition - { - EmissionColor = new LinearColor { RGBA = srclinerColor }, - }, - Rim = new VrmLib.MToon.RimDefinition - { - RimColor = new LinearColor { RGBA = srclinerColor }, - } - }; + // gltfMaterial.Definition = new VrmLib.MToon.MToonDefinition + // { + // Color = new VrmLib.MToon.ColorDefinition + // { + // LitColor = new LinearColor { RGBA = srclinerColor }, + // ShadeColor = new LinearColor { RGBA = srclinerColor }, + // }, + // Outline = new VrmLib.MToon.OutlineDefinition + // { + // OutlineColor = new LinearColor { RGBA = srclinerColor }, + // }, + // Emission = new VrmLib.MToon.EmissionDefinition + // { + // EmissionColor = new LinearColor { RGBA = srclinerColor }, + // }, + // Rim = new VrmLib.MToon.RimDefinition + // { + // RimColor = new LinearColor { RGBA = srclinerColor }, + // } + // }; - var bytes = model.ToGlb(); + // var bytes = model.ToGlb(); - var dstAssets = ToUnity(bytes); - var dstMaterial = dstAssets.Map.Materials.First(x => x.Value.name == key.Name).Value; - // sRGB - EqualColor(srcGammaColor.ToUnityColor(), dstMaterial.GetColor(VrmLib.MToon.Utils.PropColor)); - EqualColor(srcGammaColor.ToUnityColor(), dstMaterial.GetColor(VrmLib.MToon.Utils.PropShadeColor)); - EqualColor(srcGammaColor.ToUnityColor(), dstMaterial.GetColor(VrmLib.MToon.Utils.PropOutlineColor)); - // HDR Color - EqualColor(srcColor, dstMaterial.GetColor(VrmLib.MToon.Utils.PropEmissionColor)); - EqualColor(srcColor, dstMaterial.GetColor(VrmLib.MToon.Utils.PropRimColor)); + // var dstAssets = ToUnity(bytes); + // var dstMaterial = dstAssets.Map.Materials.First(x => x.Value.name == key.Name).Value; + // // sRGB + // EqualColor(srcGammaColor.ToUnityColor(), dstMaterial.GetColor(VrmLib.MToon.Utils.PropColor)); + // EqualColor(srcGammaColor.ToUnityColor(), dstMaterial.GetColor(VrmLib.MToon.Utils.PropShadeColor)); + // EqualColor(srcGammaColor.ToUnityColor(), dstMaterial.GetColor(VrmLib.MToon.Utils.PropOutlineColor)); + // // HDR Color + // EqualColor(srcColor, dstMaterial.GetColor(VrmLib.MToon.Utils.PropEmissionColor)); + // EqualColor(srcColor, dstMaterial.GetColor(VrmLib.MToon.Utils.PropRimColor)); - yield return null; - } - #endregion + // yield return null; + // } + // #endregion - #region Texture + // #region Texture - Texture2D CreateMonoTexture(float mono, float alpha, bool isLinear) - { - Texture2D texture = new Texture2D(128, 128, TextureFormat.ARGB32, mipChain: false, linear: isLinear); - Color col = new Color(mono, mono, mono, alpha); - for (int y = 0; y < texture.height; y++) - { - for (int x = 0; x < texture.width; x++) - { - texture.SetPixel(x, y, col); - } - } - texture.Apply(); - return texture; - } + // Texture2D CreateMonoTexture(float mono, float alpha, bool isLinear) + // { + // Texture2D texture = new Texture2D(128, 128, TextureFormat.ARGB32, mipChain: false, linear: isLinear); + // Color col = new Color(mono, mono, mono, alpha); + // for (int y = 0; y < texture.height; y++) + // { + // for (int x = 0; x < texture.width; x++) + // { + // texture.SetPixel(x, y, col); + // } + // } + // texture.Apply(); + // return texture; + // } - void EqualTextureColor(Texture2D texture, VrmLib.ImageTexture imageTexture, bool isLinear) - { - var srcColor = texture.GetPixel(0, 0); + // void EqualTextureColor(Texture2D texture, VrmLib.ImageTexture imageTexture, bool isLinear) + // { + // var srcColor = texture.GetPixel(0, 0); - var dstTexture = new Texture2D(2, 2, TextureFormat.ARGB32, mipChain: false, linear: isLinear); - dstTexture.LoadImage(imageTexture.Image.Bytes.ToArray()); - var dstColor = dstTexture.GetPixel(0, 0); + // var dstTexture = new Texture2D(2, 2, TextureFormat.ARGB32, mipChain: false, linear: isLinear); + // dstTexture.LoadImage(imageTexture.Image.Bytes.ToArray()); + // var dstColor = dstTexture.GetPixel(0, 0); - Debug.LogFormat("src:{0}, dst{1}", srcColor, dstColor); - EqualColor(srcColor, dstColor); - } + // Debug.LogFormat("src:{0}, dst{1}", srcColor, dstColor); + // EqualColor(srcColor, dstColor); + // } - [UnityTest] - public IEnumerator MToonTextureToGltf_BaseColorTexture() - { - var assets = ToUnity(_vrmPath); - var srcMaterial = assets.Map.Materials.First(); - var key = srcMaterial.Key; - var srcSrgbTexture = CreateMonoTexture(0.5f, 0.5f, false); + // [UnityTest] + // public IEnumerator MToonTextureToGltf_BaseColorTexture() + // { + // var assets = ToUnity(_vrmPath); + // var srcMaterial = assets.Map.Materials.First(); + // var key = srcMaterial.Key; + // var srcSrgbTexture = CreateMonoTexture(0.5f, 0.5f, false); - srcMaterial.Value.SetTexture(VrmLib.MToon.Utils.PropMainTex, srcSrgbTexture); + // srcMaterial.Value.SetTexture(VrmLib.MToon.Utils.PropMainTex, srcSrgbTexture); - var model = ToVrmModel(assets.Root); - var dstMaterial = model.Materials.First(x => x.Name == key.Name) as VrmLib.MToonMaterial; + // var model = ToVrmModel(assets.Root); + // var dstMaterial = model.Materials.First(x => x.Name == key.Name) as VrmLib.MToonMaterial; - var imageTexture = dstMaterial.Definition.Color.LitMultiplyTexture.Texture as VrmLib.ImageTexture; - EqualTextureColor(srcSrgbTexture, imageTexture, false); + // var imageTexture = dstMaterial.Definition.Color.LitMultiplyTexture.Texture as VrmLib.ImageTexture; + // EqualTextureColor(srcSrgbTexture, imageTexture, false); - yield return null; - } + // yield return null; + // } - [UnityTest] - public IEnumerator MToonTextureToGltf_OutlineWidthTexture() - { - var assets = ToUnity(_vrmPath); - var srcMaterial = assets.Map.Materials.First(); - var key = srcMaterial.Key; - var srcLinearTexture = CreateMonoTexture(0.5f, 0.5f, true); + // [UnityTest] + // public IEnumerator MToonTextureToGltf_OutlineWidthTexture() + // { + // var assets = ToUnity(_vrmPath); + // var srcMaterial = assets.Map.Materials.First(); + // var key = srcMaterial.Key; + // var srcLinearTexture = CreateMonoTexture(0.5f, 0.5f, true); - srcMaterial.Value.SetTexture(VrmLib.MToon.Utils.PropOutlineWidthTexture, srcLinearTexture); + // srcMaterial.Value.SetTexture(VrmLib.MToon.Utils.PropOutlineWidthTexture, srcLinearTexture); - var model = ToVrmModel(assets.Root); - var dstMaterial = model.Materials.First(x => x.Name == key.Name) as VrmLib.MToonMaterial; + // var model = ToVrmModel(assets.Root); + // var dstMaterial = model.Materials.First(x => x.Name == key.Name) as VrmLib.MToonMaterial; - var imageTexture = dstMaterial.Definition.Outline.OutlineWidthMultiplyTexture.Texture as VrmLib.ImageTexture; - EqualTextureColor(srcLinearTexture, imageTexture, true); + // var imageTexture = dstMaterial.Definition.Outline.OutlineWidthMultiplyTexture.Texture as VrmLib.ImageTexture; + // EqualTextureColor(srcLinearTexture, imageTexture, true); - yield return null; - } + // yield return null; + // } - [UnityTest] - public IEnumerator GetOrCreateTextureTest() - { - var converter = new RuntimeVrmConverter(); - var material = new UnityEngine.Material(Shader.Find("VRM/MToon")); - var srcLinearTexture = CreateMonoTexture(0.5f, 1.0f, true); - var srcSRGBTexture = CreateMonoTexture(0.5f, 1.0f, false); + // [UnityTest] + // public IEnumerator GetOrCreateTextureTest() + // { + // var converter = new RuntimeVrmConverter(); + // var material = new UnityEngine.Material(Shader.Find("VRM/MToon")); + // var srcLinearTexture = CreateMonoTexture(0.5f, 1.0f, true); + // var srcSRGBTexture = CreateMonoTexture(0.5f, 1.0f, false); - { - material.SetTexture(VrmLib.MToon.Utils.PropOutlineWidthTexture, srcSRGBTexture); - var textureInfo = converter.GetOrCreateTexture(material, srcSRGBTexture, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default); - var imageTexture = textureInfo.Texture as VrmLib.ImageTexture; - EqualTextureColor(srcSRGBTexture, imageTexture, false); - } + // { + // material.SetTexture(VrmLib.MToon.Utils.PropOutlineWidthTexture, srcSRGBTexture); + // var textureInfo = converter.GetOrCreateTexture(material, srcSRGBTexture, VrmLib.Texture.ColorSpaceTypes.Srgb, VrmLib.Texture.TextureTypes.Default); + // var imageTexture = textureInfo.Texture as VrmLib.ImageTexture; + // EqualTextureColor(srcSRGBTexture, imageTexture, false); + // } - { - material.SetTexture(VrmLib.MToon.Utils.PropOutlineWidthTexture, srcLinearTexture); - var textureInfo = converter.GetOrCreateTexture(material, srcLinearTexture, VrmLib.Texture.ColorSpaceTypes.Linear, VrmLib.Texture.TextureTypes.Default); - var imageTexture = textureInfo.Texture as VrmLib.ImageTexture; - EqualTextureColor(srcLinearTexture, imageTexture, true); - } + // { + // material.SetTexture(VrmLib.MToon.Utils.PropOutlineWidthTexture, srcLinearTexture); + // var textureInfo = converter.GetOrCreateTexture(material, srcLinearTexture, VrmLib.Texture.ColorSpaceTypes.Linear, VrmLib.Texture.TextureTypes.Default); + // var imageTexture = textureInfo.Texture as VrmLib.ImageTexture; + // EqualTextureColor(srcLinearTexture, imageTexture, true); + // } - yield return null; - } + // yield return null; + // } - [UnityTest] - public IEnumerator MToonTextureToUnity() - { - yield return null; - } + // [UnityTest] + // public IEnumerator MToonTextureToUnity() + // { + // yield return null; + // } #endregion } } \ No newline at end of file diff --git a/Assets/VRM10/Tests.PlayMode/VRM10.Tests.PlayMode.asmdef b/Assets/VRM10/Tests.PlayMode/VRM10.Tests.PlayMode.asmdef index 972ea0c0c..032941920 100644 --- a/Assets/VRM10/Tests.PlayMode/VRM10.Tests.PlayMode.asmdef +++ b/Assets/VRM10/Tests.PlayMode/VRM10.Tests.PlayMode.asmdef @@ -3,7 +3,8 @@ "references": [ "VrmLib", "VRM10", - "UniGLTF" + "UniGLTF", + "VRMShaders" ], "optionalUnityReferences": [ "TestAssemblies" diff --git a/Assets/VRM10/Tests/ApiSampleTests.cs b/Assets/VRM10/Tests/ApiSampleTests.cs index b2372d1b2..df721491b 100644 --- a/Assets/VRM10/Tests/ApiSampleTests.cs +++ b/Assets/VRM10/Tests/ApiSampleTests.cs @@ -1,6 +1,7 @@ using System; using System.IO; using NUnit.Framework; +using UniGLTF; using UnityEngine; using UnityEngine.TestTools; @@ -12,21 +13,25 @@ namespace UniVRM10.Test { var bytes = MigrationVrm.Migrate(File.ReadAllBytes(path)); - if (!UniGLTF.Glb.TryParse(bytes, out UniGLTF.Glb glb, out Exception ex)) - { - Debug.LogError($"fail to Glb.TryParse: {path} => {ex}"); - return null; - } + var parser = new GltfParser(); + parser.Parse("migrated", bytes); - var model = UniVRM10.VrmLoader.CreateVrmModel(bytes, new FileInfo(path)); + var model = UniVRM10.VrmLoader.CreateVrmModel(parser); return model; } - ModelAsset BuildGameObject(VrmLib.Model model, bool showMesh) + GameObject BuildGameObject(GltfParser parser, bool showMesh) { - var assets = RuntimeUnityBuilder.ToUnityAsset(model, showMesh); - UniVRM10.ComponentBuilder.Build10(model, assets); - return assets; + using (var loader = new RuntimeUnityBuilder(parser)) + { + loader.Load(); + if (showMesh) + { + loader.ShowMeshes(); + } + loader.EnableUpdateWhenOffscreen(); + return loader.DisposeOnGameObjectDestroyed().gameObject; + } } VrmLib.Model ToModel(UnityEngine.GameObject target) @@ -50,27 +55,16 @@ namespace UniVRM10.Test var path = "Tests/Models/Alicia_vrm-0.51/AliciaSolid_vrm-0.51.vrm"; Debug.Log($"load: {path}"); - // import - var srcModel = ReadModel(path); - Debug.Log(srcModel); + var migrated = MigrationVrm.Migrate(File.ReadAllBytes(path)); - var asset = BuildGameObject(srcModel, false); + var parser = new GltfParser(); + parser.Parse(path, migrated); + + var asset = BuildGameObject(parser, true); Debug.Log(asset); - // renderer setting - foreach (var render in asset.Renderers) - { - // show when RuntimeUnityBuilder.ToUnity(showMesh = false) - render.enabled = true; - // avoid culling - if (render is SkinnedMeshRenderer skinned) - { - skinned.updateWhenOffscreen = true; - } - } - // export - var dstModel = ToModel(asset.Root); + var dstModel = ToModel(asset); Debug.Log(dstModel); var vrmBytes = ToVrm10(dstModel); diff --git a/Assets/VRM10/Tests/MigrationTests.cs b/Assets/VRM10/Tests/MigrationTests.cs index e6265804b..2f5bded6f 100644 --- a/Assets/VRM10/Tests/MigrationTests.cs +++ b/Assets/VRM10/Tests/MigrationTests.cs @@ -5,6 +5,7 @@ using UniJSON; using System; using UniGLTF; using System.Runtime.InteropServices; +using System.Collections.Generic; namespace UniVRM10 { @@ -154,5 +155,63 @@ namespace UniVRM10 } Assert.AreEqual(1.0f, BitConverter.ToSingle(bytes, 4)); } + + static IEnumerable EnumerateGltfFiles(DirectoryInfo dir) + { + if (dir.Name == ".git") + { + yield break; + } + + foreach (var child in dir.EnumerateDirectories()) + { + foreach (var x in EnumerateGltfFiles(child)) + { + yield return x; + } + } + + foreach (var child in dir.EnumerateFiles()) + { + switch (child.Extension.ToLower()) + { + case ".vrm": + yield return child; + break; + } + } + } + + [Test] + public void Migrate_VrmTestModels() + { + var env = System.Environment.GetEnvironmentVariable("VRM_TEST_MODELS"); + if (string.IsNullOrEmpty(env)) + { + return; + } + var root = new DirectoryInfo(env); + if (!root.Exists) + { + return; + } + + foreach (var gltf in EnumerateGltfFiles(root)) + { + var bytes = File.ReadAllBytes(gltf.FullName); + try + { + var migrated = MigrationVrm.Migrate(bytes); + var parser = new GltfParser(); + parser.Parse(gltf.FullName, migrated); + UniGLTF.Extensions.VRMC_vrm.GltfDeserializer.TryGet(parser.GLTF.extensions, out UniGLTF.Extensions.VRMC_vrm.VRMC_vrm vrm); + Assert.NotNull(vrm); + } + catch (UnNormalizedException) + { + Debug.LogWarning($"[Not Normalized] {gltf}"); + } + } + } } } diff --git a/Assets/VRM10/Tests/SerializationTests.cs b/Assets/VRM10/Tests/SerializationTests.cs index a899681c1..a051a09c0 100644 --- a/Assets/VRM10/Tests/SerializationTests.cs +++ b/Assets/VRM10/Tests/SerializationTests.cs @@ -7,7 +7,7 @@ using UniGLTF; using UniJSON; using UnityEditor; using UnityEngine; -using VrmLib.Diff; + namespace UniVRM10 { @@ -70,32 +70,6 @@ namespace UniVRM10 } } - static (UniGLTF.glTFMaterial, bool) ToProtobufMaterial(VrmLib.Material vrmlibMaterial, List textures) - { - if (vrmlibMaterial is VrmLib.MToonMaterial mtoon) - { - // MToon - var protobufMaterial = UniVRM10.MToonAdapter.MToonToGltf(mtoon, textures); - return (protobufMaterial, true); - } - else if (vrmlibMaterial is VrmLib.UnlitMaterial unlit) - { - // Unlit - var protobufMaterial = UniVRM10.MaterialAdapter.UnlitToGltf(unlit, textures); - return (protobufMaterial, true); - } - else if (vrmlibMaterial is VrmLib.PBRMaterial pbr) - { - // PBR - var protobufMaterial = UniVRM10.MaterialAdapter.PBRToGltf(pbr, textures); - return (protobufMaterial, false); - } - else - { - throw new NotImplementedException(); - } - } - static void CompareUnityMaterial(Material lhs, Material rhs) { Assert.AreEqual(lhs.name, rhs.name); @@ -170,63 +144,63 @@ namespace UniVRM10 "_Glossiness", // Gloss is burned into the texture and changed to the default value (1.0) }; - /// Unity material を export => import して元の material と一致するか - [Test] - [TestCase("TestMToon", typeof(VrmLib.MToonMaterial))] - [TestCase("TestUniUnlit", typeof(VrmLib.UnlitMaterial))] - [TestCase("TestStandard", typeof(VrmLib.PBRMaterial))] - [TestCase("TestUnlitColor", typeof(VrmLib.UnlitMaterial), false)] - [TestCase("TestUnlitTexture", typeof(VrmLib.UnlitMaterial), false)] - [TestCase("TestUnlitTransparent", typeof(VrmLib.UnlitMaterial), false)] - [TestCase("TestUnlitCutout", typeof(VrmLib.UnlitMaterial), false)] - public void UnityMaterialTest(string materialName, Type vrmLibMaterialType, bool sameShader = true) - { - // asset (cerate copy for avoid modify asset) - var src = new Material(Resources.Load(materialName)); + // /// Unity material を export => import して元の material と一致するか + // [Test] + // [TestCase("TestMToon", typeof(UniGLTF.Extensions.VRMC_vrm.MToonMaterial))] + // [TestCase("TestUniUnlit", typeof(UniGLTF.Extensions.VRMC_vrm.UnlitMaterial))] + // [TestCase("TestStandard", typeof(UniGLTF.Extensions.VRMC_vrm.PBRMaterial))] + // [TestCase("TestUnlitColor", typeof(UniGLTF.Extensions.VRMC_vrm.UnlitMaterial), false)] + // [TestCase("TestUnlitTexture", typeof(UniGLTF.Extensions.VRMC_vrm.UnlitMaterial), false)] + // [TestCase("TestUnlitTransparent", typeof(UniGLTF.Extensions.VRMC_vrm.UnlitMaterial), false)] + // [TestCase("TestUnlitCutout", typeof(UniGLTF.Extensions.VRMC_vrm.UnlitMaterial), false)] + // public void UnityMaterialTest(string materialName, Type vrmLibMaterialType, bool sameShader = true) + // { + // // asset (cerate copy for avoid modify asset) + // var src = new Material(Resources.Load(materialName)); - // asset => vrmlib - var converter = new UniVRM10.RuntimeVrmConverter(); - var vrmLibMaterial = converter.Export10(src, (a, b, c, d) => null); - Assert.AreEqual(vrmLibMaterialType, vrmLibMaterial.GetType()); + // // asset => vrmlib + // var converter = new UniVRM10.RuntimeVrmConverter(); + // // var vrmLibMaterial = converter.Export10(src, (a, b, c, d) => null); + // // Assert.AreEqual(vrmLibMaterialType, vrmLibMaterial.GetType()); - // vrmlib => gltf - var textures = new List(); - var (gltfMaterial, hasKhrUnlit) = ToProtobufMaterial(vrmLibMaterial, textures); - if (gltfMaterial.extensions != null) - { - gltfMaterial.extensions = gltfMaterial.extensions.Deserialize(); - } - Assert.AreEqual(hasKhrUnlit, glTF_KHR_materials_unlit.IsEnable(gltfMaterial)); + // // // vrmlib => gltf + // // var textures = new List(); + // // var (gltfMaterial, hasKhrUnlit) = ToProtobufMaterial(vrmLibMaterial, textures); + // // if (gltfMaterial.extensions != null) + // // { + // // gltfMaterial.extensions = gltfMaterial.extensions.Deserialize(); + // // } + // // Assert.AreEqual(hasKhrUnlit, glTF_KHR_materials_unlit.IsEnable(gltfMaterial)); - // gltf => json - var jsonMaterial = Serialize(gltfMaterial, UniGLTF.GltfSerializer.Serialize_gltf_materials_ITEM); + // // // gltf => json + // // var jsonMaterial = Serialize(gltfMaterial, UniGLTF.GltfSerializer.Serialize_gltf_materials_ITEM); - // gltf <= json - var deserialized = UniGLTF.GltfDeserializer.Deserialize_gltf_materials_LIST(jsonMaterial.ParseAsJson()); + // // // gltf <= json + // // var deserialized = UniGLTF.GltfDeserializer.Deserialize_gltf_materials_LIST(jsonMaterial.ParseAsJson()); - // vrmlib <= gltf - var loaded = deserialized.FromGltf(textures); - var context = ModelDiffContext.Create(); - ModelDiffExtensions.MaterialEquals(context, vrmLibMaterial, loaded); - var diff = context.List - .Where(x => !s_ignoreKeys.Contains(x.Context)) - .ToArray(); - if (diff.Length > 0) - { - Debug.LogWarning(string.Join("\n", diff.Select(x => $"{x.Context}: {x.Message}"))); - } - Assert.AreEqual(0, diff.Length); + // // // vrmlib <= gltf + // // var loaded = deserialized.FromGltf(textures); + // // // var context = ModelDiffContext.Create(); + // // // ModelDiffExtensions.MaterialEquals(context, vrmLibMaterial, loaded); + // // // var diff = context.List + // // // .Where(x => !s_ignoreKeys.Contains(x.Context)) + // // // .ToArray(); + // // // if (diff.Length > 0) + // // // { + // // // Debug.LogWarning(string.Join("\n", diff.Select(x => $"{x.Context}: {x.Message}"))); + // // // } + // // // Assert.AreEqual(0, diff.Length); - // <= vrmlib - var map = new Dictionary(); - var dst = UniVRM10.RuntimeUnityMaterialBuilder.CreateMaterialAsset(loaded, hasVertexColor: false, map); - dst.name = src.name; + // // // <= vrmlib + // // var map = new Dictionary(); + // // var dst = UniVRM10.RuntimeUnityMaterialBuilder.CreateMaterialAsset(loaded, hasVertexColor: false, map); + // // dst.name = src.name; - if (sameShader) - { - CompareUnityMaterial(src, dst); - } - } + // // if (sameShader) + // // { + // // CompareUnityMaterial(src, dst); + // // } + // } [Test] public void ExpressionTest() @@ -242,53 +216,53 @@ namespace UniVRM10 } { - var expression = new VrmLib.Expression(VrmLib.ExpressionPreset.Blink, "blink", true) - { - OverrideBlink = VrmLib.ExpressionOverrideType.None, - OverrideLookAt = VrmLib.ExpressionOverrideType.Block, - OverrideMouth = VrmLib.ExpressionOverrideType.Blend, - }; + // var expression = new UniGLTF.Extensions.VRMC_vrm.Expression(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset.Blink, "blink", true) + // { + // OverrideBlink = UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.None, + // OverrideLookAt = UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.Block, + // OverrideMouth = UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.Blend, + // }; - // export - var gltf = UniVRM10.ExpressionAdapter.ToGltf(expression, new List(), new List()); - Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.none, gltf.OverrideBlink); - Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.block, gltf.OverrideLookAt); - Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.blend, gltf.OverrideMouth); + // // export + // var gltf = UniVRM10.ExpressionAdapter.ToGltf(expression, new List(), new List()); + // Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.none, gltf.OverrideBlink); + // Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.block, gltf.OverrideLookAt); + // Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.blend, gltf.OverrideMouth); - // import - var imported = UniVRM10.ExpressionAdapter.FromGltf(gltf, new List(), new List()); - Assert.AreEqual(VrmLib.ExpressionOverrideType.None, imported.OverrideBlink); - Assert.AreEqual(VrmLib.ExpressionOverrideType.Block, imported.OverrideLookAt); - Assert.AreEqual(VrmLib.ExpressionOverrideType.Blend, imported.OverrideMouth); + // // import + // var imported = UniVRM10.ExpressionAdapter.FromGltf(gltf, new List(), new List()); + // Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.None, imported.OverrideBlink); + // Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.Block, imported.OverrideLookAt); + // Assert.AreEqual(UniGLTF.Extensions.VRMC_vrm.ExpressionOverrideType.Blend, imported.OverrideMouth); } { - // export - foreach (var preset in Enum.GetValues(typeof(VrmLib.ExpressionPreset)) as VrmLib.ExpressionPreset[]) - { - var expression = new VrmLib.Expression(preset, "", false); + // // export + // foreach (var preset in Enum.GetValues(typeof(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset)) as UniGLTF.Extensions.VRMC_vrm.ExpressionPreset[]) + // { + // var expression = new UniGLTF.Extensions.VRMC_vrm.Expression(preset, "", false); - // expect no exception - var gltf = ExpressionAdapter.ToGltf( - expression, - new List(), - new List()); - } + // // expect no exception + // var gltf = ExpressionAdapter.ToGltf( + // expression, + // new List(), + // new List()); + // } - // import - foreach (var preset in Enum.GetValues(typeof(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset)) as UniGLTF.Extensions.VRMC_vrm.ExpressionPreset[]) - { - var gltf = new UniGLTF.Extensions.VRMC_vrm.Expression - { - Preset = preset, - }; + // // import + // foreach (var preset in Enum.GetValues(typeof(UniGLTF.Extensions.VRMC_vrm.ExpressionPreset)) as UniGLTF.Extensions.VRMC_vrm.ExpressionPreset[]) + // { + // var gltf = new UniGLTF.Extensions.VRMC_vrm.Expression + // { + // Preset = preset, + // }; - // expect no exception - ExpressionAdapter.FromGltf( - gltf, - new List(), - new List()); - } + // // expect no exception + // ExpressionAdapter.FromGltf( + // gltf, + // new List(), + // new List()); + // } } } } diff --git a/Assets/VRM10/Tests/TextureTests.cs b/Assets/VRM10/Tests/TextureTests.cs deleted file mode 100644 index 6dd794175..000000000 --- a/Assets/VRM10/Tests/TextureTests.cs +++ /dev/null @@ -1,171 +0,0 @@ -using NUnit.Framework; -using System.IO; -using UnityEngine; -using UnityEngine.Assertions; -using Assert = NUnit.Framework.Assert; - -namespace UniVRM10 -{ - public class TextureTests - { - [Test] - public void TextureExportTest() - { - //// Dummy texture - //var tex0 = new Texture2D(128, 128) - //{ - // wrapMode = TextureWrapMode.Clamp, - // filterMode = FilterMode.Trilinear, - //}; - //var textureManager = new TextureExportManager(new Texture[] {tex0}); - - //var material = new Material(Shader.Find("Standard")); - //material.mainTexture = tex0; - - //var materialExporter = new MaterialExporter(); - //materialExporter.ExportMaterial(material, textureManager); - - //var convTex0 = textureManager.GetExportTexture(0); - //var sampler = TextureSamplerUtil.Export(convTex0); - - //Assert.AreEqual(glWrap.CLAMP_TO_EDGE, sampler.wrapS); - //Assert.AreEqual(glWrap.CLAMP_TO_EDGE, sampler.wrapT); - //Assert.AreEqual(glFilter.LINEAR_MIPMAP_LINEAR, sampler.minFilter); - //Assert.AreEqual(glFilter.LINEAR_MIPMAP_LINEAR, sampler.magFilter); - } - } - - public class MetallicRoughnessConverterTests - { - const float epsilon = 0.005f; - private static void EqualColor(Color color1, Color color2) - { - Assert.AreEqual(color1.r, color2.r, epsilon); - Assert.AreEqual(color1.g, color2.g, epsilon); - Assert.AreEqual(color1.b, color2.b, epsilon); - Assert.AreEqual(color1.a, color2.a, epsilon); - } - - public static Texture2D CreateMonoTexture(Color color, bool isLinear) - { - var texture = new Texture2D(64, 64, TextureFormat.RGBA32, false, isLinear) - { - wrapMode = TextureWrapMode.Clamp, - filterMode = FilterMode.Trilinear, - }; - - Fill(texture, color); - return texture; - } - - public static void Fill(Texture2D texture, Color color) - { - for (int y = 0; y < texture.height; ++y) - { - for (int x = 0; x < texture.width; ++x) - { - texture.SetPixel(x, y, color); - } - } - texture.Apply(); - } - - public static Color GetColor(Texture2D texture) - { - return texture.GetPixel(0, 0); - } - - [Test] - public void ExportingColorTest() - { - - { - var smoothness = 1.0f; - var src = CreateMonoTexture(new UnityEngine.Color(1.0f, 1.0f, 1.0f, 1.0f), true); - var material = UniVRM10.TextureConvertMaterial.GetMetallicRoughnessUnityToGltf(smoothness); - var dst = UnityTextureUtil.CopyTexture(src, RenderTextureReadWrite.Linear, material); - // r <- 0 : (Unused) - // g <- 0 : ((1 - src.a(as float) * smoothness) ^ 2)(as uint8) - // b <- 255 : Same metallic (src.r) - // a <- 255 : (Unused) - EqualColor(GetColor(dst), new Color(0, 0, 1.0f, 1.0f)); - } - - { - var smoothness = 0.5f; - var src = CreateMonoTexture(new UnityEngine.Color(1.0f, 1.0f, 1.0f, 1.0f), true); - var material = UniVRM10.TextureConvertMaterial.GetMetallicRoughnessUnityToGltf(smoothness); - var dst = UnityTextureUtil.CopyTexture(src, RenderTextureReadWrite.Linear, material); - // r <- 0 : (Unused) - // g <- 63 : ((1 - src.a(as float) * smoothness) ^ 2)(as uint8) - // b <- 255 : Same metallic (src.r) - // a <- 255 : (Unused) - EqualColor(GetColor(dst), new Color(0, 0.25f, 1.0f, 1.0f)); - } - - { - var smoothness = 0.0f; - var src = CreateMonoTexture(new UnityEngine.Color(1.0f, 1.0f, 1.0f, 1.0f), true); - var material = UniVRM10.TextureConvertMaterial.GetMetallicRoughnessUnityToGltf(smoothness); - var dst = UnityTextureUtil.CopyTexture(src, RenderTextureReadWrite.Linear, material); - // r <- 0 : (Unused) - // g <- 255 : ((1 - src.a(as float) * smoothness) ^ 2)(as uint8) - // b <- 255 : Same metallic (src.r) - // a <- 255 : (Unused) - EqualColor(GetColor(dst), new Color(0, 1.0f, 1.0f, 1.0f)); - } - } - - [Test] - public void ImportingColorTest() - { - { - var roughnessFactor = 1.0f; - var src = CreateMonoTexture(new UnityEngine.Color(1.0f, 1.0f, 1.0f, 1.0f), true); - var material = UniVRM10.TextureConvertMaterial.GetMetallicRoughnessGltfToUnity(roughnessFactor); - var dst = UnityTextureUtil.CopyTexture(src, RenderTextureReadWrite.Linear, material); - // r <- 255 : Same metallic (src.r) - // g <- 0 : (Unused) - // b <- 0 : (Unused) - // a <- 0 : ((1 - sqrt(src.g(as float) * roughnessFactor)))(as uint8) - EqualColor(GetColor(dst), new Color(1.0f, 0, 0, 0)); - } - - { - var roughnessFactor = 1.0f; - var src = CreateMonoTexture(new UnityEngine.Color(1.0f, 0.25f, 1.0f, 1.0f), true); - var material = UniVRM10.TextureConvertMaterial.GetMetallicRoughnessGltfToUnity(roughnessFactor); - var dst = UnityTextureUtil.CopyTexture(src, RenderTextureReadWrite.Linear, material); - // r <- 255 : Same metallic (src.r) - // g <- 0 : (Unused) - // b <- 0 : (Unused) - // a <- 128 : ((1 - sqrt(src.g(as float) * roughnessFactor)))(as uint8) - EqualColor(GetColor(dst), new Color(1.0f, 0, 0, 0.5f)); - } - - { - var roughnessFactor = 0.5f; - var src = CreateMonoTexture(new UnityEngine.Color(1.0f, 1.0f, 1.0f, 1.0f), true); - var material = UniVRM10.TextureConvertMaterial.GetMetallicRoughnessGltfToUnity(roughnessFactor); - var dst = UnityTextureUtil.CopyTexture(src, RenderTextureReadWrite.Linear, material); - // r <- 255 : Same metallic (src.r) - // g <- 0 : (Unused) - // b <- 0 : (Unused) - // a <- 74 : ((1 - sqrt(src.g(as float) * roughnessFactor)))(as uint8) - EqualColor(GetColor(dst), new Color(1.0f, 0, 0, 0.29289f)); - } - - { - var roughnessFactor = 0.0f; - var src = CreateMonoTexture(new UnityEngine.Color(1.0f, 1.0f, 1.0f, 1.0f), true); - var material = UniVRM10.TextureConvertMaterial.GetMetallicRoughnessGltfToUnity(roughnessFactor); - var dst = UnityTextureUtil.CopyTexture(src, RenderTextureReadWrite.Linear, material); - // r <- 255 : Same metallic (src.r) - // g <- 0 : (Unused) - // b <- 0 : (Unused) - // a <- 255 : ((1 - sqrt(src.g(as float) * roughnessFactor)))(as uint8) - EqualColor(GetColor(dst), new Color(1.0f, 0, 0, 1.0f)); - } - } - } -} diff --git a/Assets/VRM10/Tests/TextureTests.cs.meta b/Assets/VRM10/Tests/TextureTests.cs.meta deleted file mode 100644 index 1fc373ed0..000000000 --- a/Assets/VRM10/Tests/TextureTests.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 782661967221c594196e50532a9eef88 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh.meta b/Assets/VRM10/vrmlib/Runtime/Bvh.meta deleted file mode 100644 index 0a55d43bc..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: ac2c48555929afa47903182006ab82d2 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh/Bvh.cs b/Assets/VRM10/vrmlib/Runtime/Bvh/Bvh.cs deleted file mode 100644 index c140b33fb..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh/Bvh.cs +++ /dev/null @@ -1,360 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; - -namespace VrmLib.Bvh -{ - public class BvhException : Exception - { - public BvhException(string msg) : base(msg) { } - } - - public enum Channel - { - Xposition, - Yposition, - Zposition, - Xrotation, - Yrotation, - Zrotation, - } - public static class ChannelExtensions - { - public static string ToProperty(this Channel ch) - { - switch (ch) - { - case Channel.Xposition: return "localPosition.x"; - case Channel.Yposition: return "localPosition.y"; - case Channel.Zposition: return "localPosition.z"; - case Channel.Xrotation: return "localEulerAnglesBaked.x"; - case Channel.Yrotation: return "localEulerAnglesBaked.y"; - case Channel.Zrotation: return "localEulerAnglesBaked.z"; - } - - throw new BvhException("no property for " + ch); - } - - public static bool IsLocation(this Channel ch) - { - switch (ch) - { - case Channel.Xposition: - case Channel.Yposition: - case Channel.Zposition: return true; - case Channel.Xrotation: - case Channel.Yrotation: - case Channel.Zrotation: return false; - } - - throw new BvhException("no property for " + ch); - } - } - - public class EndSite : BvhNode - { - public EndSite() : base("") - { - } - - public override void Parse(StringReader r) - { - r.ReadLine(); // offset - } - } - - public class ChannelCurve - { - public float[] Keys - { - get; - private set; - } - - public ChannelCurve(int frameCount) - { - Keys = new float[frameCount]; - } - - public void SetKey(int frame, float value) - { - Keys[frame] = value; - } - } - - public class Bvh - { - public BvhNode Root - { - get; - private set; - } - - public TimeSpan FrameTime - { - get; - private set; - } - - public ChannelCurve[] Channels - { - get; - private set; - } - - int m_frames; - public int FrameCount - { - get { return m_frames; } - } - - public struct PathWithProperty - { - public string Path; - public string Property; - public bool IsLocation; - } - - public bool TryGetPathWithPropertyFromChannel(ChannelCurve channel, out PathWithProperty pathWithProp) - { - var index = Channels.ToList().IndexOf(channel); - if (index == -1) - { - pathWithProp = default(PathWithProperty); - return false; - } - - foreach (var node in Root.Traverse()) - { - for (int i = 0; i < node.Channels.Length; ++i, --index) - { - if (index == 0) - { - pathWithProp = new PathWithProperty - { - Path = GetPath(node), - Property = node.Channels[i].ToProperty(), - IsLocation = node.Channels[i].IsLocation(), - }; - return true; - } - } - } - - throw new BvhException("channel is not found"); - } - - public string GetPath(BvhNode node) - { - var list = new List() { node.Name }; - - var current = node; - while (current != null) - { - current = GetParent(current); - if (current != null) - { - list.Insert(0, current.Name); - } - } - - return String.Join("/", list.ToArray()); - } - - BvhNode GetParent(BvhNode node) - { - foreach (var x in Root.Traverse()) - { - if (x.Children.Contains(node)) - { - return x; - } - } - - return null; - } - - public ChannelCurve GetChannel(BvhNode target, Channel channel) - { - var index = 0; - foreach (var node in Root.Traverse()) - { - for (int i = 0; i < node.Channels.Length; ++i, ++index) - { - if (node == target && node.Channels[i] == channel) - { - return Channels[index]; - } - } - } - - throw new BvhException("channel is not found"); - } - - public override string ToString() - { - return string.Format("{0}nodes, {1}channels, {2}frames, {3:0.00}seconds" - , Root.Traverse().Count() - , Channels.Length - , m_frames - , m_frames * FrameTime.TotalSeconds); - } - - public Bvh(BvhNode root, int frames, float seconds) - { - Root = root; - FrameTime = TimeSpan.FromSeconds(seconds); - m_frames = frames; - var channelCount = Root.Traverse() - .Where(x => x.Channels != null) - .Select(x => x.Channels.Length) - .Sum(); - Channels = Enumerable.Range(0, channelCount) - .Select(x => new ChannelCurve(frames)) - .ToArray() - ; - } - - public void ParseFrame(int frame, string line) - { - var splitted = line.Trim().Split().Where(x => !string.IsNullOrEmpty(x)).ToArray(); - if (splitted.Length != Channels.Length) - { - throw new BvhException("frame key count is not match channel count"); - } - for (int i = 0; i < Channels.Length; ++i) - { - Channels[i].SetKey(frame, float.Parse(splitted[i])); - } - } - } - - public static class BvhParser - { - static BvhNode ParseNode(StringReader r, int level = 0) - { - var firstline = r.ReadLine().Trim(); - var splitted = firstline.Split(); - if (splitted.Length != 2) - { - if (splitted.Length == 1) - { - if (splitted[0] == "}") - { - return null; - } - } - throw new BvhException(String.Format("splitted to {0}({1})", splitted.Length, firstline)); - } - - BvhNode node = null; - if (splitted[0] == "ROOT") - { - if (level != 0) - { - throw new BvhException("nested ROOT"); - } - node = new BvhNode(splitted[1]); - } - else if (splitted[0] == "JOINT") - { - if (level == 0) - { - throw new BvhException("should ROOT, but JOINT"); - } - node = new BvhNode(splitted[1]); - } - else if (splitted[0] == "End") - { - if (level == 0) - { - throw new BvhException("End in level 0"); - } - node = new EndSite(); - } - else - { - throw new BvhException("unknown type: " + splitted[0]); - } - - if (r.ReadLine().Trim() != "{") - { - throw new BvhException("'{' is not found"); - } - - node.Parse(r); - - // child nodes - while (true) - { - var child = ParseNode(r, level + 1); - if (child == null) - { - break; - } - - if (!(child is EndSite)) - { - node.AddChid(child); - } - } - - return node; - } - - public static Bvh FromPath(string path) - { - return Parse(File.ReadAllText(path)); - } - - public static Bvh Parse(string src) - { - using (var r = new StringReader(src)) - { - if (r.ReadLine() != "HIERARCHY") - { - throw new BvhException("not start with HIERARCHY"); - } - - var root = ParseNode(r); - if (root == null) - { - return null; - } - - var frames = 0; - var frameTime = 0.0f; - if (r.ReadLine() == "MOTION") - { - var frameSplitted = r.ReadLine().Split(':'); - if (frameSplitted[0] != "Frames") - { - throw new BvhException("Frames is not found"); - } - frames = int.Parse(frameSplitted[1]); - - var frameTimeSplitted = r.ReadLine().Split(':'); - if (frameTimeSplitted[0] != "Frame Time") - { - throw new BvhException("Frame Time is not found"); - } - frameTime = float.Parse(frameTimeSplitted[1]); - } - - var bvh = new Bvh(root, frames, frameTime); - - for (int i = 0; i < frames; ++i) - { - var line = r.ReadLine(); - bvh.ParseFrame(i, line); - } - - bvh.Root.UpdatePosition(Vector3.Zero); - - return bvh; - } - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh/Bvh.cs.meta b/Assets/VRM10/vrmlib/Runtime/Bvh/Bvh.cs.meta deleted file mode 100644 index 3451a2a10..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh/Bvh.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3876c0b36fb1fc54e9f7a5fc412967ec -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhAnimationClip.cs b/Assets/VRM10/vrmlib/Runtime/Bvh/BvhAnimationClip.cs deleted file mode 100644 index 1a836dd0a..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhAnimationClip.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Numerics; - -namespace VrmLib.Bvh -{ - public static class BvhAnimation - { - class CurveSet - { - BvhNode Node = default; - Func EulerToRotation = default; - public CurveSet(BvhNode node) - { - Node = node; - } - - public ChannelCurve PositionX = default; - public ChannelCurve PositionY = default; - public ChannelCurve PositionZ = default; - public Vector3 GetPosition(int i) - { - return new Vector3( - PositionX.Keys[i], - PositionY.Keys[i], - PositionZ.Keys[i]); - } - - public ChannelCurve RotationX = default; - public ChannelCurve RotationY = default; - public ChannelCurve RotationZ = default; - public Quaternion GetRotation(int i) - { - if (EulerToRotation == null) - { - EulerToRotation = Node.GetEulerToRotation(); - } - return EulerToRotation( - RotationX.Keys[i], - RotationY.Keys[i], - RotationZ.Keys[i] - ); - } - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhAnimationClip.cs.meta b/Assets/VRM10/vrmlib/Runtime/Bvh/BvhAnimationClip.cs.meta deleted file mode 100644 index 417828c56..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhAnimationClip.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 556644864ce505b43b0f967425a25c0c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhExtensions.cs b/Assets/VRM10/vrmlib/Runtime/Bvh/BvhExtensions.cs deleted file mode 100644 index 13b5b0eee..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhExtensions.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Linq; -using System.Numerics; - -namespace VrmLib.Bvh -{ - public static class BvhExtensions - { - public static Func GetEulerToRotation(this BvhNode bvh) - { - var order = bvh.Channels.Where(x => x == Channel.Xrotation || x == Channel.Yrotation || x == Channel.Zrotation).ToArray(); - - return (x, y, z) => - { - var xRot = Quaternion.CreateFromYawPitchRoll(x, 0, 0); - var yRot = Quaternion.CreateFromYawPitchRoll(0, y, 0); - var zRot = Quaternion.CreateFromYawPitchRoll(0, 0, z); - - var r = Quaternion.Identity; - foreach (var ch in order) - { - switch (ch) - { - case Channel.Xrotation: r = r * xRot; break; - case Channel.Yrotation: r = r * yRot; break; - case Channel.Zrotation: r = r * zRot; break; - default: throw new BvhException("no rotation"); - } - } - return r; - }; - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhExtensions.cs.meta b/Assets/VRM10/vrmlib/Runtime/Bvh/BvhExtensions.cs.meta deleted file mode 100644 index 59cc066a2..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: be2bfe50d0adaf24185001d94f5ff8e0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhNode.cs b/Assets/VRM10/vrmlib/Runtime/Bvh/BvhNode.cs deleted file mode 100644 index 6564d2a08..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhNode.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; - -namespace VrmLib.Bvh -{ - public class BvhNode - { - public String Name - { - get; - set; - } - - public override string ToString() - { - return $"{Name}"; - } - - public HumanoidBones Bone - { - get; - set; - } - - // world position - public Vector3 SkeletonLocalPosition - { - get; - private set; - } - - public void UpdatePosition(Vector3 parentPosition) - { - SkeletonLocalPosition = parentPosition + Offset; - - foreach (var child in Children) - { - child.UpdatePosition(SkeletonLocalPosition); - } - } - - public Vector3 Offset; - - public Channel[] Channels - { - get; - private set; - } - - List m_children = new List(); - - - public IReadOnlyList Children => m_children; - - - public void AddChid(BvhNode child) - { - child.Parent = this; - m_children.Add(child); - } - - - public BvhNode Parent - { - get; - private set; - } - - public BvhNode(string name) - { - Name = name; - } - - public virtual void Parse(StringReader r) - { - Offset = ParseOffset(r.ReadLine()); - - Channels = ParseChannel(r.ReadLine()); - } - - static Vector3 ParseOffset(string line) - { - var splited = line.Trim().Split(); - if (splited[0] != "OFFSET") - { - throw new BvhException("OFFSET is not found"); - } - - var offset = splited.Skip(1).Where(x => !string.IsNullOrEmpty(x)).Select(x => float.Parse(x)).ToArray(); - return new Vector3(offset[0], offset[1], offset[2]); - } - - static Channel[] ParseChannel(string line) - { - var splited = line.Trim().Split(); - if (splited[0] != "CHANNELS") - { - throw new BvhException("CHANNELS is not found"); - } - var count = int.Parse(splited[1]); - if (count + 2 != splited.Length) - { - throw new BvhException("channel count is not match with splited count"); - } - return splited.Skip(2).Select(x => (Channel)Enum.Parse(typeof(Channel), x)).ToArray(); - } - - public IEnumerable Traverse() - { - yield return this; - - foreach (var child in Children) - { - foreach (var descentant in child.Traverse()) - { - yield return descentant; - } - } - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhNode.cs.meta b/Assets/VRM10/vrmlib/Runtime/Bvh/BvhNode.cs.meta deleted file mode 100644 index db53f700d..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Bvh/BvhNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ac87eb7c7e9da9c458c0601587ed0bc9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/EnumUtil.cs b/Assets/VRM10/vrmlib/Runtime/EnumUtil.cs index 47e2fecf7..46447797e 100644 --- a/Assets/VRM10/vrmlib/Runtime/EnumUtil.cs +++ b/Assets/VRM10/vrmlib/Runtime/EnumUtil.cs @@ -44,7 +44,7 @@ namespace VrmLib static IEnumerable GetValues() { - foreach (var t in Enum.GetValues(typeof(Texture))) + foreach (var t in Enum.GetValues(typeof(T))) { yield return (T)t; } diff --git a/Assets/VRM10/vrmlib/Runtime/Humanoid/SkeletonMeshUtility.cs b/Assets/VRM10/vrmlib/Runtime/Humanoid/SkeletonMeshUtility.cs index 80dabe170..71a6e89ab 100644 --- a/Assets/VRM10/vrmlib/Runtime/Humanoid/SkeletonMeshUtility.cs +++ b/Assets/VRM10/vrmlib/Runtime/Humanoid/SkeletonMeshUtility.cs @@ -5,7 +5,7 @@ using System.Numerics; namespace VrmLib { - #pragma warning disable 0649 +#pragma warning disable 0649 struct BoneWeight { public int boneIndex0; @@ -18,7 +18,7 @@ namespace VrmLib public float weight2; public float weight3; } - #pragma warning restore +#pragma warning restore class MeshBuilder { @@ -68,7 +68,7 @@ namespace VrmLib { AddBone(head.SkeletonLocalPosition, tail.SkeletonLocalPosition, bones.IndexOf(head), headTail.XWidth, headTail.ZWidth); } - else if(headTail.TailOffset!=Vector3.Zero) + else if (headTail.TailOffset != Vector3.Zero) { AddBone(head.SkeletonLocalPosition, head.SkeletonLocalPosition + headTail.TailOffset, bones.IndexOf(head), headTail.XWidth, headTail.ZWidth); } @@ -150,25 +150,25 @@ namespace VrmLib void AddQuad(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, int boneIndex, bool reverse = false) { var i = m_positioins.Count; - if(float.IsNaN(v0.X) || float.IsNaN(v0.Y) || float.IsNaN(v0.Z)) + if (float.IsNaN(v0.X) || float.IsNaN(v0.Y) || float.IsNaN(v0.Z)) { throw new Exception(); } m_positioins.Add(v0); - if(float.IsNaN(v1.X) || float.IsNaN(v1.Y) || float.IsNaN(v1.Z)) + if (float.IsNaN(v1.X) || float.IsNaN(v1.Y) || float.IsNaN(v1.Z)) { throw new Exception(); } m_positioins.Add(v1); - if(float.IsNaN(v2.X) || float.IsNaN(v2.Y) || float.IsNaN(v2.Z)) + if (float.IsNaN(v2.X) || float.IsNaN(v2.Y) || float.IsNaN(v2.Z)) { throw new Exception(); } m_positioins.Add(v2); - if(float.IsNaN(v3.X) || float.IsNaN(v3.Y) || float.IsNaN(v3.Z)) + if (float.IsNaN(v3.X) || float.IsNaN(v3.Y) || float.IsNaN(v3.Z)) { throw new Exception(); } @@ -205,40 +205,6 @@ namespace VrmLib m_indices.Add(i); } } - - public Mesh CreateMesh() - { - if(m_positioins.Any(x => float.IsNaN(x.X) || float.IsNaN(x.Y) || float.IsNaN(x.Z))) - { - throw new Exception(); - } - - var mesh = new Mesh(); - mesh.VertexBuffer = new VertexBuffer(); - mesh.VertexBuffer.Add(VertexBuffer.PositionKey, - m_positioins.ToArray()); - - mesh.VertexBuffer.Add(VertexBuffer.JointKey, - m_boneWeights.Select(x => new SkinJoints( - (ushort)x.boneIndex0, - (ushort)x.boneIndex1, - (ushort)x.boneIndex2, - (ushort)x.boneIndex3)).ToArray()); - - mesh.VertexBuffer.Add(VertexBuffer.WeightKey, - m_boneWeights.Select(x => new Vector4( - x.weight0, - x.weight1, - x.weight2, - x.weight3 - )).ToArray()); - - mesh.IndexBuffer = BufferAccessor.Create(m_indices.ToArray()); - - mesh.Submeshes.Add(new Submesh(0, mesh.IndexBuffer.Count, null)); - - return mesh; - } } struct BoneHeadTail diff --git a/Assets/VRM10/vrmlib/Runtime/ImportExport.meta b/Assets/VRM10/vrmlib/Runtime/ImportExport.meta deleted file mode 100644 index b5f2845b8..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ImportExport.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 9089f6791c42b144ca66b29ea0f186db -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmExporter.cs b/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmExporter.cs deleted file mode 100644 index b47bb7ea9..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmExporter.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace VrmLib -{ - public interface IVrmExporter - { - byte[] ToBytes(); - - #region GLTF - void ExportAsset(Model model); - void Reserve(int bytesLength); - void ExportImageAndTextures(List images, List textures); - void ExportMaterialPBR(Material src, PBRMaterial pbr, List textures); - void ExportMaterialUnlit(Material src, UnlitMaterial unlit, List textures); - void ExportMaterialMToon(Material src, MToonMaterial mtoon, List textures); - void ExportMeshes(List groups, List materials, ExportArgs option); - void ExportNodes(Node root, List nodes, List groups, ExportArgs option); - void ExportAnimations(List animations, List nodes, ExportArgs option); - #endregion - - #region VRM - void ExportVrmMeta(Vrm src, List textures); - void ExportVrmHumanoid(Dictionary map, List nodes); - void ExportVrmMaterialProperties(List materials, List textures); - void ExportVrmExpression(ExpressionManager expression, List meshes, List materials, List nodes); - void ExportVrmSpringBone(SpringBoneManager springBone, List nodes); - void ExportVrmFirstPersonAndLookAt(FirstPerson firstPerson, LookAt lookat, List meshes, List nodes); - void ExportVrmEnd(); - #endregion - } - - public static class IExporterExtensions - { - public static byte[] Export(this IVrmExporter exporter, Model m, ExportArgs option) - { - exporter.ExportAsset(m); - - /// - /// 必要な容量を先に確保 - /// (sparseは考慮してないので大きめ) - /// - { - var reserveBytes = 0; - // image - foreach (var image in m.Images) - { - reserveBytes += image.Bytes.Count; - } - // mesh - foreach (var g in m.MeshGroups) - { - foreach (var mesh in g.Meshes) - { - // 頂点バッファ - reserveBytes += mesh.IndexBuffer.ByteLength; - foreach (var kv in mesh.VertexBuffer) - { - reserveBytes += kv.Value.ByteLength; - } - // morph - foreach (var morph in mesh.MorphTargets) - { - foreach (var kv in morph.VertexBuffer) - { - reserveBytes += kv.Value.ByteLength; - } - } - } - } - exporter.Reserve(reserveBytes); - } - - exporter.ExportImageAndTextures(m.Images, m.Textures); - - // material - foreach (var src in m.Materials) - { - if (src is MToonMaterial mtoon) - { - exporter.ExportMaterialMToon(src, mtoon, m.Textures); - } - else if (src is UnlitMaterial unlit) - { - exporter.ExportMaterialUnlit(src, unlit, m.Textures); - } - else if (src is PBRMaterial pbr) - { - exporter.ExportMaterialPBR(src, pbr, m.Textures); - } - else - { - throw new NotImplementedException(); - } - } - - // mesh - exporter.ExportMeshes(m.MeshGroups, m.Materials, option); - - // node - exporter.ExportNodes(m.Root, m.Nodes, m.MeshGroups, option); - - // animation - exporter.ExportAnimations(m.Animations, m.Nodes, option); - - if (option.vrm) - { - ExportVrm(exporter, m); - } - - return exporter.ToBytes(); - } - - static void ExportVrm(IVrmExporter exporter, Model m) - { - if (m.Vrm == null) - { - return; - } - - exporter.ExportVrmMeta(m.Vrm, m.Textures); - - exporter.ExportVrmHumanoid(m.GetBoneMap(), m.Nodes); - - exporter.ExportVrmMaterialProperties(m.Materials, m.Textures); - - exporter.ExportVrmExpression(m.Vrm.ExpressionManager, m.MeshGroups, m.Materials, m.Nodes); - - exporter.ExportVrmSpringBone(m.Vrm.SpringBone, m.Nodes); - - exporter.ExportVrmFirstPersonAndLookAt(m.Vrm.FirstPerson, m.Vrm.LookAt, m.MeshGroups, m.Nodes); - - exporter.ExportVrmEnd(); - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmExporter.cs.meta b/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmExporter.cs.meta deleted file mode 100644 index 39837ad1e..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmExporter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: be395fef7a307d5428ae184a77bda86e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmStorage.cs b/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmStorage.cs deleted file mode 100644 index 905008a27..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmStorage.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace VrmLib -{ - public interface IVrmStorage - { - ArraySegment OriginalJson { get; } - - #region glTF import - string AssetVersion { get; } - string AssetMinVersion { get; } - string AssetGenerator { get; } - string AssetCopyright { get; } - int NodeCount { get; } - Node CreateNode(int index); - IEnumerable GetChildNodeIndices(int i); - int ImageCount { get; } - Image CreateImage(int index); - int TextureCount { get; } - Texture CreateTexture(int index, List images); - int MaterialCount { get; } - Material CreateMaterial(int index, List textures); - int SkinCount { get; } - Skin CreateSkin(int index, List nodes); - int MeshCount { get; } - MeshGroup CreateMesh(int index, List materials); - (int, int) GetNodeMeshSkin(int index); - int AnimationCount { get; } - Animation CreateAnimation(int index, List nodes); - #endregion - - #region VRM - bool HasVrm { get; } - Meta CreateVrmMeta(List textures); - string VrmExporterVersion { get; } - string VrmSpecVersion { get; } - void LoadVrmHumanoid(List nodes); - ExpressionManager CreateVrmExpression(List meshGroups, List materials, List nodes); - SpringBoneManager CreateVrmSpringBone(List nodes); - FirstPerson CreateVrmFirstPerson(List nodes, List meshGroups); - LookAt CreateVrmLookAt(); - #endregion - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmStorage.cs.meta b/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmStorage.cs.meta deleted file mode 100644 index 440e16713..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ImportExport/IVrmStorage.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: dc7a9b66200d54043bef5c969aa774e7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/MToon.meta b/Assets/VRM10/vrmlib/Runtime/MToon.meta deleted file mode 100644 index cf0c676df..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 42b84fc3fef628142a69b9c3638867e9 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/Enums.cs b/Assets/VRM10/vrmlib/Runtime/MToon/Enums.cs deleted file mode 100644 index 121ac116f..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/Enums.cs +++ /dev/null @@ -1,51 +0,0 @@ -namespace VrmLib.MToon -{ - public enum DebugMode - { - None = 0, - Normal = 1, - LitShadeRate = 2, - } - - public enum OutlineColorMode - { - FixedColor = 0, - MixedLighting = 1, - } - - public enum OutlineWidthMode - { - None = 0, - WorldCoordinates = 1, - ScreenCoordinates = 2, - } - - public enum RenderMode - { - Opaque = 0, - Cutout = 1, - Transparent = 2, - TransparentWithZWrite = 3, - } - - public enum CullMode - { - Off = 0, - Front = 1, - Back = 2, - } - - public enum RotationUnit - { - Rounds = 0, - Degrees = 1, - Radians = 2 - } - - public struct RenderQueueRequirement - { - public int DefaultValue; - public int MinValue; - public int MaxValue; - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/Enums.cs.meta b/Assets/VRM10/vrmlib/Runtime/MToon/Enums.cs.meta deleted file mode 100644 index 6f620cf15..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/Enums.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 65d99cc4b12aae949ab5ce97d343348f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/EnumsEx.cs b/Assets/VRM10/vrmlib/Runtime/MToon/EnumsEx.cs deleted file mode 100644 index b7b0c2e15..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/EnumsEx.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace VrmLib.MToon -{ - public enum RenderQueue - { - Background = 1000, - Geometry = 2000, - AlphaTest = 2450, - GeometryLast = 2500, - Transparent = 3000, - Overlay = 4000 - } - - public enum BlendMode - { - Zero = 0, - One = 1, - DstColor = 2, - SrcColor = 3, - OneMinusDstColor = 4, - SrcAlpha = 5, - OneMinusSrcColor = 6, - DstAlpha = 7, - OneMinusDstAlpha = 8, - SrcAlphaSaturate = 9, - OneMinusSrcAlpha = 10 - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/EnumsEx.cs.meta b/Assets/VRM10/vrmlib/Runtime/MToon/EnumsEx.cs.meta deleted file mode 100644 index 8658da65c..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/EnumsEx.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0e1d9671390f90c4e99f4d840cf5a417 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/MToonDefinition.cs b/Assets/VRM10/vrmlib/Runtime/MToon/MToonDefinition.cs deleted file mode 100644 index 6627620b8..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/MToonDefinition.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System.Numerics; -using Color = VrmLib.LinearColor; -using Texture2D = VrmLib.TextureInfo; - -namespace VrmLib.MToon -{ - public class MToonDefinition - { - public MetaDefinition Meta; - public RenderingDefinition Rendering; - public ColorDefinition Color; - public LightingDefinition Lighting; - public EmissionDefinition Emission; - public MatCapDefinition MatCap; - public RimDefinition Rim; - public OutlineDefinition Outline; - public TextureUvCoordsDefinition TextureOption; - } - - public class MetaDefinition - { - public string Implementation; - public int VersionNumber; - } - - public class RenderingDefinition - { - public RenderMode RenderMode; - public CullMode CullMode; - public int RenderQueueOffsetNumber; - } - - public class ColorDefinition - { - public Color LitColor; - public Texture2D LitMultiplyTexture; - public Color ShadeColor; - public Texture2D ShadeMultiplyTexture; - public float CutoutThresholdValue; - } - - public class LightingDefinition - { - public LitAndShadeMixingDefinition LitAndShadeMixing; - public LightingInfluenceDefinition LightingInfluence; - public NormalDefinition Normal; - } - - public class LitAndShadeMixingDefinition - { - public float ShadingShiftValue; - public float ShadingToonyValue; - public float ShadowReceiveMultiplierValue; - public Texture2D ShadowReceiveMultiplierMultiplyTexture; - public float LitAndShadeMixingMultiplierValue; - public Texture2D LitAndShadeMixingMultiplierMultiplyTexture; - } - - public class LightingInfluenceDefinition - { - public float LightColorAttenuationValue; - public float GiIntensityValue; - } - - public class EmissionDefinition - { - public Color EmissionColor; - public Texture2D EmissionMultiplyTexture; - } - - public class MatCapDefinition - { - public Texture2D AdditiveTexture; - } - - public class RimDefinition - { - public Color RimColor; - public Texture2D RimMultiplyTexture; - public float RimLightingMixValue; - public float RimFresnelPowerValue; - public float RimLiftValue; - } - - public class NormalDefinition - { - public Texture2D NormalTexture; - public float NormalScaleValue = 1.0f; - } - - public class OutlineDefinition - { - public OutlineWidthMode OutlineWidthMode; - public float OutlineWidthValue; - public Texture2D OutlineWidthMultiplyTexture; - public float OutlineScaledMaxDistanceValue; - public OutlineColorMode OutlineColorMode; - public Color OutlineColor; - public float OutlineLightingMixValue; - } - - public class TextureUvCoordsDefinition - { - public Vector2 MainTextureLeftBottomOriginScale = Vector2.One; - public Vector2 MainTextureLeftBottomOriginOffset; - public Texture2D UvAnimationMaskTexture; - public float UvAnimationScrollXSpeedValue; - public float UvAnimationScrollYSpeedValue; - public float UvAnimationRotationSpeedValue; - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/MToonDefinition.cs.meta b/Assets/VRM10/vrmlib/Runtime/MToon/MToonDefinition.cs.meta deleted file mode 100644 index 79c2e008d..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/MToonDefinition.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bb3219008785c29408ca542a4352f517 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/Utils.cs b/Assets/VRM10/vrmlib/Runtime/MToon/Utils.cs deleted file mode 100644 index b4a66d415..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/Utils.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System; - -namespace VrmLib.MToon -{ - /// - /// from https://github.com/Santarh/MToon/tree/master/MToon/Scripts - /// - /// * namespace MToon to VrmLib.Mtoon - /// * remove `using UnityEngine;` - /// * remove `using UnityEngine.Rendering;` - /// * change static class to class - /// * using Color = VrmLib.LinearColor; - /// * using Texture2D = VrmLib.TextureInfo; - /// - /// - public partial class Utils - { - public const string ShaderName = "VRM/MToon"; - - public const string PropVersion = "_MToonVersion"; - public const string PropDebugMode = "_DebugMode"; - public const string PropOutlineWidthMode = "_OutlineWidthMode"; - public const string PropOutlineColorMode = "_OutlineColorMode"; - public const string PropBlendMode = "_BlendMode"; - public const string PropCullMode = "_CullMode"; - public const string PropOutlineCullMode = "_OutlineCullMode"; - public const string PropCutoff = "_Cutoff"; - public const string PropColor = "_Color"; - public const string PropShadeColor = "_ShadeColor"; - public const string PropMainTex = "_MainTex"; - public const string PropShadeTexture = "_ShadeTexture"; - public const string PropBumpScale = "_BumpScale"; - public const string PropBumpMap = "_BumpMap"; - public const string PropReceiveShadowRate = "_ReceiveShadowRate"; - public const string PropReceiveShadowTexture = "_ReceiveShadowTexture"; - public const string PropShadingGradeRate = "_ShadingGradeRate"; - public const string PropShadingGradeTexture = "_ShadingGradeTexture"; - public const string PropShadeShift = "_ShadeShift"; - public const string PropShadeToony = "_ShadeToony"; - public const string PropLightColorAttenuation = "_LightColorAttenuation"; - public const string PropIndirectLightIntensity = "_IndirectLightIntensity"; - public const string PropRimColor = "_RimColor"; - public const string PropRimTexture = "_RimTexture"; - public const string PropRimLightingMix = "_RimLightingMix"; - public const string PropRimFresnelPower = "_RimFresnelPower"; - public const string PropRimLift = "_RimLift"; - public const string PropSphereAdd = "_SphereAdd"; - public const string PropEmissionColor = "_EmissionColor"; - public const string PropEmissionMap = "_EmissionMap"; - public const string PropOutlineWidthTexture = "_OutlineWidthTexture"; - public const string PropOutlineWidth = "_OutlineWidth"; - public const string PropOutlineScaledMaxDistance = "_OutlineScaledMaxDistance"; - public const string PropOutlineColor = "_OutlineColor"; - public const string PropOutlineLightingMix = "_OutlineLightingMix"; - public const string PropUvAnimMaskTexture = "_UvAnimMaskTexture"; - public const string PropUvAnimScrollX = "_UvAnimScrollX"; - public const string PropUvAnimScrollY = "_UvAnimScrollY"; - public const string PropUvAnimRotation = "_UvAnimRotation"; - public const string PropSrcBlend = "_SrcBlend"; - public const string PropDstBlend = "_DstBlend"; - public const string PropZWrite = "_ZWrite"; - public const string PropAlphaToMask = "_AlphaToMask"; - - public const string KeyNormalMap = "_NORMALMAP"; - public const string KeyAlphaTestOn = "_ALPHATEST_ON"; - public const string KeyAlphaBlendOn = "_ALPHABLEND_ON"; - public const string KeyAlphaPremultiplyOn = "_ALPHAPREMULTIPLY_ON"; - public const string KeyOutlineWidthWorld = "MTOON_OUTLINE_WIDTH_WORLD"; - public const string KeyOutlineWidthScreen = "MTOON_OUTLINE_WIDTH_SCREEN"; - public const string KeyOutlineColorFixed = "MTOON_OUTLINE_COLOR_FIXED"; - public const string KeyOutlineColorMixed = "MTOON_OUTLINE_COLOR_MIXED"; - public const string KeyDebugNormal = "MTOON_DEBUG_NORMAL"; - public const string KeyDebugLitShadeRate = "MTOON_DEBUG_LITSHADERATE"; - - public const string TagRenderTypeKey = "RenderType"; - public const string TagRenderTypeValueOpaque = "Opaque"; - public const string TagRenderTypeValueTransparentCutout = "TransparentCutout"; - public const string TagRenderTypeValueTransparent = "Transparent"; - - public const int DisabledIntValue = 0; - public const int EnabledIntValue = 1; - - public static RenderQueueRequirement GetRenderQueueRequirement(RenderMode renderMode) - { - const int shaderDefaultQueue = -1; - const int firstTransparentQueue = 2501; - const int spanOfQueue = 50; - - switch (renderMode) - { - case RenderMode.Opaque: - return new RenderQueueRequirement() - { - DefaultValue = shaderDefaultQueue, - MinValue = shaderDefaultQueue, - MaxValue = shaderDefaultQueue, - }; - case RenderMode.Cutout: - return new RenderQueueRequirement() - { - DefaultValue = (int)RenderQueue.AlphaTest, - MinValue = (int)RenderQueue.AlphaTest, - MaxValue = (int)RenderQueue.AlphaTest, - }; - case RenderMode.Transparent: - return new RenderQueueRequirement() - { - DefaultValue = (int)RenderQueue.Transparent, - MinValue = (int)RenderQueue.Transparent - spanOfQueue + 1, - MaxValue = (int)RenderQueue.Transparent, - }; - case RenderMode.TransparentWithZWrite: - return new RenderQueueRequirement() - { - DefaultValue = firstTransparentQueue, - MinValue = firstTransparentQueue, - MaxValue = firstTransparentQueue + spanOfQueue - 1, - }; - default: - throw new ArgumentOutOfRangeException("renderMode", renderMode, null); - } - } - - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/Utils.cs.meta b/Assets/VRM10/vrmlib/Runtime/MToon/Utils.cs.meta deleted file mode 100644 index 8153ed560..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/Utils.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ab8e72c10cd2ffa46aeebba6db2775b9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/UtilsVersion.cs b/Assets/VRM10/vrmlib/Runtime/MToon/UtilsVersion.cs deleted file mode 100644 index a4cddf1fc..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/UtilsVersion.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace VrmLib.MToon -{ - public partial class Utils - { - public const string Implementation = "Santarh/MToon"; - public const int VersionNumber = 32; - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/MToon/UtilsVersion.cs.meta b/Assets/VRM10/vrmlib/Runtime/MToon/UtilsVersion.cs.meta deleted file mode 100644 index 16d2ecd56..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MToon/UtilsVersion.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0f7dbc0d574925f4cb061f82618910a0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material.meta b/Assets/VRM10/vrmlib/Runtime/Material.meta deleted file mode 100644 index 0484e4cc8..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: e1ee80125f7de8c4888e2591bce7d759 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material/AlphaModeType.cs b/Assets/VRM10/vrmlib/Runtime/Material/AlphaModeType.cs deleted file mode 100644 index 77eae82be..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/AlphaModeType.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace VrmLib -{ - public enum AlphaModeType - { - OPAQUE, - MASK, - BLEND, - BLEND_ZWRITE, - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Material/AlphaModeType.cs.meta b/Assets/VRM10/vrmlib/Runtime/Material/AlphaModeType.cs.meta deleted file mode 100644 index 53fa101c3..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/AlphaModeType.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4daa4a30bc14c074aa34243dd719d20e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material/ColorSpace.cs b/Assets/VRM10/vrmlib/Runtime/Material/ColorSpace.cs deleted file mode 100644 index bfda42f6d..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/ColorSpace.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.Numerics; - -namespace VrmLib -{ - public struct LinearColor : IEquatable - { - public Vector4 RGBA; - - public float[] ToFloat4() - { - return new float[]{ - RGBA.X, - RGBA.Y, - RGBA.Z, - RGBA.W, - }; - } - - public float[] ToFloat3() - { - return new float[]{ - RGBA.X, - RGBA.Y, - RGBA.Z, - }; - } - - public override bool Equals(object obj) - { - if (obj is LinearColor color) - { - return Equals(color); - } - else - { - return false; - } - } - - public override int GetHashCode() - { - return RGBA.GetHashCode(); - } - - public static bool operator ==(LinearColor lhs, LinearColor rhs) - { - return lhs.Equals(rhs); - } - - public static bool operator !=(LinearColor lhs, LinearColor rhs) - { - return !(lhs == rhs); - } - - public static LinearColor FromLiner(Vector4 color) - { - return new LinearColor - { - RGBA = color - }; - } - - public static LinearColor FromLiner(float r, float g, float b, float a) - { - return new LinearColor - { - RGBA = new Vector4(r, g, b, a) - }; - } - - public static LinearColor FromLiner(float[] color) - { - return new LinearColor - { - RGBA = new Vector4(color[0], color[1], color[2], color[3]) - }; - } - - public static LinearColor White => new LinearColor - { - RGBA = Vector4.One, - }; - - public static LinearColor Black => new LinearColor - { - RGBA = new Vector4(0, 0, 0, 1), - }; - - public bool Equals(LinearColor other) - { - return RGBA == other.RGBA; - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Material/ColorSpace.cs.meta b/Assets/VRM10/vrmlib/Runtime/Material/ColorSpace.cs.meta deleted file mode 100644 index bc86c95bc..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/ColorSpace.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e00837e0bb376a0438a56ba05d5fcb6a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material/Image.cs b/Assets/VRM10/vrmlib/Runtime/Material/Image.cs deleted file mode 100644 index ad4355854..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/Image.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace VrmLib -{ - /// - /// 画像の用途 - /// - [Flags] - public enum ImageUsage - { - None, - Color, - Normal, - } - - struct PngChunk - { - public readonly string Type; - public readonly ArraySegment Data; - - public readonly ArraySegment CRC; - - public PngChunk(string type, ArraySegment data, ArraySegment crc) - { - Type = type; - Data = data; - CRC = crc; - } - - public override string ToString() - { - return $"{Type}: {Data.Count} bytes"; - } - } - - static class PngUtil - { - static readonly Byte[] PNG_MAGIC = new byte[] - { - 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A - }; - - // big endian - public static int ToInt32BE(ArraySegment bytes) - { - var endian = bytes.Slice(0, 4).ToArray(); - // endian.AsSpan().Reverse(); // to LE - // return BitConverter.ToInt32(endian); - return endian[3] | (8 << endian[2]) | (16 << endian[1]) | (24 << endian[0]); - } - - public static IEnumerable ParseBytes(ArraySegment bytes) - { - if (!bytes.Slice(0, 8).SequenceEqual(PNG_MAGIC)) - { - throw new FormatException("is not png"); - } - bytes = bytes.Slice(8); - - while (bytes.Count > 0) - { - var length = ToInt32BE(bytes); - bytes = bytes.Slice(4); - - var type = bytes.Slice(0, 4); - var chunkType = Encoding.ASCII.GetString(type.Array, type.Offset, type.Count); - bytes = bytes.Slice(4); - - var data = bytes.Slice(0, length); - bytes = bytes.Slice(length); - - var crc = bytes.Slice(0, 4); - bytes = bytes.Slice(4); - - yield return new PngChunk(chunkType, data, crc); - } - } - } - - public class Image : GltfId - { - public string Name; - public string MimeType; - public ArraySegment Bytes; - - public ImageUsage Usage; - - public override string ToString() - { - if (MimeType == "image/png") - { - foreach (var chunk in PngUtil.ParseBytes(Bytes)) - { - if (chunk.Type == "IHDR") - { - - var w = PngUtil.ToInt32BE(chunk.Data.Slice(0, 4)); - var h = PngUtil.ToInt32BE(chunk.Data.Slice(4, 4)); - return $"{Name}: {MimeType}: {w}x{h}"; - } - } - } - - return $"{Name}: {MimeType}: {Bytes.Count} bytes"; - } - - public Image(string name, string mimeType, ImageUsage usage, ArraySegment bytes) - { - Name = name; - MimeType = mimeType; - Bytes = bytes; - Usage = usage; - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Material/Image.cs.meta b/Assets/VRM10/vrmlib/Runtime/Material/Image.cs.meta deleted file mode 100644 index b33b264ad..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/Image.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3b80c203904677843915b1b442c18519 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material/Material.cs b/Assets/VRM10/vrmlib/Runtime/Material/Material.cs deleted file mode 100644 index c9f50828c..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/Material.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Collections.Generic; -using System; -using System.Numerics; - -namespace VrmLib -{ - public class Material: GltfId - { - public string Name; - - public virtual LinearColor BaseColorFactor - { - get; - set; - } = LinearColor.White; - - public virtual TextureInfo BaseColorTexture - { - get; - set; - } - - public virtual AlphaModeType AlphaMode - { - get; - set; - } = AlphaModeType.OPAQUE; - - public virtual float AlphaCutoff - { - get; - set; - } = 0.5f; - - public virtual bool DoubleSided - { - get; - set; - } - - public Material(string name) - { - Name = name; - } - - static protected bool ImageIsEquals(Image lhs, Image rhs) - { - if (lhs is null) - { - return rhs is null; - } - else - { - if (rhs is null) - { - return false; - } - } - - if (!lhs.Bytes.Equals(rhs.Bytes)) - { - return false; - } - - return true; - } - - static protected bool TextureIsEquals(TextureInfo lhs, TextureInfo rhs) - { - if (lhs is null) - { - return rhs is null; - } - else - { - if (rhs is null) - { - return false; - } - } - - if (lhs.Offset != rhs.Offset) return false; - if (lhs.Scaling != rhs.Scaling) return false; - - if (lhs.Texture is ImageTexture lImage && rhs.Texture is ImageTexture rImage) - { - if (!ImageIsEquals(lImage.Image, rImage.Image)) - { - return false; - } - } - else - { - return false; - } - - return true; - } - - public virtual bool CanIntegrate(Material rhs) - { - return false; - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Material/Material.cs.meta b/Assets/VRM10/vrmlib/Runtime/Material/Material.cs.meta deleted file mode 100644 index 159f6dd36..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/Material.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6eb1bafca5d964e44a1de8c990d715a3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material/PBRMaterial.cs b/Assets/VRM10/vrmlib/Runtime/Material/PBRMaterial.cs deleted file mode 100644 index 75981b310..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/PBRMaterial.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Numerics; - -namespace VrmLib -{ - public class PBRMaterial : Material, IEquatable - { - public PBRMaterial(string name) : base(name) - { - } - - public override string ToString() - { - var sb = new System.Text.StringBuilder(); - sb.Append($"[PBR]{Name}"); - if (BaseColorTexture != null) - { - sb.Append(" ColorTex"); - } - if (MetallicRoughnessTexture != null) - { - sb.Append(" MetallicRoughnessTex"); - } - if (EmissiveTexture != null) - { - sb.Append(" EmissiveTex"); - } - if (NormalTexture != null) - { - sb.Append(" NormalTex"); - } - if (OcclusionTexture != null) - { - sb.Append(" OcclusionTex"); - } - return sb.ToString(); - } - - public Single MetallicFactor; - public Single RoughnessFactor; - public Texture MetallicRoughnessTexture; - - public Vector3 EmissiveFactor = Vector3.Zero; - public Texture EmissiveTexture; - - public Texture NormalTexture; - public float NormalTextureScale = 1.0f; - - public Texture OcclusionTexture; - public float OcclusionTextureStrength = 1.0f; - - public bool Equals(PBRMaterial other) - { - if (!base.Equals(other)) return false; - if (MetallicFactor != other.MetallicFactor) return false; - if (RoughnessFactor != other.RoughnessFactor) return false; - if (MetallicRoughnessTexture != other.MetallicRoughnessTexture) return false; - if (EmissiveFactor != other.EmissiveFactor) return false; - if (EmissiveTexture != other.EmissiveTexture) return false; - if (NormalTexture != other.NormalTexture) return false; - if (NormalTextureScale != other.NormalTextureScale) return false; - if (OcclusionTexture != other.OcclusionTexture) return false; - if (OcclusionTextureStrength != other.OcclusionTextureStrength) return false; - - return true; - } - - public override bool CanIntegrate(Material _rhs) - { - var rhs = _rhs as PBRMaterial; - if (rhs == null) - { - return false; - } - - return this.Equals(rhs); - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/Material/PBRMaterial.cs.meta b/Assets/VRM10/vrmlib/Runtime/Material/PBRMaterial.cs.meta deleted file mode 100644 index a7136d535..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/PBRMaterial.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2fceae9e1295b7e45a7937a949ea5e6b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material/Texture.cs b/Assets/VRM10/vrmlib/Runtime/Material/Texture.cs deleted file mode 100644 index a5b819a07..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/Texture.cs +++ /dev/null @@ -1,162 +0,0 @@ -using System; -using System.Numerics; - -namespace VrmLib -{ - public enum TextureMagFilterType : int - { - NEAREST = 9728, - LINEAR = 9729 - } - - public enum TextureMinFilterType : int - { - NEAREST = 9728, - LINEAR = 9729, - - NEAREST_MIPMAP_NEAREST = 9984, - LINEAR_MIPMAP_NEAREST = 9985, - NEAREST_MIPMAP_LINEAR = 9986, - LINEAR_MIPMAP_LINEAR = 9987, - } - - public enum TextureWrapType : int - { - REPEAT = 10497, - CLAMP_TO_EDGE = 33071, - MIRRORED_REPEAT = 33648, - } - - public class TextureSampler - { - public TextureWrapType WrapS; - public TextureWrapType WrapT; - - public TextureMinFilterType MinFilter; - public TextureMagFilterType MagFilter; - } - - public abstract class Texture: GltfId - { - public enum TextureTypes - { - Default, - NormalMap, - MetallicRoughness, - Emissive, - Occlusion - }; - - public enum ColorSpaceTypes - { - Srgb, - Linear, - }; - - public string Name; - public TextureSampler Sampler; - public ColorSpaceTypes ColorSpace; - public TextureTypes TextureType; - - protected Texture(string name, TextureSampler sampler, ColorSpaceTypes colorSpace, TextureTypes textureType) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - Name = name; - Sampler = sampler; - ColorSpace = colorSpace; - TextureType = textureType; - } - } - - public class ImageTexture : Texture, IEquatable - { - public Image Image; - - public ImageTexture(string name, TextureSampler sampler, Image image, ColorSpaceTypes colorSpace, TextureTypes textureType = TextureTypes.Default) : base(name, sampler, colorSpace, textureType) - { - Image = image; - } - - public override string ToString() - { - return $"{Name}({Image.Name}: {Image.MimeType})"; - } - - public override int GetHashCode() - { - return base.GetHashCode(); - } - - public override bool Equals(object obj) - { - if (obj is ImageTexture rhs) - { - return Equals(rhs); - } - else - { - return false; - } - } - - public bool Equals(ImageTexture other) - { - if (Name != other.Name) return false; - // if (Offset != other.Offset) return false; - // if (Scaling != other.Scaling) return false; - if (!Image.Bytes.Equals(other.Image.Bytes)) return false; - return true; - } - } - - public class MetallicRoughnessImageTexture : ImageTexture - { - public float RoughnessFactor; - - public MetallicRoughnessImageTexture(string name, TextureSampler sampler, Image image, float roughnessFactor, ColorSpaceTypes colorSpace, TextureTypes textureType = TextureTypes.Default) - : base(name, sampler, image, colorSpace, textureType) - { - Image = image; - RoughnessFactor = roughnessFactor; - } - } - - /// - /// 単色の 2x2 テクスチャ - /// - public class SolidTexture : Texture - { - public readonly Vector4 Color; - - public SolidTexture(string name, TextureSampler sampler, Vector4 color, ColorSpaceTypes colorSpace, TextureTypes textureType) : base(name, sampler, colorSpace, textureType) - { - Color = color; - } - - public static readonly SolidTexture White = new SolidTexture("white", new TextureSampler(), Vector4.One, ColorSpaceTypes.Srgb, TextureTypes.Default); - } - - /// - /// レンダーターゲットの元になる - /// - public class RenderTexture : Texture - { - public int Width; - public int Height; - - public RenderTexture(string name, TextureSampler sampler, ColorSpaceTypes colorSpace, TextureTypes textureType, int width = 256, int height = 256) : base(name, sampler, colorSpace, textureType) - { - Width = width; - Height = height; - } - - public void Resize(int w, int h) - { - Width = w; - Height = h; - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Material/Texture.cs.meta b/Assets/VRM10/vrmlib/Runtime/Material/Texture.cs.meta deleted file mode 100644 index c0caa2976..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/Texture.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c424b000dcd245749bbf5c204453a6d9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material/TextureInfo.cs b/Assets/VRM10/vrmlib/Runtime/Material/TextureInfo.cs deleted file mode 100644 index d58e0d507..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/TextureInfo.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Numerics; - -namespace VrmLib -{ - public class TextureInfo - { - - public Texture Texture; - // uv = uv * scaling + offset - public Vector2 Offset; - public Vector2 Scaling = Vector2.One; - - public float[] OffsetScaling - { - get => new float[] { Offset.X, Offset.Y, Scaling.X, Scaling.Y }; - set - { - Offset.X = value[0]; - Offset.Y = value[1]; - Scaling.X = value[2]; - Scaling.Y = value[3]; - } - } - - public TextureInfo(Texture texture) - { - Texture = texture; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/Material/TextureInfo.cs.meta b/Assets/VRM10/vrmlib/Runtime/Material/TextureInfo.cs.meta deleted file mode 100644 index f26320f79..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/TextureInfo.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5d377e18003320f409858e0fe55e5e47 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Material/UnlitMaterial.cs b/Assets/VRM10/vrmlib/Runtime/Material/UnlitMaterial.cs deleted file mode 100644 index bc8ab0f53..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/UnlitMaterial.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Numerics; - -namespace VrmLib -{ - // - // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit - // - public class UnlitMaterial : Material - { - public const string ExtensionName = "KHR_materials_unlit"; - - public override string ToString() - { - var sb = new System.Text.StringBuilder(); - sb.Append($"[Unlit]{Name}"); - if (BaseColorTexture != null) - { - sb.Append($" => {BaseColorTexture}"); - } - return sb.ToString(); - } - - public UnlitMaterial(string name) : base(name) - { - } - - public override bool CanIntegrate(Material _rhs) - { - var rhs = _rhs as UnlitMaterial; - if (rhs == null) - { - return false; - } - - // copy - if (BaseColorFactor != rhs.BaseColorFactor) return false; - if (BaseColorTexture != rhs.BaseColorTexture) return false; - if (AlphaMode != rhs.AlphaMode) return false; - if (AlphaCutoff != rhs.AlphaCutoff) return false; - if (DoubleSided != rhs.DoubleSided) return false; - - return true; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/Material/UnlitMaterial.cs.meta b/Assets/VRM10/vrmlib/Runtime/Material/UnlitMaterial.cs.meta deleted file mode 100644 index a39e17bec..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Material/UnlitMaterial.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3211ce9591dfcb44493a22c111f91086 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Mesh.cs b/Assets/VRM10/vrmlib/Runtime/Mesh.cs index 2f6d4f57c..7de93f88e 100644 --- a/Assets/VRM10/vrmlib/Runtime/Mesh.cs +++ b/Assets/VRM10/vrmlib/Runtime/Mesh.cs @@ -34,18 +34,18 @@ namespace VrmLib { public int Offset; public int DrawCount; - public Material Material; + public int Material; public override string ToString() { - return $"{Material.Name}({DrawCount})"; + return $"{Material}({DrawCount})"; } - public Submesh(Material material) : this(0, 0, material) + public Submesh(int material) : this(0, 0, material) { } - public Submesh(int offset, int drawCount, Material material) + public Submesh(int offset, int drawCount, int material) { Offset = offset; DrawCount = drawCount; diff --git a/Assets/VRM10/vrmlib/Runtime/MeshExtensions.cs b/Assets/VRM10/vrmlib/Runtime/MeshExtensions.cs index fa068237c..0fa78c6ea 100644 --- a/Assets/VRM10/vrmlib/Runtime/MeshExtensions.cs +++ b/Assets/VRM10/vrmlib/Runtime/MeshExtensions.cs @@ -653,7 +653,7 @@ namespace VrmLib { // 連続して同じMaterialのSubMeshを連結する mesh.Submeshes.Clear(); - Material current = null; + int current = -1; foreach (var submesh in order) { if (current != submesh.Material) diff --git a/Assets/VRM10/vrmlib/Runtime/MeshFactory.cs b/Assets/VRM10/vrmlib/Runtime/MeshFactory.cs deleted file mode 100644 index 546985c0b..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MeshFactory.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Numerics; - -namespace VrmLib -{ - public static class MeshFactory - { - public static Mesh CreateQuadrangle() - { - var mesh = new Mesh(); - mesh.IndexBuffer = BufferAccessor.Create(new int[] { 0, 1, 2, 2, 3, 0 }); - mesh.VertexBuffer = new VertexBuffer(); - mesh.VertexBuffer.Add(VertexBuffer.PositionKey, new Vector3[]{ - new Vector3(-1, 1, 0), - new Vector3(1, 1, 0), - new Vector3(1, -1, 0), - new Vector3(-1, -1, 0), - }); - mesh.VertexBuffer.Add(VertexBuffer.TexCoordKey, new Vector2[]{ - new Vector2(0, 0), - new Vector2(1, 0), - new Vector2(1, 1), - new Vector2(0, 1), - }); - mesh.Submeshes.Add(new Submesh(0, 6, new Material("SCREEN"))); - return mesh; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/MeshFactory.cs.meta b/Assets/VRM10/vrmlib/Runtime/MeshFactory.cs.meta deleted file mode 100644 index f52f73bcf..000000000 --- a/Assets/VRM10/vrmlib/Runtime/MeshFactory.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d7c93f9da54dc08429261518417be9aa -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Model.cs b/Assets/VRM10/vrmlib/Runtime/Model.cs index deb5546fb..c445904a6 100644 --- a/Assets/VRM10/vrmlib/Runtime/Model.cs +++ b/Assets/VRM10/vrmlib/Runtime/Model.cs @@ -18,8 +18,6 @@ namespace VrmLib Coordinates = coordinates; } - public ArraySegment OriginalJson; - public Coordinates Coordinates; public string AssetVersion = "2.0"; @@ -27,14 +25,8 @@ namespace VrmLib public string AssetCopyright; public string AssetMinVersion; - // gltf/images - public readonly List Images = new List(); - - // gltf/textures - public readonly List Textures = new List(); - // gltf/materials - public readonly List Materials = new List(); + public readonly List Materials = new List(); // gltf/skins public readonly List Skins = new List(); @@ -80,8 +72,6 @@ namespace VrmLib Root.CalcWorldMatrix(); } - public Vrm Vrm; - public Dictionary GetBoneMap() { return Root.Traverse() @@ -94,16 +84,6 @@ namespace VrmLib var sb = new StringBuilder(); sb.Append($"[GLTF] generator: {AssetGenerator}\n"); - for (int i = 0; i < Images.Count; ++i) - { - var x = Images[i]; - sb.Append($"[Image#{i:00}] {x}\n"); - } - // for (int i = 0; i < Textures.Count; ++i) - // { - // var t = Textures[i]; - // sb.Append($"[Texture#{i:00}] {t}\n"); - // } for (int i = 0; i < Materials.Count; ++i) { var m = Materials[i]; @@ -126,38 +106,6 @@ namespace VrmLib sb.Append($"[Skin] {skin}\n"); } - // - // VRM - // - if (Vrm != null) - { - sb.Append($"[VRM] export: {Vrm.ExporterVersion}, spec: {Vrm.SpecVersion}\n"); - sb.Append($"[VRM][meta] {Vrm.Meta}\n"); - var boneMap = GetBoneMap(); - if (boneMap.Any()) - { - sb.Append($"[VRM][humanoid] {boneMap.Count}/{Enum.GetValues(typeof(HumanoidBones)).Length - 1}\n"); - if (boneMap.Keys.Contains(HumanoidBones.unknown)) - { - sb.Append($"[VRM][humanoid] {boneMap.Count} contains 'unknown'\n"); - } - if (boneMap.TryGetValue(HumanoidBones.jaw, out Node jaw)) - { - sb.Append($"[VRM][humanoid] contains 'jaw' => {jaw.Name}\n"); - } - } - if (Vrm.ExpressionManager != null - && Vrm.ExpressionManager.ExpressionList != null - && Vrm.ExpressionManager.ExpressionList.Any()) - { - sb.Append("[VRM][expression] "); - foreach (var ex in Vrm.ExpressionManager.ExpressionList) - { - sb.Append($"[{ex.Preset}]"); - } - sb.Append($"\n"); - } - } return sb.ToString(); } diff --git a/Assets/VRM10/vrmlib/Runtime/ModelDiff.cs b/Assets/VRM10/vrmlib/Runtime/ModelDiff.cs deleted file mode 100644 index f4c830b57..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelDiff.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace VrmLib.Diff -{ - static class ObjectExtensions - { - public static bool IsNull(this T self) - { - if (typeof(T).IsClass) - { - return self == null; - } - else - { - return false; - } - } - } - - public struct ModelDiff - { - public string Context; - public string Message; - - public override string ToString() - { - return $"{Context}: {Message}"; - } - } - - public struct ModelDiffContext - { - public readonly string Path; - - public readonly List List; - - ModelDiffContext(string path, List list) - { - Path = path; - List = list; - } - - public bool Push(T lhs, T rhs, Func pred = null) - { - if (pred != null) - { - if (!pred(this, lhs, rhs)) - { - List.Add(new ModelDiff - { - Context = Path, - Message = $"{lhs} != {rhs}", - }); - return false; - } - return true; - } - - if (!RequireComapre(lhs, rhs, out bool equals)) - { - return equals; - } - - if (lhs.Equals(rhs)) - { - return true; - } - else - { - List.Add(new ModelDiff - { - Context = Path, - Message = $"{lhs} != {rhs}", - }); - return false; - } - } - - public ModelDiffContext Enter(string key) - { - if (string.IsNullOrEmpty(Path)) - { - return new ModelDiffContext(key, List); - } - else - { - return new ModelDiffContext(Path + "." + key, List); - } - } - - public static ModelDiffContext Create() - { - return new ModelDiffContext("", new List()); - } - - public bool RequireComapre(object lhs, object rhs, out bool equals) - { - if (lhs is null) - { - if (rhs is null) - { - equals = true; - return false; - } - else - { - equals = false; - List.Add(new ModelDiff - { - Context = Path, - Message = "lhs is null" - }); - return false; - } - } - else - { - if (rhs is null) - { - equals = false; - List.Add(new ModelDiff - { - Context = Path, - Message = "rhs is null" - }); - return false; - } - } - - equals = false; - return true; - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/ModelDiff.cs.meta b/Assets/VRM10/vrmlib/Runtime/ModelDiff.cs.meta deleted file mode 100644 index 2f7236761..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelDiff.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1cef47aa218fe78498b3bc0e698b817a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/ModelDiffExtensions.cs b/Assets/VRM10/vrmlib/Runtime/ModelDiffExtensions.cs deleted file mode 100644 index dea18e469..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelDiffExtensions.cs +++ /dev/null @@ -1,540 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using VrmLib.MToon; - -namespace VrmLib.Diff -{ - public static class ModelDiffExtensions - { - /// - /// 違うところを集める(debug用) - /// - public static List Diff(this Model lhs, Model rhs) - { - var context = ModelDiffContext.Create(); - context.Enter(nameof(lhs.AssetGenerator)).Push(lhs.AssetGenerator, rhs.AssetGenerator, StringEquals); - context.Enter(nameof(lhs.AssetVersion)).Push(lhs.AssetVersion, rhs.AssetVersion, StringEquals); - context.Enter(nameof(lhs.AssetMinVersion)).Push(lhs.AssetMinVersion, rhs.AssetMinVersion, StringEquals); - context.Enter(nameof(lhs.AssetCopyright)).Push(lhs.AssetCopyright, rhs.AssetCopyright, StringEquals); - - // Materialの参照で比較する - ListDiff(context.Enter("Materials"), lhs.Materials, rhs.Materials, MaterialEquals); - ListDiff(context.Enter("Meshes"), lhs.MeshGroups, rhs.MeshGroups, MeshGroupEquals); - ListDiff(context.Enter("Nodes"), lhs.Nodes, rhs.Nodes, NodeEquals); - ListDiff(context.Enter("Skins"), lhs.Skins, rhs.Skins, SkinEquals); - Vrm(context.Enter("Vrm"), lhs, rhs); - - return context.List; - } - - #region Private - static bool ListDiff(ModelDiffContext context, List lhs, List rhs, Func pred, Func order = null) - { - var equals = true; - if (lhs.Count != rhs.Count) - { - equals = false; - context.List.Add(new ModelDiff - { - Context = context.Path, - Message = $"{lhs.Count} != {rhs.Count}", - }); - } - - var l = order != null ? lhs.OrderBy(order).GetEnumerator() : lhs.GetEnumerator(); - var r = order != null ? rhs.OrderBy(order).GetEnumerator() : rhs.GetEnumerator(); - for (int i = 0; i < lhs.Count; ++i) - { - l.MoveNext(); - r.MoveNext(); - if (!pred(context.Enter($"{i}"), l.Current, r.Current)) - equals = false; - } - return equals; - } - - const float EPSILON = 1e-5f; - - static bool Vector3NearlyEquals(ModelDiffContext _, Vector3 l, Vector3 r) - { - if (Math.Abs(l.X - r.X) > EPSILON) return false; - if (Math.Abs(l.Y - r.Y) > EPSILON) return false; - if (Math.Abs(l.Z - r.Z) > EPSILON) return false; - return true; - } - - static bool QuaternionNearlyEquals(ModelDiffContext _, Quaternion l, Quaternion r) - { - if (Math.Abs(l.X - r.X) > EPSILON) return false; - if (Math.Abs(l.Y - r.Y) > EPSILON) return false; - if (Math.Abs(l.Z - r.Z) > EPSILON) return false; - if (Math.Abs(l.W - r.W) > EPSILON) return false; - return true; - } - - static bool StringEquals(ModelDiffContext _, string l, string r) - { - if (string.IsNullOrEmpty(l)) - { - return string.IsNullOrEmpty(r); - } - else - { - if (string.IsNullOrEmpty(r)) - { - return false; - } - else - { - return l == r; - } - } - } - - static bool ImageBytesEquals(ModelDiffContext context, Image lhs, Image rhs) - { - if (lhs is null) - { - if (rhs is null) - { - return true; - } - else - { - return false; - } - } - if (rhs is null) - { - return false; - } - return lhs.Bytes.SequenceEqual(rhs.Bytes); - } - - static void Image(ModelDiffContext context, Image lhs, Image rhs) - { - context.Enter($"{lhs.Name}:{rhs.Name}").Push(lhs, rhs, ImageBytesEquals); - } - - static bool TextureInfoEquals(ModelDiffContext context, TextureInfo lhs, TextureInfo rhs) - { - if (!context.RequireComapre(lhs, rhs, out bool equals)) - { - return equals; - } - - if (lhs.Offset != rhs.Offset) - { - return false; - } - if (lhs.Scaling != rhs.Scaling) - { - return false; - } - return TextureEquals(context.Enter("Texture"), lhs.Texture, rhs.Texture); - } - - static bool TextureEquals(ModelDiffContext context, Texture lhs, Texture rhs) - { - if (!context.RequireComapre(lhs, rhs, out bool equals)) - { - if (!equals) - return false; - return true; - } - - equals = true; - if (!context.Enter("Name").Push(lhs.Name, rhs.Name, StringEquals)) - equals = false; - if (!context.Enter("MagFilter").Push(lhs.Sampler.MagFilter, rhs.Sampler.MagFilter)) - equals = false; - if (!context.Enter("MinFilter").Push(lhs.Sampler.MinFilter, rhs.Sampler.MinFilter)) - equals = false; - if (!context.Enter("WrapS").Push(lhs.Sampler.WrapS, rhs.Sampler.WrapS)) - equals = false; - if (!context.Enter("WrapT").Push(lhs.Sampler.WrapT, rhs.Sampler.WrapT)) - equals = false; - if (lhs is ImageTexture l && rhs is ImageTexture r) - { - if (!ImageBytesEquals(context, l.Image, r.Image)) - equals = false; - return equals; - } - else - { - return false; - } - } - - static void Texture(ModelDiffContext context, Texture lhs, Texture rhs) - { - context.Enter($"{lhs.Name}:{rhs.Name}").Push(lhs, rhs, TextureEquals); - } - - static bool BaseMaterialEquals(ModelDiffContext context, Material lhs, Material rhs) - { - var equals = true; - if (!context.Enter(nameof(lhs.AlphaCutoff)).Push(lhs.AlphaCutoff, rhs.AlphaCutoff)) equals = false; - if (!context.Enter(nameof(lhs.AlphaMode)).Push(lhs.AlphaMode, rhs.AlphaMode)) equals = false; - if (!context.Enter(nameof(lhs.BaseColorFactor)).Push(lhs.BaseColorFactor, rhs.BaseColorFactor)) equals = false; - if (!context.Enter(nameof(lhs.BaseColorTexture)).Push(lhs.BaseColorTexture?.Texture, rhs.BaseColorTexture?.Texture, TextureEquals)) equals = false; - if (!context.Enter(nameof(lhs.DoubleSided)).Push(lhs.DoubleSided, rhs.DoubleSided)) equals = false; - return equals; - } - - static bool PBRMaterialEquals(ModelDiffContext context, PBRMaterial lhs, PBRMaterial rhs) - { - var equals = true; - if (!BaseMaterialEquals(context, lhs, rhs)) equals = false; - if (!context.Enter(nameof(lhs.EmissiveFactor)).Push(lhs.EmissiveFactor, rhs.EmissiveFactor)) equals = false; - if (!context.Enter(nameof(lhs.EmissiveTexture)).Push(lhs.EmissiveTexture, rhs.EmissiveTexture, TextureEquals)) equals = false; - if (!context.Enter(nameof(lhs.MetallicFactor)).Push(lhs.MetallicFactor, rhs.MetallicFactor)) equals = false; - if (!context.Enter(nameof(lhs.MetallicRoughnessTexture)).Push(lhs.MetallicRoughnessTexture, rhs.MetallicRoughnessTexture, TextureEquals)) equals = false; - if (!context.Enter(nameof(lhs.NormalTexture)).Push(lhs.NormalTexture, rhs.NormalTexture, TextureEquals)) equals = false; - if (!context.Enter(nameof(lhs.OcclusionTexture)).Push(lhs.OcclusionTexture, rhs.OcclusionTexture, TextureEquals)) equals = false; - if (!context.Enter(nameof(lhs.RoughnessFactor)).Push(lhs.RoughnessFactor, rhs.RoughnessFactor)) equals = false; - return equals; - } - - static bool MToonDefinitionEquals(ModelDiffContext context, object lhs, object rhs, Type t) - { - if (!context.RequireComapre(lhs, rhs, out bool equals)) - { - return equals; - } - - equals = true; - foreach (var fi in t.GetFields()) - { - if (fi.FieldType == typeof(TextureInfo)) - { - if (!context.Enter(fi.Name).Push(fi.GetValue(lhs) as TextureInfo, fi.GetValue(rhs) as TextureInfo, TextureInfoEquals)) - equals = false; - } - else - { - if (!context.Enter(fi.Name).Push(fi.GetValue(lhs), fi.GetValue(rhs))) - equals = false; - } - } - return equals; - } - - static bool MToonDefinitionEquals(ModelDiffContext context, MToonDefinition lhs, MToonDefinition rhs) - { - var equals = true; - if (!MToonDefinitionEquals(context.Enter(nameof(MetaDefinition)), lhs?.Meta, rhs?.Meta, typeof(MetaDefinition))) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(ColorDefinition)), lhs?.Color, rhs?.Color, typeof(ColorDefinition))) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(OutlineDefinition)), lhs?.Outline, rhs?.Outline, typeof(OutlineDefinition))) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(LightingInfluenceDefinition)), lhs?.Lighting.LightingInfluence, rhs?.Lighting.LightingInfluence, typeof(LightingInfluenceDefinition))) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(LitAndShadeMixingDefinition)), lhs?.Lighting.LitAndShadeMixing, rhs?.Lighting.LitAndShadeMixing, typeof(LitAndShadeMixingDefinition))) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(EmissionDefinition)), lhs?.Emission, rhs?.Emission, typeof(EmissionDefinition))) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(MatCapDefinition)), lhs?.MatCap, rhs?.MatCap, typeof(MatCapDefinition))) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(RimDefinition)), lhs?.Rim, rhs?.Rim, typeof(RimDefinition))) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(TextureUvCoordsDefinition)), lhs?.TextureOption, rhs?.TextureOption, typeof(TextureUvCoordsDefinition))) - equals = false; - return equals; - } - - static bool MToonMaterialEquals(ModelDiffContext context, MToonMaterial lhs, MToonMaterial rhs) - { - var equals = true; - if (!BaseMaterialEquals(context, lhs, rhs)) - equals = false; - if (!context.Enter(nameof(lhs._DebugMode)).Push(lhs._DebugMode, rhs._DebugMode)) - equals = false; - if (!context.Enter(nameof(lhs._DstBlend)).Push(lhs._DstBlend, rhs._DstBlend)) - equals = false; - if (!context.Enter(nameof(lhs._SrcBlend)).Push(lhs._SrcBlend, rhs._SrcBlend)) - equals = false; - if (!context.Enter(nameof(lhs._ZWrite)).Push(lhs._ZWrite, rhs._ZWrite)) - equals = false; - if (!MToonDefinitionEquals(context.Enter(nameof(lhs.Definition)), lhs.Definition, rhs.Definition)) - equals = false; - // context.Enter(nameof(lhs.KeyWords)).Push( lhs.KeyWords, rhs.KeyWords); - return equals; - } - - static bool UnlitMaterialEquals(ModelDiffContext context, UnlitMaterial lhs, UnlitMaterial rhs) - { - return BaseMaterialEquals(context, lhs, rhs); - } - - public static bool MaterialEquals(ModelDiffContext context, Material l, Material r) - { - var equals = true; - if (!context.Enter("Name").Push(l.Name, r.Name, StringEquals)) - equals = false; - - // context.Enter($"{i}:{lhs[i].Name}:{rhs[i].Name}").Push( lhs[i], rhs[i], MaterialEquals); - if (l.GetType() != r.GetType()) - { - context.Enter($"Type").Push(l.GetType(), r.GetType()); - equals = false; - } - else if (l is PBRMaterial lp && r is PBRMaterial rp) - { - if (!PBRMaterialEquals(context.Enter($"(PBRMaterial)"), lp, rp)) - equals = false; - } - else if (l is MToonMaterial lm && r is MToonMaterial rm) - { - if (!MToonMaterialEquals(context.Enter($"(MToonMaterial)"), lm, rm)) - equals = false; - } - else if (l is UnlitMaterial lu && r is UnlitMaterial ru) - { - if (!UnlitMaterialEquals(context.Enter($"(UnlitMaterial)"), lu, ru)) - equals = false; - } - else - { - throw new Exception(); - } - return equals; - } - - static bool AccessorEquals(ModelDiffContext context, BufferAccessor lhs, BufferAccessor rhs) - { - if (!context.RequireComapre(lhs, rhs, out bool equals)) - { - return equals; - } - - return lhs.Bytes.SequenceEqual(rhs.Bytes); - } - - static bool VertexBufferEquals(ModelDiffContext context, VertexBuffer lhs, VertexBuffer rhs) - { - var equals = true; - foreach (var kv in lhs) - { - rhs.TryGetValue(kv.Key, out BufferAccessor accessor); - if (!context.Enter(kv.Key).Push(kv.Value, accessor, AccessorEquals)) equals = false; - } - return equals; - } - - static bool MeshEquals(ModelDiffContext context, Mesh lhs, Mesh rhs) - { - return VertexBufferEquals(context.Enter(nameof(lhs.VertexBuffer)), lhs.VertexBuffer, rhs.VertexBuffer); - } - - static bool MeshGroupEquals(ModelDiffContext context, MeshGroup lhs, MeshGroup rhs) - { - return ListDiff(context.Enter("Meshes"), lhs.Meshes, rhs.Meshes, MeshEquals); - } - - static bool NodeEquals(ModelDiffContext context, Node lhs, Node rhs) - { - if (lhs is null) - { - if (rhs is null) - { - return true; - } - else - { - return false; - } - } - else - { - if (rhs is null) - { - return false; - } - } - - var equals = true; - if (!context.Enter(nameof(lhs.Name)).Push(lhs.Name, rhs.Name, StringEquals)) equals = false; - if (!context.Enter(nameof(lhs.LocalTranslation)).Push(lhs.LocalTranslation, rhs.LocalTranslation, Vector3NearlyEquals)) equals = false; - if (!context.Enter(nameof(lhs.LocalRotation)).Push(lhs.LocalRotation, rhs.LocalRotation, QuaternionNearlyEquals)) equals = false; - if (!context.Enter(nameof(lhs.LocalScaling)).Push(lhs.LocalScaling, rhs.LocalScaling, Vector3NearlyEquals)) equals = false; - if (!context.Enter(nameof(lhs.Parent)).Push(lhs.Parent?.Name, rhs.Parent?.Name)) equals = false; - if (!context.Enter(nameof(lhs.HumanoidBone)).Push(lhs.HumanoidBone, rhs.HumanoidBone)) equals = false; - return equals; - } - - static bool SkinEquals(ModelDiffContext context, Skin lhs, Skin rhs) - { - var equals = true; - if (!context.Enter("Root").Push(lhs.Root, rhs.Root, NodeEquals)) equals = false; - if (!ListDiff(context.Enter("Joints"), lhs.Joints, rhs.Joints, NodeEquals)) equals = false; - if (!context.Enter("InverseMatrices").Push(lhs.InverseMatrices, rhs.InverseMatrices, AccessorEquals)) equals = false; - return equals; - } - - static void Vrm(ModelDiffContext context, Model lhs, Model rhs) - { - context.Enter(nameof(lhs.Vrm.SpecVersion)).Push(lhs.Vrm.SpecVersion, rhs.Vrm.SpecVersion); - context.Enter(nameof(lhs.Vrm.ExporterVersion)).Push(lhs.Vrm.ExporterVersion, rhs.Vrm.ExporterVersion); - VrmMeta(context.Enter(nameof(lhs.Vrm.Meta)), lhs.Vrm.Meta, rhs.Vrm.Meta); - ListDiff(context.Enter(nameof(lhs.Vrm.ExpressionManager)), lhs.Vrm.ExpressionManager.ExpressionList, rhs.Vrm.ExpressionManager.ExpressionList, VrmExpressionEquals, x => (int)x.Preset); - VrmFirstPerson(context.Enter(nameof(lhs.Vrm.FirstPerson)), lhs.Vrm.FirstPerson, rhs.Vrm.FirstPerson); - VrmLookAt(context.Enter(nameof(lhs.Vrm.LookAt)), lhs.Vrm.LookAt, rhs.Vrm.LookAt); - ListDiff(context.Enter("SpringBone.Springs"), lhs.Vrm.SpringBone.Springs, rhs.Vrm.SpringBone.Springs, VrmSpringBoneEquals); - } - - static void VrmMeta(ModelDiffContext context, Meta lhs, Meta rhs) - { - context.Enter(nameof(lhs.Name)).Push(lhs.Name, rhs.Name); - context.Enter(nameof(lhs.Version)).Push(lhs.Version, rhs.Version); - context.Enter(nameof(lhs.CopyrightInformation)).Push(lhs.CopyrightInformation, rhs.CopyrightInformation); - context.Enter(nameof(lhs.Author)).Push(lhs.Author, rhs.Author); - context.Enter(nameof(lhs.ContactInformation)).Push(lhs.ContactInformation, rhs.ContactInformation); - context.Enter(nameof(lhs.Reference)).Push(lhs.Reference, rhs.Reference); - context.Enter(nameof(lhs.Thumbnail)).Push(lhs.Thumbnail, rhs.Thumbnail, ImageBytesEquals); - // AvatarPermission - context.Enter(nameof(lhs.AvatarPermission.AvatarUsage)).Push(lhs.AvatarPermission.AvatarUsage, rhs.AvatarPermission.AvatarUsage); - context.Enter(nameof(lhs.AvatarPermission.IsAllowedViolentUsage)).Push(lhs.AvatarPermission.IsAllowedViolentUsage, rhs.AvatarPermission.IsAllowedViolentUsage); - context.Enter(nameof(lhs.AvatarPermission.IsAllowedSexualUsage)).Push(lhs.AvatarPermission.IsAllowedSexualUsage, rhs.AvatarPermission.IsAllowedSexualUsage); - context.Enter(nameof(lhs.AvatarPermission.IsAllowedCommercialUsage)).Push(lhs.AvatarPermission.IsAllowedCommercialUsage, rhs.AvatarPermission.IsAllowedCommercialUsage); - context.Enter(nameof(lhs.AvatarPermission.CommercialUsage)).Push(lhs.AvatarPermission.CommercialUsage, rhs.AvatarPermission.CommercialUsage); - context.Enter(nameof(lhs.AvatarPermission.IsAllowedCommercialUsage)).Push(lhs.AvatarPermission.IsAllowedCommercialUsage, rhs.AvatarPermission.IsAllowedCommercialUsage); - context.Enter(nameof(lhs.AvatarPermission.IsAllowedCommercialUsage)).Push(lhs.AvatarPermission.IsAllowedCommercialUsage, rhs.AvatarPermission.IsAllowedCommercialUsage); - context.Enter(nameof(lhs.AvatarPermission.OtherPermissionUrl)).Push(lhs.AvatarPermission.OtherPermissionUrl, rhs.AvatarPermission.OtherPermissionUrl); - // RedistributionLicense - context.Enter(nameof(lhs.RedistributionLicense.License)).Push(lhs.RedistributionLicense.License, rhs.RedistributionLicense.License); - context.Enter(nameof(lhs.RedistributionLicense.OtherLicenseUrl)).Push(lhs.RedistributionLicense.OtherLicenseUrl, rhs.RedistributionLicense.OtherLicenseUrl); - } - - static bool VrmExpressionEquals(ModelDiffContext context, Expression lhs, Expression rhs) - { - if (lhs.IsNull()) - { - if (rhs.IsNull()) - { - // ok - return true; - } - else - { - context.List.Add(new ModelDiff - { - Context = context.Path, - Message = "lhs is null", - }); - return false; - } - } - else - { - if (rhs.IsNull()) - { - context.List.Add(new ModelDiff - { - Context = context.Path, - Message = "rhs is null", - }); - return false; - } - } - - var equals = true; - if (!context.Enter(nameof(lhs.Preset)).Push(lhs.Preset, rhs.Preset)) equals = false; - if (!context.Enter(nameof(lhs.Name)).Push(lhs.Name, rhs.Name, StringEquals)) equals = false; - if (!context.Enter(nameof(lhs.IsBinary)).Push(lhs.IsBinary, rhs.IsBinary)) equals = false; - if (!ListDiff(context.Enter(nameof(lhs.MorphTargetBinds)), lhs.MorphTargetBinds, rhs.MorphTargetBinds, VrmExpressionBindValueEquals)) equals = false; - if (!ListDiff(context.Enter(nameof(lhs.MaterialColorBinds)), lhs.MaterialColorBinds, rhs.MaterialColorBinds, VrmMaterialBindValueEquals)) equals = false; - return equals; - } - - static bool VrmExpressionBindValueEquals(ModelDiffContext context, MorphTargetBind lhs, MorphTargetBind rhs) - { - var equals = true; - if (!context.Enter("Node").Push(lhs.Node, rhs.Node, NodeEquals)) equals = false; - if (!context.Enter("Name").Push(lhs.Name, rhs.Name)) equals = false; - if (!context.Enter("Value").Push(lhs.Value, rhs.Value)) equals = false; - return equals; - } - - static bool VrmMaterialBindValueEquals(ModelDiffContext context, MaterialColorBind lhs, MaterialColorBind rhs) - { - var equals = true; - if (!context.Enter("Material.Name").Push(lhs.Material.Name, rhs.Material.Name)) equals = false; - if (!context.Enter("Property").Push(lhs.Property, rhs.Property)) equals = false; - // if (!context.Enter("Value").Push(lhs.m_value, rhs.m_value)) equals = false; - if (!context.Enter("BindType").Push(lhs.BindType, rhs.BindType)) equals = false; - return equals; - } - - static bool FirstPersonMeshAnnotationEquals(ModelDiffContext context, FirstPersonMeshAnnotation lhs, FirstPersonMeshAnnotation rhs) - { - var equals = true; - if (!context.Enter("Node").Push(lhs.Node, rhs.Node, NodeEquals)) equals = false; - if (!context.Enter("Flag").Push(lhs.FirstPersonFlag, rhs.FirstPersonFlag)) equals = false; - return equals; - } - - static void VrmFirstPerson(ModelDiffContext context, FirstPerson lhs, FirstPerson rhs) - { - // context.Enter("HeadNode").Push(lhs.m_fp, rhs.m_fp, NodeEquals); - ListDiff(context.Enter("Annotations"), lhs.Annotations, rhs.Annotations, FirstPersonMeshAnnotationEquals); - } - - static void VrmLookAt(ModelDiffContext context, LookAt lhs, LookAt rhs) - { - context.Enter("Offset").Push(lhs.OffsetFromHeadBone, rhs.OffsetFromHeadBone, Vector3NearlyEquals); - context.Enter(nameof(lhs.LookAtType)).Push(lhs.LookAtType, rhs.LookAtType); - VrmLookAtRangeMap(context.Enter(nameof(lhs.HorizontalInner)), lhs.HorizontalInner, rhs.HorizontalInner); - VrmLookAtRangeMap(context.Enter(nameof(lhs.HorizontalOuter)), lhs.HorizontalOuter, rhs.HorizontalOuter); - VrmLookAtRangeMap(context.Enter(nameof(lhs.VerticalUp)), lhs.VerticalUp, rhs.VerticalUp); - VrmLookAtRangeMap(context.Enter(nameof(lhs.VerticalDown)), lhs.VerticalDown, rhs.VerticalDown); - } - - static void VrmLookAtRangeMap(ModelDiffContext context, LookAtRangeMap lhs, LookAtRangeMap rhs) - { - context.Enter(nameof(lhs.InputMaxValue)).Push(lhs.InputMaxValue, rhs.InputMaxValue); - context.Enter(nameof(lhs.OutputScaling)).Push(lhs.OutputScaling, rhs.OutputScaling); - context.Enter("Curve").Push(lhs.Curve, rhs.Curve); - } - - static bool VrmSpringBoneJointEquals(ModelDiffContext context, SpringJoint lhs, SpringJoint rhs) - { - var equals = true; - if (!context.Enter("DragForce").Push(lhs.DragForce, rhs.DragForce)) equals = false; - if (!context.Enter("GravityDir").Push(lhs.GravityDir, rhs.GravityDir)) equals = false; - if (!context.Enter("GravityPower").Push(lhs.GravityPower, rhs.GravityPower)) equals = false; - if (!context.Enter("HitRadius").Push(lhs.HitRadius, rhs.HitRadius)) equals = false; - if (!context.Enter("Stiffness").Push(lhs.Stiffness, rhs.Stiffness)) equals = false; - return equals; - } - - static bool VrmSpringBoneEquals(ModelDiffContext context, SpringBone lhs, SpringBone rhs) - { - var equals = true; - if (!context.Enter("Comment").Push(lhs.Comment, rhs.Comment)) equals = false; - if (!context.Enter("Origin").Push(lhs.Origin, rhs.Origin)) equals = false; - if (!ListDiff(context.Enter("Joint"), lhs.Joints, rhs.Joints, VrmSpringBoneJointEquals)) equals = false; - return equals; - } - - static bool VrmSpringBoneColliderEquals(ModelDiffContext context, VrmSpringBoneCollider lhs, VrmSpringBoneCollider rhs) - { - var equals = true; - if (!context.Enter("Offset").Push(lhs.Offset, rhs.Offset)) equals = false; - if (!context.Enter("Radius").Push(lhs.Radius, rhs.Radius)) equals = false; - return equals; - } - - static bool VrmSpringBoneColliderEquals(ModelDiffContext context, SpringBoneColliderGroup lhs, SpringBoneColliderGroup rhs) - { - var equals = true; - if (!context.Enter("Node").Push(lhs.Node, rhs.Node, NodeEquals)) equals = false; - if (!ListDiff(context.Enter("Colliders"), lhs.Colliders, rhs.Colliders, VrmSpringBoneColliderEquals)) equals = false; - return equals; - } - #endregion - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/ModelDiffExtensions.cs.meta b/Assets/VRM10/vrmlib/Runtime/ModelDiffExtensions.cs.meta deleted file mode 100644 index 3b2d45403..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelDiffExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 93cf70a1afdd7784e8c964726d98edd6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensions.cs b/Assets/VRM10/vrmlib/Runtime/ModelExtensions.cs index 2decb5c83..bb5b94a24 100644 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensions.cs +++ b/Assets/VRM10/vrmlib/Runtime/ModelExtensions.cs @@ -68,9 +68,6 @@ namespace VrmLib public static void CheckIndex(this Model model) { - CheckIndex(model.Images, nameof(model.Images)); - CheckIndex(model.Textures, nameof(model.Textures)); - CheckIndex(model.Materials, nameof(model.Materials)); CheckIndex(model.Nodes, nameof(model.Nodes)); CheckIndex(model.Skins, nameof(model.Skins)); CheckIndex(model.MeshGroups, nameof(model.MeshGroups)); diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForBvh.cs b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForBvh.cs deleted file mode 100644 index 8de2835b2..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForBvh.cs +++ /dev/null @@ -1,303 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using System.Runtime.InteropServices; -using VrmLib.Bvh; - -namespace VrmLib -{ - public static class ModelExtensionsForBvh - { - static float ToRad(float src) - { - return src / 180.0f * MathFWrap.PI; - } - - static BvhNode GetNode(BvhNode root, string path) - { - var splitted = path.Split('/'); - - var it = splitted.Select(x => x).GetEnumerator(); - var current = root; - if (splitted[0] == path) - { - return current; - } - it.MoveNext(); - while (it.MoveNext()) - { - current = current.Children.First(x => x.Name == it.Current); - } - - return current; - } - - public static Model CreateFromBvh(BvhNode node) - { - // add nodes - var model = new Model(Coordinates.Vrm1); - model.Root.Name = "__bvh_root__"; - - AddBvhNodeRecursive(model, model.Root, node); - - return model; - } - - static void AddBvhNodeRecursive(Model model, Node parent, BvhNode node) - { - var newNode = new Node(node.Name) - { - HumanoidBone = node.Bone, - }; - - model.Nodes.Add(newNode); - parent.Add(newNode); - newNode.Translation = node.SkeletonLocalPosition; - - foreach (var child in node.Children) - { - AddBvhNodeRecursive(model, newNode, child); - } - } - - class BvhNodeCurves - { - public Bvh.ChannelCurve LocalPositionX; - public Bvh.ChannelCurve LocalPositionY; - public Bvh.ChannelCurve LocalPositionZ; - - public Bvh.ChannelCurve EulerX; - public Bvh.ChannelCurve EulerY; - public Bvh.ChannelCurve EulerZ; - - public void Set(string prop, Bvh.ChannelCurve curve) - { - switch (prop) - { - case "localPosition.x": - LocalPositionX = curve; - break; - - case "localPosition.y": - LocalPositionY = curve; - break; - - case "localPosition.z": - LocalPositionZ = curve; - break; - - case "localEulerAnglesBaked.x": - EulerX = curve; - break; - - case "localEulerAnglesBaked.y": - EulerY = curve; - break; - - case "localEulerAnglesBaked.z": - EulerZ = curve; - break; - - default: - break; - } - } - } - - static Animation LoadAnimation(string name, Bvh.Bvh bvh, Model model, float scalingFactor) - { - var animation = new Animation(name); - - Dictionary pathMap = new Dictionary(); - - for (int i = 0; i < bvh.Channels.Length; ++i) - { - var channel = bvh.Channels[i]; - - if (!bvh.TryGetPathWithPropertyFromChannel(channel, out Bvh.Bvh.PathWithProperty prop)) - { - throw new Exception(); - } - - if (!pathMap.TryGetValue(prop.Path, out BvhNodeCurves curves)) - { - curves = new BvhNodeCurves(); - pathMap.Add(prop.Path, curves); - } - - curves.Set(prop.Property, channel); - } - - // setup time - var timeBytes = new byte[Marshal.SizeOf(typeof(float)) * bvh.FrameCount]; - var timeSpan = SpanLike.Wrap(new ArraySegment(timeBytes)); - var now = 0.0; - for (int i = 0; i < timeSpan.Length; ++i, now += bvh.FrameTime.TotalSeconds) - { - timeSpan[i] = (float)now; - } - var times = new BufferAccessor(new ArraySegment(timeBytes), AccessorValueType.FLOAT, AccessorVectorType.SCALAR, bvh.FrameCount); - - foreach (var (key, nodeCurve) in pathMap) - { - var node = Model.GetNode(model.Root, key); - var bvhNode = GetNode(bvh.Root, key); - var curve = new NodeAnimation(); - - if (nodeCurve.LocalPositionX != null) - { - var values = new byte[Marshal.SizeOf(typeof(Vector3)) - * nodeCurve.LocalPositionX.Keys.Length]; - var span = SpanLike.Wrap(new ArraySegment(values)); - for (int i = 0; i < nodeCurve.LocalPositionX.Keys.Length; ++i) - { - span[i] = new Vector3 - { - X = nodeCurve.LocalPositionX.Keys[i] * scalingFactor, - Y = nodeCurve.LocalPositionY.Keys[i] * scalingFactor, - Z = nodeCurve.LocalPositionZ.Keys[i] * scalingFactor, - }; - } - var sampler = new CurveSampler - { - In = times, - Out = new BufferAccessor(new ArraySegment(values), - AccessorValueType.FLOAT, AccessorVectorType.VEC3, span.Length) - }; - curve.Curves.Add(AnimationPathType.Translation, sampler); - } - - if (nodeCurve.EulerX != null) - { - var values = new byte[Marshal.SizeOf(typeof(Quaternion)) - * nodeCurve.EulerX.Keys.Length]; - var span = SpanLike.Wrap(new ArraySegment(values)); - - Func getRot = (q, c, i) => q; - - foreach (var ch in bvhNode.Channels) - { - var tmp = getRot; - switch (ch) - { - case Channel.Xrotation: - getRot = (_, c, i) => - { - return tmp(_, c, i) * - Quaternion.CreateFromAxisAngle(Vector3.UnitX, ToRad(c.EulerX.Keys[i])); - }; - break; - case Channel.Yrotation: - getRot = (_, c, i) => - { - return tmp(_, c, i) * - Quaternion.CreateFromAxisAngle(Vector3.UnitY, ToRad(c.EulerY.Keys[i])); - }; - break; - case Channel.Zrotation: - getRot = (_, c, i) => - { - return tmp(_, c, i) * - Quaternion.CreateFromAxisAngle(Vector3.UnitZ, ToRad(c.EulerZ.Keys[i])); - }; - break; - default: - // throw new NotImplementedException(); - break; - } - } - - for (int i = 0; i < nodeCurve.EulerX.Keys.Length; ++i) - { - span[i] = getRot(Quaternion.Identity, nodeCurve, i); - } - var sampler = new CurveSampler - { - In = times, - Out = new BufferAccessor(new ArraySegment(values), - AccessorValueType.FLOAT, AccessorVectorType.VEC4, span.Length) - }; - curve.Curves.Add(AnimationPathType.Rotation, sampler); - } - - animation.AddCurve(node, curve); - } - - return animation; - } - - public static Model Load(string name, Bvh.Bvh bvh) - { - var model = CreateFromBvh(bvh.Root); - - // estimate skeleton - var skeleton = SkeletonEstimator.Detect(model.Root); - if (skeleton == null) - { - throw new Exception("fail to estimate skeleton"); - } - - // foot to zero - var minY = model.Nodes.Min(x => x.Translation.Y); - var hips = model.Nodes.First(x => x.HumanoidBone == HumanoidBones.hips); - if (model.Root.Children.Count != 1) - { - throw new Exception(); - } - if (model.Root.Children[0] != hips) - { - throw new Exception(); - } - hips.Translation -= new Vector3(0, minY, 0); - - // normalize scale - var pos = hips.Translation; - var factor = 1.0f; - if (pos.Y != 0) - { - factor = 1.0f / pos.Y; - foreach (var x in hips.Traverse()) - { - x.LocalTranslation *= factor; - } - hips.Translation = new Vector3(pos.X, 1.0f, pos.Z); - } - - // animation - model.Animations.Add(LoadAnimation(name, bvh, model, factor)); - - // add origin - var origin = new Node("origin"); - origin.Add(model.Root.Children[0]); - model.Nodes.Add(origin); - model.Root.Add(origin); - - return model; - } - - public static void CreateBoxMan(this Model model) - { - // skin - var skin = new Skin(); - skin.Joints.AddRange(model.Nodes); - skin.CalcInverseMatrices(); - - // mesh - var group = new MeshGroup("box-man") - { - Skin = skin, - }; - var builder = new MeshBuilder(); - builder.Build(model.Nodes); - group.Meshes.Add(builder.CreateMesh()); - model.MeshGroups.Add(group); - - // node - var meshNode = new Node("mesh"); - meshNode.MeshGroup = group; - model.Nodes.Add(meshNode); - model.Root.Add(meshNode); - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForBvh.cs.meta b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForBvh.cs.meta deleted file mode 100644 index cf83bf98c..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForBvh.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 13b0cacd23e61e1468b9b9891e0e6656 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForCoordinates.cs b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForCoordinates.cs index 8b54c97fc..304c8155f 100644 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForCoordinates.cs +++ b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForCoordinates.cs @@ -217,51 +217,6 @@ namespace VrmLib { // TODO: } - - if (model.Vrm != null) - { - if (!ignoreVrm) - { - // LookAt - if (model.Vrm.LookAt != null) - { - model.Vrm.LookAt.OffsetFromHeadBone = reverser.ReverseVector3(model.Vrm.LookAt.OffsetFromHeadBone); - } - - // SpringBone - if (model.Vrm.SpringBone != null) - { - foreach (var b in model.Vrm.SpringBone.Springs) - { - foreach (var c in b.Colliders) - { - for (int i = 0; i < c.Colliders.Count; ++i) - { - var s = c.Colliders[i]; - switch (s.ColliderType) - { - case VrmSpringBoneColliderTypes.Sphere: - c.Colliders[i] = VrmSpringBoneCollider.CreateSphere(reverser.ReverseVector3(s.Offset), s.Radius); - break; - - case VrmSpringBoneColliderTypes.Capsule: - c.Colliders[i] = VrmSpringBoneCollider.CreateCapsule(reverser.ReverseVector3(s.Offset), s.Radius, reverser.ReverseVector3(s.CapsuleTail)); - break; - - default: - throw new NotImplementedException(); - } - } - } - - foreach (var j in b.Joints) - { - j.GravityDir = reverser.ReverseVector3(j.GravityDir); - } - } - } - } - } } static void FlipTriangle(SpanLike indices) diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForHumanoid.cs b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForHumanoid.cs deleted file mode 100644 index b46dee7d1..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForHumanoid.cs +++ /dev/null @@ -1,193 +0,0 @@ -using System; -using System.Linq; -using System.Numerics; - -namespace VrmLib -{ - public static class ModelExtensionsForHumanoid - { - static ValueTuple GetUpperLower(Node root) - { - var legL = root.Traverse().FirstOrDefault(x => x.HumanoidBone == HumanoidBones.leftUpperLeg); - var legR = root.Traverse().FirstOrDefault(x => x.HumanoidBone == HumanoidBones.rightUpperLeg); - var head = root.Traverse().FirstOrDefault(x => x.HumanoidBone == HumanoidBones.head); - - var parentL = legL.Parent; - var parentR = legR.Parent; - if (parentL != parentR) - { - throw new Exception("different leftLeg parent and rightLeg parent"); - } - var lower = parentL; - - var upperAncestors = head.Ancestors().ToList(); - if (upperAncestors.Any(x => x == lower)) - { - throw new Exception("lower is ancestor of head"); - } - - var lowerAncestors = legL.Ancestors().ToList(); - - while (true) - { - if (upperAncestors.Last() != lowerAncestors.Last()) - { - break; - } - upperAncestors.RemoveAt(upperAncestors.Count - 1); - lowerAncestors.RemoveAt(lowerAncestors.Count - 1); - } - - return (upperAncestors.Last(), lowerAncestors.Last()); - } - - /// - /// - /// root - /// upper - /// lower - /// legL - /// legR - /// - /// ↓ - /// - /// ①上半身をchestにする例 - /// - /// root(hips) - /// legL - /// legR - /// lower(spine: 上下反転するため頭の位置が変わる) - /// upper(chest) - /// - /// ②上半身をspineにする例もありえる。その場合は、下半身とその親を近接させて - /// 下半身にはhumanoidボーンを割り当てない(hipsとみなす) - /// - /// root(hips) - /// legL - /// legR - /// lower(上下反転するため頭の位置が変わる) - /// upper(spine) - /// - /// ③もしくは下半身をhipsに繰り上げる - /// - /// lower(hips: 上下反転するため頭の位置が変わる) - /// legL - /// legR - /// upper(spine) - /// - /// - public static string FixInvertedPelvis(this Model model) - { - var (upper, lower) = GetUpperLower(model.Root); - if (upper == null) - { - return "FixInvertedPelvis: upper not found. this is not humanoid ? do nothing"; - } - if (lower == null) - { - return "FixInvertedPelvis: lower not found. this is model's pelvis is not inverted. do nothing"; - } - - // found lower. fix inverted pelvis... - - var hips = model.Root.FindBone(HumanoidBones.hips); - { - hips.HumanoidBone = null; - } - var spine = model.Root.FindBone(HumanoidBones.spine); - { - spine.HumanoidBone = null; - } - var chest = model.Root.FindBone(HumanoidBones.chest); - if (chest != null) - { - chest.HumanoidBone = null; - } - var legL = model.Root.FindBone(HumanoidBones.leftUpperLeg); - var legR = model.Root.FindBone(HumanoidBones.rightUpperLeg); - - // [chest] - // 上半身を下半身の子にしてchestとなす - lower.Add(upper); - upper.HumanoidBone = HumanoidBones.chest; - - // [hips] - // lowerの親をhipsとして両足の間に配置する - var newHips = lower.Parent; - newHips.Translation = new Vector3(0, legL.Translation.Y, legL.Translation.Z); - newHips.HumanoidBone = HumanoidBones.hips; - - // [spine] - // 下半身をspineとして - lower.HumanoidBone = HumanoidBones.spine; - // hips と chest の中間に配置する - lower.Translation = (upper.Translation + hips.Translation) * 0.5f; - - // [legs] - // 足の親を下半身からrootに変える - hips.Add(legL); - hips.Add(legR); - - return $"FixInvertedPelvis: lower: {lower.Name}"; - } - - static void StringBuilder(System.Text.StringBuilder sb, Node n, string indent = "") - { - sb.Append($"{indent}{n}\n"); - - foreach (var child in n.Children) - { - StringBuilder(sb, child, indent + " "); - } - } - - public static string HumanoidBoneEstimate(this Model model) - { - var sb = new System.Text.StringBuilder(); - sb.Append("HumanoidBoneEstimate: "); - - // estimate skeleton - var skeleton = SkeletonEstimator.Detect(model.Root); - if (skeleton == null) - { - return "fail to estimate skeleton"; - } - - // rename bone - foreach (var kv in skeleton) - { - kv.Value.Name = kv.Key.ToString(); - } - - if (model.Vrm == null) - { - sb.Append("add vrm humanoid"); - model.Vrm = new Vrm(new Meta - { - }, "UniVRM-0.51.0", "0.0"); - } - else - { - - } - - StringBuilder(sb, skeleton[HumanoidBones.hips]); - - foreach (var skin in model.Skins) - { - if (skin.Root == null) - { - skin.Root = (Node)skeleton[HumanoidBones.hips].Parent; - sb.Append($"{skin}: set {skin.Root}\n"); - } - else - { - sb.Append($"{skin}: {skin.Root}\n"); - } - } - - return sb.ToString(); ; - } - - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForHumanoid.cs.meta b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForHumanoid.cs.meta deleted file mode 100644 index a935ab25a..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForHumanoid.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e290d6e2d1cfe684488ad5504f0ce8dc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForSingleMesh.cs b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForSingleMesh.cs deleted file mode 100644 index ea4d782f9..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForSingleMesh.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System.Linq; - -namespace VrmLib -{ - public static class ModelExtensionsForSingleMesh - { - /// - /// 各ノードのスキニングで使用されている回数 - /// - public static int[] GetNodeSkinUseCount(Model model) - { - // create new skin - var useCountList = new int[model.Nodes.Count]; - foreach (var n in model.Root.Traverse().Skip(1)) - { - var g = n.MeshGroup; - if (g == null) - { - continue; - } - - if (g.Skin == null) - { - // Skin無し。そのMeshに乗る - var index = model.Nodes.IndexOf(n); - ++useCountList[index]; - } - else - { - // Skinあり。VertexBufferの JOINT_0 と WEIGHT_0 を見る - var skinJoints = g.Skin.Joints; - foreach (var m in g.Meshes) - { - var joints = m.VertexBuffer.GetOrCreateJoints(); - var weights = m.VertexBuffer.GetOrCreateWeights(); - for (int i = 0; i < joints.Length; ++i) - { - var j = joints[i]; - var w = weights[i]; - if (w.X > 0) - { - var node = skinJoints[j.Joint0]; - var index = model.Nodes.IndexOf(node); - ++useCountList[index]; - } - if (w.Y > 0) - { - var node = skinJoints[j.Joint1]; - var index = model.Nodes.IndexOf(node); - ++useCountList[index]; - } - if (w.Z > 0) - { - var node = skinJoints[j.Joint2]; - var index = model.Nodes.IndexOf(node); - ++useCountList[index]; - } - if (w.W > 0) - { - var node = skinJoints[j.Joint3]; - var index = model.Nodes.IndexOf(node); - ++useCountList[index]; - } - } - } - } - } - return useCountList; - } - - /// - /// Integrate meshes to a single mesh - /// - /// - /// - public static MeshGroup CreateSingleMesh(this Model model, string name) - { - // new mesh to store result - var meshGroup = new MeshGroup(name); - var mesh = new Mesh - { - VertexBuffer = new VertexBuffer() - }; - meshGroup.Meshes.Add(mesh); - - var useCountList = GetNodeSkinUseCount(model); - - // new Skin. - // Joints has include all joint - meshGroup.Skin = new Skin(); - for (int i = 0; i < useCountList.Length; ++i) - { - if (useCountList[i] > 0) - { - // add joint that has bone weight - meshGroup.Skin.Joints.Add(model.Nodes[i]); - } - } - model.Skins.Clear(); - model.Skins.Add(meshGroup.Skin); - - // concatenate all mesh - foreach (var node in model.Root.Traverse().Skip(1)) - { - var g = node.MeshGroup; - if (g != null) - { - foreach (var m in g.Meshes) - { - if (g.Skin != null && m.VertexBuffer.Joints != null && m.VertexBuffer.Weights != null) - { - var jointIndexMap = g.Skin.Joints.Select(x => meshGroup.Skin.Joints.IndexOf(x)).ToArray(); - mesh.Append(m.VertexBuffer, m.IndexBuffer, m.Submeshes, m.MorphTargets, jointIndexMap); - } - else - { - var rootIndex = meshGroup.Skin.Joints.IndexOf(node); - mesh.Append(m.VertexBuffer, m.IndexBuffer, m.Submeshes, m.MorphTargets, null, rootIndex, node.Matrix); - } - } - } - } - - foreach (var target in mesh.MorphTargets) - { - target.VertexBuffer.Resize(mesh.VertexBuffer.Count); - } - - return meshGroup; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForSingleMesh.cs.meta b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForSingleMesh.cs.meta deleted file mode 100644 index b9223cc94..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForSingleMesh.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ff27373084460f24b8866d4853a9acda -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForValidation.cs b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForValidation.cs deleted file mode 100644 index 4664e0e43..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForValidation.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Linq; - -namespace VrmLib -{ - public static class ModelExtensionsForValidation - { - public static void Validate(this Model model, Node node, string message) - { - if (node is null) - { - throw new ArgumentNullException(message); - } - if (!model.Nodes.Contains(node)) - { - throw new ArgumentException($"{message}: node found in nodes"); - } - } - - public static void Validate(this Model model) - { - foreach (var node in model.Root.Traverse().Skip(1)) - { - model.Validate(node, "nodes must Contains node"); - } - - foreach (var skin in model.Skins) - { - foreach (var joint in skin.Joints) - { - model.Validate(joint, "nodes must Contatins joint"); - } - } - - if (model.Vrm != null) - { - if (model.Vrm.ExpressionManager != null) - { - foreach (var b in model.Vrm.ExpressionManager.ExpressionList) - { - foreach (var v in b.MorphTargetBinds) - { - model.Validate(v.Node, "MorphTargetBindValue.Node is null"); - } - } - } - - if (model.Vrm.FirstPerson != null) - { - foreach (var a in model.Vrm.FirstPerson.Annotations) - { - model.Validate(a.Node, "FirstPersonMeshAnnotation.Node is null"); - } - } - - var humanDict = model.Root.Traverse() - .Where(x => x.HumanoidBone.HasValue) - .ToDictionary(x => x.HumanoidBone.Value, x => x); - - foreach (var required in new[]{ - HumanoidBones.hips, - }) - { - if (!humanDict.ContainsKey(required)) - { - throw new Exception($"no {required}"); - } - } - } - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForValidation.cs.meta b/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForValidation.cs.meta deleted file mode 100644 index b2ad6bb8e..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelExtensionsForValidation.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e7f73e8a96ec0774dadaa1f526c80210 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/ModelModifier.cs b/Assets/VRM10/vrmlib/Runtime/ModelModifier.cs index b349d755b..9fa7f1363 100644 --- a/Assets/VRM10/vrmlib/Runtime/ModelModifier.cs +++ b/Assets/VRM10/vrmlib/Runtime/ModelModifier.cs @@ -82,34 +82,6 @@ namespace VrmLib } Model.Nodes.Remove(remove); - - if (Model.Vrm != null) - { - if (Model.Vrm.ExpressionManager != null) - { - foreach (var b in Model.Vrm.ExpressionManager.ExpressionList) - { - foreach (var v in b.MorphTargetBinds) - { - if (v.Node == remove) - { - throw new NotImplementedException("referenced from morphtargetbind"); - } - } - } - } - - if (Model.Vrm.FirstPerson != null) - { - foreach (var a in Model.Vrm.FirstPerson.Annotations) - { - if (a.Node == remove) - { - throw new NotImplementedException("referenced from firstPerson"); - } - } - } - } } /// @@ -161,54 +133,8 @@ namespace VrmLib } Model.Nodes.Add(dst); - // fix VRM - if (Model.Vrm != null) - { - // replace: VrmMorphTargetBind.Mesh - if (Model.Vrm.ExpressionManager != null) - { - foreach (var x in Model.Vrm.ExpressionManager.ExpressionList) - { - for (int i = 0; i < x.MorphTargetBinds.Count; ++i) - { - var v = x.MorphTargetBinds[i]; - if (src == v.Node) - { - v.Node = dst; - } - } - } - } - - // replace: VrmFirstPerson.MeshAnnotations - Model.Vrm.FirstPerson.Annotations.RemoveAll(x => x.Node == src); - if (!Model.Vrm.FirstPerson.Annotations.Any(x => x.Node == dst)) - { - Model.Vrm.FirstPerson.Annotations.Add( - new FirstPersonMeshAnnotation(dst, FirstPersonMeshType.Auto)); - } - } - // TODO: SpringBone } #endregion - - public void MaterialReplace(Material src, Material dst) - { - // replace material of submesh - foreach (var group in Model.MeshGroups) - { - foreach (var mesh in group.Meshes) - { - foreach (var submesh in mesh.Submeshes) - { - if (submesh.Material == src) - { - submesh.Material = dst; - } - } - } - } - } } } \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/ModelModifierExtensions.cs b/Assets/VRM10/vrmlib/Runtime/ModelModifierExtensions.cs deleted file mode 100644 index a65745823..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelModifierExtensions.cs +++ /dev/null @@ -1,365 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; - -namespace VrmLib -{ - public static class ModelModifierExtensions - { - public static bool TryAdd(this IDictionary dict, TKey key, TValue addValue) - { - bool canAdd = !dict.ContainsKey(key); - - if (canAdd) - dict.Add(key, addValue); - - return canAdd; - } - - public static TValue GetValueOrDefault(this System.Collections.Generic.IReadOnlyDictionary dictionary, TKey key) - { - if (dictionary.TryGetValue(key, out TValue value)) - { - return value; - } - else - { - return default; - } - } - - static void ReplaceMorphTargetAnimationNode(IEnumerable animations, Node dst) - { - foreach (var animation in animations) - { - var dstAnimation = animation.GetOrCreateNodeAnimation(dst); - foreach (var (node, nodeAnimation) in animation.NodeMap) - { - if (nodeAnimation.Curves.TryGetValue(AnimationPathType.Weights, out CurveSampler curve)) - { - // remove - nodeAnimation.Curves.Remove(AnimationPathType.Weights); - - // add - if (!dstAnimation.Curves.TryAdd(AnimationPathType.Weights, curve)) - { - Console.Error.WriteLine($"already exists. skip: {node.Name}: {nodeAnimation}"); - } - } - } - } - } - - /// Expression - /// FirstPersonの置き換え - public static void MeshNodeReplace(this ModelModifier modifier, Node src, Node dst) - { - var vrm = modifier.Model.Vrm; - if (vrm is null) - { - return; - } - - if (vrm.ExpressionManager != null) - { - foreach (var b in vrm.ExpressionManager.ExpressionList) - { - foreach (var v in b.MorphTargetBinds) - { - if (v.Node == src) - { - v.Node = dst; - } - } - } - } - if (vrm.FirstPerson != null) - { - foreach (var a in vrm.FirstPerson.Annotations) - { - if (a.Node == src) - { - a.Node = dst; - } - } - } - } - - public static string SingleMesh(this ModelModifier modifier, string name) - { - var count = modifier.Model.MeshGroups.Sum(x => x.Meshes.Count); - var meshes = modifier.Model.Root.Traverse() - .Select(x => x.MeshGroup) - .Where(x => x != null) - .Select(x => $"[{x.Name}]") - .ToArray(); - if (meshes.Length == 0) - { - return "SingleMesh: no mesh. do nothing"; - } - if (meshes.Length <= 1) - { - return "SingleMesh: one mesh. do nothing"; - } - - var mesh = modifier.Model.CreateSingleMesh(name); - var meshNode = new Node(mesh.Name) - { - MeshGroup = mesh, - }; - mesh.Skin.Root = meshNode; - - // fix bone weight (0, x, 0, 0) => (x, 0, 0, 0) - // mesh.Meshes[0].VertexBuffer.FixBoneWeight(); - - // replace morphAnimation reference - ReplaceMorphTargetAnimationNode(modifier.Model.Animations, meshNode); - - // update Model - foreach (var x in modifier.Model.MeshGroups.ToArray()) - { - modifier.MeshReplace(x, mesh); - } - foreach (var node in modifier.Model.Nodes) - { - if (node.MeshGroup != null) - { - node.MeshGroup = null; - modifier.MeshNodeReplace(node, meshNode); - } - - } - modifier.NodeAdd(meshNode); - - var names = string.Join("", meshes); - // return $"SingleMesh: {names}"; - return $"SingleMesh: {count} => {modifier.Model.MeshGroups.Sum(x => x.Meshes.Count)}"; - } - - public static void SepareteByMorphTarget(this ModelModifier modifier, MeshGroup mesh) - { - var (with, without) = mesh.SepareteByMorphTarget(); - var list = new List(); - if (with != null) list.Add(with); - if (without != null) list.Add(without); - - // 分割モデルで置き換え - if (list.Any()) - { - modifier.MeshReplace(mesh, list[0]); - // rename node - modifier.Model.Nodes.Find(x => x.MeshGroup == list[0]).Name = list[0].Name; - } - - if (list.Count > 1) - { - // morph無しと有り両方存在する場合に2つ目を追加する - modifier.MeshReplace(null, list[1]); - modifier.NodeAdd(new Node(list[1].Name) - { - MeshGroup = list[1] - }); - } - } - - public static void SepareteByHeadBone(this ModelModifier modifier, MeshGroup mesh, HashSet boneIndices) - { - var (with, without) = mesh.SepareteByHeadBone(boneIndices); - var list = new List(); - if (with != null) list.Add(with); - if (without != null) list.Add(without); - - // 分割モデルで置き換え - if (list.Any()) - { - modifier.MeshReplace(mesh, list[0]); - // rename node - modifier.Model.Nodes.Find(x => x.MeshGroup == list[0]).Name = list[0].Name; - } - - if (list.Count > 1) - { - // 頭と胴体で分割後2つ以上ある場合、2つ目を追加する - modifier.MeshReplace(null, list[1]); - modifier.NodeAdd(new Node(list[1].Name) - { - MeshGroup = list[1] - }); - } - } - - public static string NodeReduce(this ModelModifier modifier) - { - var count = modifier.Model.Nodes.Count; - var removeNames = new List(); - - // ノードを削除する - foreach (var node in modifier.Model.GetRemoveNodes()) - { - modifier.NodeRemove(node); - removeNames.Add($"[{node.Name}]"); - foreach (var skin in modifier.Model.Skins) - { - var index = skin.Joints.IndexOf(node); - if (index != -1) - { - // remove - skin.Joints[index] = null; - } - } - } - - // 削除されたノードを参照する頂点バッファを修正する - foreach (var meshGroup in modifier.Model.MeshGroups) - { - var skin = meshGroup.Skin; - if (skin != null && skin.Joints.Contains(null)) - { - foreach (var mesh in meshGroup.Meshes) - { - skin.FixBoneWeight(mesh.VertexBuffer.Joints, mesh.VertexBuffer.Weights); - } - } - } - - var joined = string.Join("", removeNames); - - return $"NodeReduce: {count} => {modifier.Model.Nodes.Count}"; - // return $"NodeReduce: {joined}"; - } - - public static string SkinningBake(this ModelModifier modifier) - { - foreach (var node in modifier.Model.Nodes) - { - var meshGroup = node.MeshGroup; - if (meshGroup == null) - { - continue; - } - - if (meshGroup.Skin != null) - { - // 正規化されていれば1つしかない - // されていないと Primitive の数だけある - foreach (var mesh in meshGroup.Meshes) - { - { - // Skinningの出力先を自身にすることでBakeする - meshGroup.Skin.Skinning(mesh.VertexBuffer); - } - - // morphのPositionは相対値が入っているはずなので、手を加えない(正規化されていない場合、二重に補正が掛かる) - /* - foreach (var morph in mesh.MorphTargets) - { - if (morph.VertexBuffer.Positions != null) - { - meshGroup.Skin.Skinning(morph.VertexBuffer); - } - } - */ - } - - meshGroup.Skin.Root = null; - meshGroup.Skin.InverseMatrices = null; - } - else - { - foreach (var mesh in meshGroup.Meshes) - { - // nodeに対して疑似的にSkinningする - // 回転と拡縮を適用し位置は適用しない - mesh.ApplyRotationAndScaling(node.Matrix); - } - } - } - - // 回転・拡縮を除去する - modifier.Model.ApplyRotationAndScale(); - - // inverse matrix の再計算 - foreach (var node in modifier.Model.Nodes) - { - var meshGroup = node.MeshGroup; - if (meshGroup == null) - { - continue; - } - - foreach (var mesh in meshGroup.Meshes) - { - if (meshGroup.Skin != null) - { - meshGroup.Skin.CalcInverseMatrices(); - } - } - } - - return "SkinningBake"; - } - - public static string CloneSharedMesh(this ModelModifier modifier) - { - Dictionary m_useMap = new Dictionary(); - - var cloned = new List(); - - foreach (var node in modifier.Model.Nodes) - { - if (node.MeshGroup == null) - { - continue; - } - - var n = m_useMap.GetValueOrDefault(node.MeshGroup); - if (n > 0) - { - // copy - node.MeshGroup = node.MeshGroup.Clone(); - cloned.Add($"[{node.MeshGroup.Name}]"); - } - m_useMap[node.MeshGroup] = n + 1; - } - - if (!cloned.Any()) - { - return "CloneSharedMesh: no shared mesh. do nothing"; - } - else - { - var joined = string.Join("", cloned); - return $"CloneSharedMesh: copy {joined}"; - } - } - - public static string MaterialIntegrate(this ModelModifier modifier) - { - var sb = new System.Text.StringBuilder(); - var materials = new List(); - - foreach (var material in modifier.Model.Materials.ToArray()) - { - var found = materials.FirstOrDefault(x => x.CanIntegrate(material)); - if (found != null) - { - // merge - modifier.MaterialReplace(material, found); - } - else - { - // add - materials.Add(material); - } - } - - sb.Append($"MaterialIntegrate: {modifier.Model.Materials.Count} => {materials.Count}"); - - modifier.Model.Materials.Clear(); - modifier.Model.Materials.AddRange(materials); - - return sb.ToString(); - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/ModelModifierExtensions.cs.meta b/Assets/VRM10/vrmlib/Runtime/ModelModifierExtensions.cs.meta deleted file mode 100644 index b5a46a790..000000000 --- a/Assets/VRM10/vrmlib/Runtime/ModelModifierExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 54fd566dc84b51643886ce8858a671db -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm.meta b/Assets/VRM10/vrmlib/Runtime/Vrm.meta deleted file mode 100644 index 26ebf0757..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 1a5f2134b543a044fb0396a2655abf72 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/Expression.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/Expression.cs deleted file mode 100644 index fd76d338e..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/Expression.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; - -namespace VrmLib -{ - public enum ExpressionOverrideType - { - None, - Block, - Blend, - } - - public class Expression - { - public readonly ExpressionPreset Preset; - public readonly string Name; - - public bool IsBinary; - - public ExpressionOverrideType OverrideBlink; - public ExpressionOverrideType OverrideLookAt; - public ExpressionOverrideType OverrideMouth; - - public readonly List MorphTargetBinds = new List(); - - public readonly List MaterialColorBinds = new List(); - - public readonly List TextureTransformBinds = new List(); - - public void CleanupUVScaleOffset() - { - // ST_S, ST_T を統合する - var count = TextureTransformBinds.Count; - var map = new Dictionary(); - foreach (var uv in TextureTransformBinds.OrderBy(uv => uv.Material.Name).Distinct()) - { - if (!map.TryGetValue(uv.Material, out TextureTransformBind value)) - { - value = new TextureTransformBind(uv.Material, Vector2.One, Vector2.Zero); - } - map[uv.Material] = value.Merge(uv); - } - TextureTransformBinds.Clear(); - foreach (var kv in map) - { - TextureTransformBinds.Add(new TextureTransformBind(kv.Key, - kv.Value.Scale, - kv.Value.Offset)); - } - // Console.WriteLine($"MergeUVScaleOffset: {count} => {UVScaleOffsetValues.Count}"); - } - - public Expression(ExpressionPreset preset, string name, bool isBinary) - { - Preset = preset; - Name = name; - IsBinary = isBinary; - } - - public override string ToString() - { - return Preset.ToString(); - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/Expression.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/Expression.cs.meta deleted file mode 100644 index afba40f28..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/Expression.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e4a3ac008751679488d4e9263bc80d45 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionManager.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionManager.cs deleted file mode 100644 index eafaffdb9..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionManager.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Generic; - -namespace VrmLib -{ - public class ExpressionManager - { - public readonly List ExpressionList = new List(); - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionManager.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionManager.cs.meta deleted file mode 100644 index 4fc228183..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4cf8de25227692f408aed2703ff27c6c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionPreset.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionPreset.cs deleted file mode 100644 index e15615d89..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionPreset.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace VrmLib -{ - public class ExpressionPresetMigrationStringAttribute : System.Attribute - { - /// - /// vrm-0.X での名前 - /// - public string Vrm0; - - public ExpressionPresetMigrationStringAttribute(string name) - { - Vrm0 = name; - } - } - - /// - /// VRM-1.0 順に並べ替え。 - /// - /// VRM-0.X とは変換表が必用デス - /// - public enum ExpressionPreset - { - [ExpressionPresetMigrationString("unknown")] - Custom, - // 喜怒哀楽驚 - [ExpressionPresetMigrationString("joy")] - Happy, - [ExpressionPresetMigrationString("angry")] - Angry, - [ExpressionPresetMigrationString("sorrow")] - Sad, - [ExpressionPresetMigrationString("fun")] - Relaxed, - [ExpressionPresetMigrationString(null)] - Surprised, - // Procedural(LipSync) - [ExpressionPresetMigrationString("a")] - Aa, - [ExpressionPresetMigrationString("i")] - Ih, - [ExpressionPresetMigrationString("u")] - Ou, - [ExpressionPresetMigrationString("e")] - Ee, - [ExpressionPresetMigrationString("o")] - Oh, - // Procedural(Blink) - [ExpressionPresetMigrationString("blink")] - Blink, - [ExpressionPresetMigrationString("blink_l")] - BlinkLeft, - [ExpressionPresetMigrationString("blink_r")] - BlinkRight, - // Procedural(LookAt) - [ExpressionPresetMigrationString("lookup")] - LookUp, - [ExpressionPresetMigrationString("lookdown")] - LookDown, - [ExpressionPresetMigrationString("lookleft")] - LookLeft, - [ExpressionPresetMigrationString("lookright")] - LookRight, - // other - [ExpressionPresetMigrationString("neutral")] - Neutral, - } - - public static class ExpressionPresetMigration - { - static readonly Dictionary s_map = GetValues().ToDictionary(x => x.Key, x => x.Value); - - static IEnumerable> GetValues() - { - var t = typeof(ExpressionPreset); - foreach (var x in EnumUtil.Values()) - { - var mi = t.GetMember(x.ToString()).FirstOrDefault(m => m.DeclaringType == t); - var attr = mi.GetCustomAttributes(typeof(ExpressionPresetMigrationStringAttribute), true).First(); - if (attr is ExpressionPresetMigrationStringAttribute vrmAttr && !string.IsNullOrEmpty(vrmAttr.Vrm0)) - { - yield return new KeyValuePair(vrmAttr.Vrm0, x); - } - } - } - - public static ExpressionPreset FromVrm0String(string src) - { - if (s_map.TryGetValue(src, out ExpressionPreset preset)) - { - return preset; - } - else - { - return ExpressionPreset.Custom; - } - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionPreset.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionPreset.cs.meta deleted file mode 100644 index b819b9722..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/ExpressionPreset.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ebb92c36b2be88c4c835c55346488158 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/FirstPerson.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/FirstPerson.cs deleted file mode 100644 index 9cd7cd5f6..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/FirstPerson.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Collections.Generic; -using System.Numerics; - -namespace VrmLib -{ - public enum FirstPersonMeshType - { - Auto, // Create headlessModel - Both, // Default layer - ThirdPersonOnly, - FirstPersonOnly, - } - - public class FirstPersonMeshAnnotation - { - public Node Node; - - public readonly FirstPersonMeshType FirstPersonFlag; - - public FirstPersonMeshAnnotation(Node node, FirstPersonMeshType flag) - { - Node = node; - FirstPersonFlag = flag; - } - } - - public class FirstPerson - { - public readonly List Annotations = new List(); - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/FirstPerson.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/FirstPerson.cs.meta deleted file mode 100644 index 7ec89205e..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/FirstPerson.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 757db113e51e3b14b970eaa4301738d3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/IAvatarPermission.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/IAvatarPermission.cs deleted file mode 100644 index 7146056a9..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/IAvatarPermission.cs +++ /dev/null @@ -1,72 +0,0 @@ -namespace VrmLib -{ - public enum AvatarUsageType - { - OnlyAuthor, - ExplicitlyLicensedPerson, - Everyone, - } - - public enum CommercialUsageType - { - PersonalNonCommercialNonProfit, - PersonalNonCommercialProfit, - PersonalCommercial, - Corporation, - } - - public interface IAvatarPermission - { - AvatarUsageType AvatarUsage { get; } - bool IsAllowedViolentUsage { get; } - bool IsAllowedSexualUsage { get; } - - // 1.0 removed - bool IsAllowedCommercialUsage { get; } - - // 1.0 added - CommercialUsageType CommercialUsage { get; } - - // 1.0 added - bool IsAllowedPoliticalOrReligiousUsage { get; } - - // 1.0 added - bool IsAllowedGameUsage { get; } - - string OtherPermissionUrl { get; } - } - - /// - /// 1.0向け - /// - public class AvatarPermission : IAvatarPermission - { - public AvatarUsageType AvatarUsage { get; set; } - - public bool IsAllowedViolentUsage { get; set; } - - public bool IsAllowedSexualUsage { get; set; } - - public bool IsAllowedCommercialUsage - { - get - { - switch (CommercialUsage) - { - case CommercialUsageType.Corporation: - case CommercialUsageType.PersonalCommercial: - return true; - } - return false; - } - } - - public CommercialUsageType CommercialUsage { get; set; } - - public bool IsAllowedPoliticalOrReligiousUsage { get; set; } - - public bool IsAllowedGameUsage { get; set; } - - public string OtherPermissionUrl { get; set; } = ""; - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/IAvatarPermission.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/IAvatarPermission.cs.meta deleted file mode 100644 index d2629a7e9..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/IAvatarPermission.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2254356479156e24b8da9a4310c126aa -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/IRedistributionLicense.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/IRedistributionLicense.cs deleted file mode 100644 index 0bfb223d7..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/IRedistributionLicense.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; - -namespace VrmLib -{ - public enum DistributionLicenseType - { - Redistribution_Prohibited, - CC0, - CC_BY, - CC_BY_NC, - CC_BY_SA, - CC_BY_NC_SA, - CC_BY_ND, - CC_BY_NC_ND, - Other - } - - public enum CreditNotationType - { - Required, - Unnecessary, - Abandoned, - } - - public enum ModificationLicenseType - { - Prohibited, - Inherited, - NotInherited - } - - public interface IRedistributionLicense - { - // 1.0 removed - DistributionLicenseType License { get; } - - CreditNotationType CreditNotation { get; } - bool IsAllowRedistribution { get; } - string OtherLicenseUrl { get; } - - ModificationLicenseType ModificationLicense { get; } - } - - /// 1.0 向け - public class RedistributionLicense : IRedistributionLicense - { - public DistributionLicenseType License - { - get => DistributionLicenseType.Redistribution_Prohibited; - } - - public CreditNotationType CreditNotation { get; set; } - - public bool IsAllowRedistribution { get; set; } - - public ModificationLicenseType ModificationLicense { get; set; } - - public string OtherLicenseUrl { get; set; } = ""; - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/IRedistributionLicense.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/IRedistributionLicense.cs.meta deleted file mode 100644 index 21334d0ef..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/IRedistributionLicense.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 275466b758478f442a575a611fd92faf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/LookAt.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/LookAt.cs deleted file mode 100644 index 1a0897e49..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/LookAt.cs +++ /dev/null @@ -1,41 +0,0 @@ - - -using System.Numerics; - -namespace VrmLib -{ - public enum LookAtType - { - Bone, - Expression, - } - - public class LookAtRangeMap - { - /// - /// Yaw, Pitch 各を 0 ~ InputMaxValue で clamp する - /// - public float InputMaxValue = 90.0f; - - /// - /// 0 ~ InputMaxValue を 0 ~ 1 に map してから乗算する - /// - public float OutputScaling = 10.0f; - - /// 4つでひとつのキー。最低8 - public float[] Curve; - } - - public class LookAt - { - public Vector3 OffsetFromHeadBone; - - public LookAtType LookAtType; - - public LookAtRangeMap HorizontalInner = new LookAtRangeMap(); - public LookAtRangeMap HorizontalOuter = new LookAtRangeMap(); - public LookAtRangeMap VerticalUp = new LookAtRangeMap(); - public LookAtRangeMap VerticalDown = new LookAtRangeMap(); - - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/LookAt.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/LookAt.cs.meta deleted file mode 100644 index 394eaa7c0..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/LookAt.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2023bcdc0e48f3a4398c6db4ef343de4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MToonMaterial.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/MToonMaterial.cs deleted file mode 100644 index 90ab95f21..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MToonMaterial.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; - -namespace VrmLib -{ - public class MToonMaterial : UnlitMaterial - { - public override LinearColor BaseColorFactor - { - get => Definition.Color.LitColor; - set => Definition.Color.LitColor = value; - } - - public override TextureInfo BaseColorTexture - { - get => Definition.Color.LitMultiplyTexture; - set => Definition.Color.LitMultiplyTexture = value; - } - - public override AlphaModeType AlphaMode - { - get - { - switch (Definition.Rendering.RenderMode) - { - case MToon.RenderMode.Opaque: return AlphaModeType.OPAQUE; - case MToon.RenderMode.Cutout: return AlphaModeType.MASK; - case MToon.RenderMode.Transparent: return AlphaModeType.BLEND; - case MToon.RenderMode.TransparentWithZWrite: return AlphaModeType.BLEND_ZWRITE; - default: throw new NotImplementedException(); - } - } - set - { - switch (value) - { - case AlphaModeType.OPAQUE: Definition.Rendering.RenderMode = MToon.RenderMode.Opaque; break; - case AlphaModeType.MASK: Definition.Rendering.RenderMode = MToon.RenderMode.Cutout; break; - case AlphaModeType.BLEND: Definition.Rendering.RenderMode = MToon.RenderMode.Transparent; break; - case AlphaModeType.BLEND_ZWRITE: Definition.Rendering.RenderMode = MToon.RenderMode.TransparentWithZWrite; break; - default: throw new NotImplementedException(); - } - } - } - - public override float AlphaCutoff - { - get => Definition.Color.CutoutThresholdValue; - set => Definition.Color.CutoutThresholdValue = value; - } - - public MToonMaterial(string name) : base(name) - { - } - - public new const string ExtensionName = "VRMC_materials_mtoon"; - - public override string ToString() - { - return $"[MTOON]{Name}"; - } - - public float _DebugMode; - public float _SrcBlend; - public float _DstBlend; - public float _ZWrite; - - public MToon.MToonDefinition Definition; - - public override bool CanIntegrate(Material _rhs) - { - var rhs = _rhs as MToonMaterial; - if (rhs == null) - { - return false; - } - - if (!Definition.Equals(rhs.Definition)) return false; - - return true; - } - - public const string MToonShaderName = "VRM/MToon"; - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MToonMaterial.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/MToonMaterial.cs.meta deleted file mode 100644 index 6cba80fcd..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MToonMaterial.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3f7171f053cf12643bddfdba3afe9e80 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindType.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindType.cs deleted file mode 100644 index 9640c07be..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindType.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace VrmLib -{ - public enum MaterialBindType - { - // /// float2: テクスチャーのUVの拡大率。UVでアクセスするテクスチャーすべてに適用される - // UvScale, - // /// float2: テクスチャーのUVのoffset。UVでアクセスするテクスチャーすべてに適用される - // UvOffset, - - // float4: Unlit, PBR, MToon - Color, - /// float4: PBR, MToon - EmissionColor, - /// float4: MToon - ShadeColor, - /// float4: MToon - RimColor, - /// float4: MToon - OutlineColor, - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindType.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindType.cs.meta deleted file mode 100644 index efafffd64..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindType.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c8ff16fe448a1ae4dbcb5bc28bc6efd5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindTypeExtensions.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindTypeExtensions.cs deleted file mode 100644 index a838f242f..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindTypeExtensions.cs +++ /dev/null @@ -1,229 +0,0 @@ -using System; - -namespace VrmLib -{ - public static class MaterialBindTypeExtensions - { - public const string UV_PROPERTY = "_MainTex_ST"; - public const string COLOR_PROPERTY = "_Color"; - public const string EMISSION_COLOR_PROPERTY = "_EmissionColor"; - public const string RIM_COLOR_PROPERTY = "_RimColor"; - public const string OUTLINE_COLOR_PROPERTY = "_OutlineColor"; - public const string SHADE_COLOR_PROPERTY = "_ShadeColor"; - - #region UnlitMaterial - static string _GetProperty(UnlitMaterial unlit, MaterialBindType bindType) - { - switch (bindType) - { - // case MaterialBindType.UvOffset: - // case MaterialBindType.UvScale: - // return UV_PROPERTY; - - case MaterialBindType.Color: - return COLOR_PROPERTY; - } - - throw new NotImplementedException(); - } - - static MaterialBindType _GetBindType(UnlitMaterial unlit, string property) - { - switch (property) - { - // case UV_PROPERTY: - // return MaterialBindType.UvOffset; - - case COLOR_PROPERTY: - return MaterialBindType.Color; - } - - throw new NotImplementedException(); - } - #endregion - - #region PBRMaterial - static string _GetProperty(PBRMaterial pbr, MaterialBindType bindType) - { - switch (bindType) - { - // case MaterialBindType.UvOffset: - // case MaterialBindType.UvScale: - // return UV_PROPERTY; - - case MaterialBindType.Color: - return COLOR_PROPERTY; - - case MaterialBindType.EmissionColor: - return EMISSION_COLOR_PROPERTY; - } - - throw new NotImplementedException(); - } - - static MaterialBindType _GetBindType(PBRMaterial pbr, string property) - { - switch (property) - { - // case UV_PROPERTY: - // return MaterialBindType.UvOffset; - - case COLOR_PROPERTY: - return MaterialBindType.Color; - - case EMISSION_COLOR_PROPERTY: - return MaterialBindType.EmissionColor; - } - - throw new NotImplementedException(); - } - #endregion - - #region MToon - static string _GetProperty(MToonMaterial mtoon, MaterialBindType bindType) - { - switch (bindType) - { - // case MaterialBindType.UvOffset: - // case MaterialBindType.UvScale: - // return UV_PROPERTY; - - case MaterialBindType.Color: - return COLOR_PROPERTY; - - case MaterialBindType.EmissionColor: - return EMISSION_COLOR_PROPERTY; - - case MaterialBindType.ShadeColor: - return SHADE_COLOR_PROPERTY; - - case MaterialBindType.RimColor: - return RIM_COLOR_PROPERTY; - - case MaterialBindType.OutlineColor: - return OUTLINE_COLOR_PROPERTY; - - } - - throw new NotImplementedException(); - } - - static MaterialBindType _GetBindType(this MToonMaterial mtoon, string property) - { - switch (property) - { - // case UV_PROPERTY: - // return MaterialBindType.UvOffset; - - case COLOR_PROPERTY: - return MaterialBindType.Color; - - case EMISSION_COLOR_PROPERTY: - return MaterialBindType.EmissionColor; - - case RIM_COLOR_PROPERTY: - return MaterialBindType.RimColor; - - case SHADE_COLOR_PROPERTY: - return MaterialBindType.ShadeColor; - - case OUTLINE_COLOR_PROPERTY: - return MaterialBindType.OutlineColor; - } - - throw new NotImplementedException(); - } - #endregion - - public static string GetProperty(this MaterialBindType bindType, Material material) - { - if (material is MToonMaterial mtoon) - { - return _GetProperty(mtoon, bindType); - } - - if (material is UnlitMaterial unlit) - { - return _GetProperty(unlit, bindType); - } - - if (material is PBRMaterial pbr) - { - return _GetProperty(pbr, bindType); - } - - throw new NotImplementedException(); - } - - public static MaterialBindType GetBindType(this Material material, string property) - { - if (material is MToonMaterial mtoon) - { - return _GetBindType(mtoon, property); - } - - if (material is UnlitMaterial unlit) - { - return _GetBindType(unlit, property); - } - - if (material is PBRMaterial pbr) - { - return _GetBindType(pbr, property); - } - - throw new NotImplementedException(); - } - - public static string GetProperty(MaterialBindType bindType) - { - switch (bindType) - { - // case MaterialBindType.UvOffset: - // case MaterialBindType.UvScale: - // return UV_PROPERTY; - - case MaterialBindType.Color: - return COLOR_PROPERTY; - - case MaterialBindType.EmissionColor: - return EMISSION_COLOR_PROPERTY; - - case MaterialBindType.ShadeColor: - return SHADE_COLOR_PROPERTY; - - case MaterialBindType.RimColor: - return RIM_COLOR_PROPERTY; - - case MaterialBindType.OutlineColor: - return OUTLINE_COLOR_PROPERTY; - - } - - throw new NotImplementedException(); - } - - public static MaterialBindType GetBindType(string property) - { - switch (property) - { - case COLOR_PROPERTY: - return MaterialBindType.Color; - - case EMISSION_COLOR_PROPERTY: - return MaterialBindType.EmissionColor; - - case RIM_COLOR_PROPERTY: - return MaterialBindType.RimColor; - - case SHADE_COLOR_PROPERTY: - return MaterialBindType.ShadeColor; - - case OUTLINE_COLOR_PROPERTY: - return MaterialBindType.OutlineColor; - } - - throw new NotImplementedException(); - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindTypeExtensions.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindTypeExtensions.cs.meta deleted file mode 100644 index 3178348dc..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialBindTypeExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a78413978cc956e4aac99418efc0d0f5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialColorBind.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialColorBind.cs deleted file mode 100644 index e9462c658..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialColorBind.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Numerics; - -namespace VrmLib -{ - public class MaterialColorBind - { - public readonly Material Material; - - /// - /// Material どのプロパティを変化させるのか - /// - public readonly MaterialBindType BindType; - - /// - /// Unity仕様の Property名 + Vector4 - /// - public KeyValuePair Property - { - get - { - // switch (BindType) - // { - // case MaterialBindType.UvScale: - // return new KeyValuePair( - // MaterialBindTypeExtensions.UV_PROPERTY, - // new Vector4(m_value.X, m_value.Y, 0, 0) - // ); - - // case MaterialBindType.UvOffset: - // return new KeyValuePair( - // MaterialBindTypeExtensions.UV_PROPERTY, - // new Vector4(1, 1, m_value.X, m_value.Y) - // ); - // } - - return new KeyValuePair(BindType.GetProperty(Material), m_value); - } - } - - readonly Vector4 m_value; - - // public MaterialBindValue(Material material, String property, Vector4 value) - // { - // Material = material; - // BindType = material.GetBindType(property); - // m_value = value; - // } - - public MaterialColorBind(Material material, MaterialBindType bindType, Vector4 value) - { - Material = material; - BindType = bindType; - m_value = value; - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialColorBind.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialColorBind.cs.meta deleted file mode 100644 index 1aea6187b..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MaterialColorBind.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ddd6cccfb542ae640aaaa61a45ffa805 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/Meta.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/Meta.cs deleted file mode 100644 index acc5d0837..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/Meta.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace VrmLib -{ - public class Meta - { - public string Name = ""; - - public string Version = ""; - - // 1.0 added - public string CopyrightInformation = ""; - - // 1.0 added - public List Authors = new List(); - - // backward compatibility - public string Author - { - get => Authors.FirstOrDefault(); - set - { - Authors.Clear(); - if (!string.IsNullOrEmpty(value)) - { - Authors.Add(value); - } - } - } - - public string ContactInformation = ""; - - public List References = new List(); - - public string Reference - { - get => References.FirstOrDefault(); - set - { - References.Clear(); - if (!string.IsNullOrEmpty(value)) - { - References.Add(value); - } - } - } - - public Image Thumbnail; - - public IAvatarPermission AvatarPermission; - - public IRedistributionLicense RedistributionLicense; - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/Meta.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/Meta.cs.meta deleted file mode 100644 index d82463d9e..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/Meta.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f885e15cc61535b4399979af17aeaa44 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/ModelExtensionsForNode.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/ModelExtensionsForNode.cs deleted file mode 100644 index df51eabb8..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/ModelExtensionsForNode.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Numerics; - - -namespace VrmLib -{ - public static class ModelExtensionsForNode - { - class NodeUsage - { - public bool HasMesh; - public int WeightUsed; - public HumanoidBones? HumanBone; - public bool TreeHasHumanBone; - - /// - /// 子階層に消さずに残すBoneが含まれるか - /// - public bool TreeHasUsedBone; - - public bool SpringUse; - - public override string ToString() - { - if (HumanBone.HasValue) - { - return $"{HumanBone.Value}"; - } - else - { - return $"{Used}"; - } - } - - public bool Used - { - get - { - if (HasMesh) return true; - if (WeightUsed > 0) return true; - if (HumanBone.HasValue && HumanBone.Value != HumanoidBones.unknown) return true; - if (SpringUse) return true; - if (TreeHasHumanBone) return true; - if (TreeHasUsedBone) return true; - return false; - } - } - } - - public static IEnumerable GetRemoveNodes(this Model model) - { - var nodeUsage = model.Nodes.Select(x => - new NodeUsage - { - HasMesh = x.MeshGroup != null, - HumanBone = x.HumanoidBone, - TreeHasHumanBone = x.Traverse().Any(y => y.HumanoidBone.HasValue), - }) - .ToArray(); - - var bones = model.Nodes.Where(x => x.HumanoidBone.HasValue).ToArray(); - - // joint use - foreach (var meshGroup in model.MeshGroups) - { - var skin = meshGroup.Skin; - if (skin != null) - { - foreach (var mesh in meshGroup.Meshes) - { - var joints = mesh.VertexBuffer.Joints; - var weights = mesh.VertexBuffer.Weights; - if (joints != null && weights != null) - { - var jointsSpan = SpanLike.Wrap(joints.Bytes); - var weightsSpan = SpanLike.Wrap(weights.Bytes); - for (int i = 0; i < jointsSpan.Length; ++i) - { - var w = weightsSpan[i]; - var j = jointsSpan[i]; - if (w.X > 0) nodeUsage[model.Nodes.IndexOf(skin.Joints[j.Joint0])].WeightUsed++; - if (w.Y > 0) nodeUsage[model.Nodes.IndexOf(skin.Joints[j.Joint1])].WeightUsed++; - if (w.Z > 0) nodeUsage[model.Nodes.IndexOf(skin.Joints[j.Joint2])].WeightUsed++; - if (w.W > 0) nodeUsage[model.Nodes.IndexOf(skin.Joints[j.Joint3])].WeightUsed++; - } - } - } - } - } - - // 削除されるNodeのうち、子階層に1つでも残るNodeがあればそのNodeも残す - for (int i = 0; i < nodeUsage.Length; i++) - { - if (nodeUsage[i].Used) continue; - - var children = model.Nodes[i].Traverse(); - - nodeUsage[i].TreeHasUsedBone = children.Where(x => nodeUsage[model.Nodes.IndexOf(x)].Used).Any(); - } - - - var spring = model.Vrm?.SpringBone; - if (spring != null) - { - foreach (var x in spring.Springs) - { - foreach (var y in x.Joints) - { - nodeUsage[model.Nodes.IndexOf(y.Node)].SpringUse = true; - } - foreach (var y in x.Colliders) - { - nodeUsage[model.Nodes.IndexOf(y.Node)].SpringUse = true; - } - } - } - - var nodes = nodeUsage.Select((x, i) => (i, x)) - .Where(x => !x.Item2.Used) - .Select(x => model.Nodes[x.Item1]) - .ToArray(); - return nodes; - } - } -} \ No newline at end of file diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/ModelExtensionsForNode.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/ModelExtensionsForNode.cs.meta deleted file mode 100644 index af76e43ab..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/ModelExtensionsForNode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f2ab63c74d9ba6444aedc57776a8a1c2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MorphTargetBind.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/MorphTargetBind.cs deleted file mode 100644 index bbca8c022..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MorphTargetBind.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace VrmLib -{ - public class MorphTargetBind - { - /// - /// 対象のMesh(Renderer) - /// - public Node Node; - - /// - /// MorphTarget の name - /// - public readonly string Name; - - /// - /// MorphTarget の適用度 - /// - public readonly float Value; - - public MorphTargetBind(Node node, string name, float value) - { - Node = node; - Name = name; - Value = value; - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/MorphTargetBind.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/MorphTargetBind.cs.meta deleted file mode 100644 index 0eb1d2c1d..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/MorphTargetBind.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a9c5b4a0882f60e45b9ba9dea21b51b4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/SpringBoneManager.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/SpringBoneManager.cs deleted file mode 100644 index 9639a21fa..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/SpringBoneManager.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Numerics; - -namespace VrmLib -{ - public enum VrmSpringBoneColliderTypes - { - Sphere, - Capsule, - } - - public struct VrmSpringBoneCollider - { - public readonly VrmSpringBoneColliderTypes ColliderType; - public readonly Vector3 Offset; - public readonly float Radius; - public readonly Vector3 CapsuleTail; - - VrmSpringBoneCollider(VrmSpringBoneColliderTypes type, Vector3 offset, float radius, Vector3 tail) - { - ColliderType = type; - Offset = offset; - Radius = radius; - CapsuleTail = tail; - } - - public static VrmSpringBoneCollider CreateSphere(Vector3 offset, float radius) - { - return new VrmSpringBoneCollider(VrmSpringBoneColliderTypes.Sphere, offset, radius, Vector3.Zero); - } - - public static VrmSpringBoneCollider CreateCapsule(Vector3 offset, float radius, Vector3 tail) - { - return new VrmSpringBoneCollider(VrmSpringBoneColliderTypes.Capsule, offset, radius, tail); - } - } - - public class SpringBoneColliderGroup - { - public readonly Node Node; - - public readonly List Colliders; - - public SpringBoneColliderGroup(Node node, IEnumerable colliders) - { - Node = node; - Colliders = colliders.ToList(); - } - } - - public class SpringJoint - { - public readonly Node Node; - - public SpringJoint(Node node) - { - Node = node; - } - - public float DragForce; - - public Vector3 GravityDir; - - public float GravityPower; - - public float HitRadius; - - public float Stiffness; - - public bool Exclude; - } - - public class SpringBone - { - public const string ExtensionName = "VRMC_springBone"; - public readonly List Joints = new List(); - public Node Origin; - - public readonly List Colliders = new List(); - - public string Comment = ""; - } - - public class SpringBoneManager - { - public readonly List Springs = new List(); - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/SpringBoneManager.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/SpringBoneManager.cs.meta deleted file mode 100644 index b7414c79b..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/SpringBoneManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2735f48f8080886478a861cca79c14d9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/TextureTransformBind.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/TextureTransformBind.cs deleted file mode 100644 index c7b2358c2..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/TextureTransformBind.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Numerics; - -namespace VrmLib -{ - public class TextureTransformBind : IEquatable - { - public readonly Material Material; - public readonly Vector2 Scale; // default = [1, 1] - public readonly Vector2 Offset; // default = [0, 0] - - public TextureTransformBind(Material material, Vector2 scale, Vector2 offset) - { - Material = material; - Scale = scale; - Offset = offset; - } - - public override int GetHashCode() - { - return Material.GetHashCode(); - } - - public bool Equals(TextureTransformBind other) - { - return Material == other.Material && Scale == other.Scale && Offset == other.Offset; - } - - /// - /// Scaleは平均。Offsetは足す - /// - /// - /// - public TextureTransformBind Merge(TextureTransformBind rhs) - { - if (Material != rhs.Material) - { - throw new System.Exception(); - } - return new TextureTransformBind(Material, (Scale + rhs.Scale) / 2, Offset + rhs.Offset); - } - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/TextureTransformBind.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/TextureTransformBind.cs.meta deleted file mode 100644 index 5d6107e3d..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/TextureTransformBind.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d69e0550fa5272248ac04fb52bef427f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/Vrm.cs b/Assets/VRM10/vrmlib/Runtime/Vrm/Vrm.cs deleted file mode 100644 index c2b02dbc2..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/Vrm.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace VrmLib -{ - public class Vrm - { - public Meta Meta = new Meta(); - - public string ExporterVersion; - public string SpecVersion; - - public Vrm(Meta meta, string exporterVersion, string specVersion) - { - Meta = meta; - ExporterVersion = exporterVersion; - SpecVersion = specVersion; - } - - public override string ToString() - { - return $"{Meta}"; - } - - public ExpressionManager ExpressionManager = new ExpressionManager(); - - public SpringBoneManager SpringBone = new SpringBoneManager(); - - public FirstPerson FirstPerson = new FirstPerson(); - - public LookAt LookAt = new LookAt(); - } -} diff --git a/Assets/VRM10/vrmlib/Runtime/Vrm/Vrm.cs.meta b/Assets/VRM10/vrmlib/Runtime/Vrm/Vrm.cs.meta deleted file mode 100644 index f5e682de4..000000000 --- a/Assets/VRM10/vrmlib/Runtime/Vrm/Vrm.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2f9ba743e96ecdc47abdc36b799ad539 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRM10/vrmlib/Tests/BvhTests.cs b/Assets/VRM10/vrmlib/Tests/BvhTests.cs deleted file mode 100644 index 46b135893..000000000 --- a/Assets/VRM10/vrmlib/Tests/BvhTests.cs +++ /dev/null @@ -1,161 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Text; -using NUnit.Framework; -using VrmLib; -using VrmLib.Bvh; - -namespace VrmLibTests -{ - public class BvhTests - { - DirectoryInfo RootPath - { - get - { - return new FileInfo(GetType().Assembly.Location).Directory.Parent.Parent; - } - } - - [Test] - [TestCase("Assets/StreamingAssets/VRM.Samples/Motions/test.txt")] - public void BvhTest(string filename) - { - var path = Path.Combine(RootPath.FullName, filename); - var text = File.ReadAllText(path, Encoding.UTF8); - var bvh = BvhParser.Parse(text); - Assert.AreEqual(4007, bvh.FrameCount); - - var model = ModelExtensionsForBvh.Load(Path.GetFileName(path), bvh); - } - - [Test] - [TestCase("Assets/StreamingAssets/VRM.Samples/Motions/test.txt")] - public void SkeletonEstimatorTest(string filename) - { - var path = Path.Combine(RootPath.FullName, filename); - var text = File.ReadAllText(path, Encoding.UTF8); - var bvh = BvhParser.Parse(text); - - var model = ModelExtensionsForBvh.CreateFromBvh(bvh.Root); - - var estimated = SkeletonEstimator.Detect(model.Root); - Assert.AreEqual(estimated[HumanoidBones.hips].Name, "Hips"); - Assert.AreEqual(estimated[HumanoidBones.spine].Name, "Spine"); - Assert.AreEqual(estimated[HumanoidBones.chest].Name, "Spine1"); - Assert.AreEqual(estimated[HumanoidBones.neck].Name, "Neck"); - Assert.AreEqual(estimated[HumanoidBones.head].Name, "Head"); - Assert.AreEqual(estimated[HumanoidBones.leftShoulder].Name, "LeftShoulder"); - Assert.AreEqual(estimated[HumanoidBones.leftUpperArm].Name, "LeftArm"); - Assert.AreEqual(estimated[HumanoidBones.leftLowerArm].Name, "LeftForeArm"); - Assert.AreEqual(estimated[HumanoidBones.leftHand].Name, "LeftHand"); - Assert.AreEqual(estimated[HumanoidBones.rightShoulder].Name, "RightShoulder"); - Assert.AreEqual(estimated[HumanoidBones.rightUpperArm].Name, "RightArm"); - Assert.AreEqual(estimated[HumanoidBones.rightLowerArm].Name, "RightForeArm"); - Assert.AreEqual(estimated[HumanoidBones.rightHand].Name, "RightHand"); - Assert.AreEqual(estimated[HumanoidBones.leftUpperLeg].Name, "LeftUpLeg"); - Assert.AreEqual(estimated[HumanoidBones.leftLowerLeg].Name, "LeftLeg"); - Assert.AreEqual(estimated[HumanoidBones.leftFoot].Name, "LeftFoot"); - Assert.AreEqual(estimated[HumanoidBones.leftToes].Name, "LeftToeBase"); - Assert.AreEqual(estimated[HumanoidBones.rightUpperLeg].Name, "RightUpLeg"); - Assert.AreEqual(estimated[HumanoidBones.rightLowerLeg].Name, "RightLeg"); - Assert.AreEqual(estimated[HumanoidBones.rightFoot].Name, "RightFoot"); - Assert.AreEqual(estimated[HumanoidBones.rightToes].Name, "RightToeBase"); - } - - DirectoryInfo TestModelPath - { - get - { - var env = Environment.GetEnvironmentVariable("VRM_TEST_MODELS"); - return new DirectoryInfo(env); - } - } - - [Test] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample00.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample01.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample02.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample03.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample04.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample05.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample06.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample07.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample08.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample09.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample10.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample11.bvh")] - [TestCase("Motions/bvh/liveanimation/la_bvh_sample12.bvh")] - public void SkeletonEstimatorTestLA(string filename) - { - var path = Path.Combine(TestModelPath.FullName, filename); - var text = File.ReadAllText(path, Encoding.UTF8); - var bvh = BvhParser.Parse(text); - var model = ModelExtensionsForBvh.CreateFromBvh(bvh.Root); - var estimated = SkeletonEstimator.Detect(model.Root); - Assert.AreEqual(estimated[HumanoidBones.hips].Name, "Hips"); - Assert.AreEqual(estimated[HumanoidBones.spine].Name, "Chest"); - Assert.AreEqual(estimated[HumanoidBones.chest].Name, "Chest2"); - Assert.AreEqual(estimated[HumanoidBones.neck].Name, "Neck"); - Assert.AreEqual(estimated[HumanoidBones.head].Name, "Head"); - Assert.AreEqual(estimated[HumanoidBones.leftShoulder].Name, "LeftCollar"); - Assert.AreEqual(estimated[HumanoidBones.leftUpperArm].Name, "LeftShoulder"); - Assert.AreEqual(estimated[HumanoidBones.leftLowerArm].Name, "LeftElbow"); - Assert.AreEqual(estimated[HumanoidBones.leftHand].Name, "LeftWrist"); - Assert.AreEqual(estimated[HumanoidBones.rightShoulder].Name, "RightCollar"); - Assert.AreEqual(estimated[HumanoidBones.rightUpperArm].Name, "RightShoulder"); - Assert.AreEqual(estimated[HumanoidBones.rightLowerArm].Name, "RightElbow"); - Assert.AreEqual(estimated[HumanoidBones.rightHand].Name, "RightWrist"); - Assert.AreEqual(estimated[HumanoidBones.leftUpperLeg].Name, "LeftHip"); - Assert.AreEqual(estimated[HumanoidBones.leftLowerLeg].Name, "LeftKnee"); - Assert.AreEqual(estimated[HumanoidBones.leftFoot].Name, "LeftAnkle"); - Assert.AreEqual(estimated[HumanoidBones.rightUpperLeg].Name, "RightHip"); - Assert.AreEqual(estimated[HumanoidBones.rightLowerLeg].Name, "RightKnee"); - Assert.AreEqual(estimated[HumanoidBones.rightFoot].Name, "RightAnkle"); - } - - [Test] - [TestCase("Motions/bvh/accad/eric1.bvh")] - [TestCase("Motions/bvh/accad/ericdog.bvh")] - [TestCase("Motions/bvh/accad/ericrun.bvh")] - [TestCase("Motions/bvh/accad/flip.bvh")] - [TestCase("Motions/bvh/accad/swagger.bvh")] - public void SkeletonEstimatorTestAccad(string filename) - { - var path = Path.Combine(TestModelPath.FullName, filename); - var text = File.ReadAllText(path, Encoding.UTF8); - var bvh = BvhParser.Parse(text); - var bones = bvh.Root.Traverse().ToArray(); - foreach (var bone in bones) - { - Console.WriteLine(bone.Name); - } - var model = ModelExtensionsForBvh.CreateFromBvh(bvh.Root); - var estimated = SkeletonEstimator.Detect(model.Root); - - Assert.AreEqual(estimated[HumanoidBones.hips].Name, "root"); - Assert.AreEqual(estimated[HumanoidBones.spine].Name, "lowerback"); - Assert.AreEqual(estimated[HumanoidBones.chest].Name, "upperback"); - Assert.AreEqual(estimated[HumanoidBones.upperChest].Name, "thorax"); - Assert.AreEqual(estimated[HumanoidBones.neck].Name, "neck"); - Assert.AreEqual(estimated[HumanoidBones.head].Name, "head"); - Assert.AreEqual(estimated[HumanoidBones.leftShoulder].Name, "lshoulderjoint"); - Assert.AreEqual(estimated[HumanoidBones.leftUpperArm].Name, "lhumerus"); - Assert.AreEqual(estimated[HumanoidBones.leftLowerArm].Name, "lradius"); - Assert.AreEqual(estimated[HumanoidBones.leftHand].Name, "lhand"); - Assert.AreEqual(estimated[HumanoidBones.rightShoulder].Name, "rshoulderjoint"); - Assert.AreEqual(estimated[HumanoidBones.rightUpperArm].Name, "rhumerus"); - Assert.AreEqual(estimated[HumanoidBones.rightLowerArm].Name, "rradius"); - Assert.AreEqual(estimated[HumanoidBones.rightHand].Name, "rhand"); - Assert.AreEqual(estimated[HumanoidBones.rightUpperLeg].Name, "rfemur"); - Assert.AreEqual(estimated[HumanoidBones.rightLowerLeg].Name, "rtibia"); - Assert.AreEqual(estimated[HumanoidBones.rightFoot].Name, "rfoot"); - Assert.AreEqual(estimated[HumanoidBones.rightToes].Name, "rtoes"); - Assert.AreEqual(estimated[HumanoidBones.leftUpperLeg].Name, "lfemur"); - Assert.AreEqual(estimated[HumanoidBones.leftLowerLeg].Name, "ltibia"); - Assert.AreEqual(estimated[HumanoidBones.leftFoot].Name, "lfoot"); - Assert.AreEqual(estimated[HumanoidBones.leftToes].Name, "ltoes"); - } - } -} diff --git a/Assets/VRM10/vrmlib/Tests/BvhTests.cs.meta b/Assets/VRM10/vrmlib/Tests/BvhTests.cs.meta deleted file mode 100644 index 49c5aa4ad..000000000 --- a/Assets/VRM10/vrmlib/Tests/BvhTests.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c6a1d4e939982f84b9f3d94de009eb0e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/VRMShaders/Runtime/TextureFactory.cs b/Assets/VRMShaders/Runtime/TextureFactory.cs index 06e2ac35c..81eafddb8 100644 --- a/Assets/VRMShaders/Runtime/TextureFactory.cs +++ b/Assets/VRMShaders/Runtime/TextureFactory.cs @@ -153,28 +153,31 @@ namespace VRMShaders return; } - foreach (var (key, value) in param.Sampler.WrapModes) + if (param.Sampler.WrapModes != null) { - switch (key) + foreach (var (key, value) in param.Sampler.WrapModes) { - case SamplerWrapType.All: - texture.wrapMode = value; - break; + switch (key) + { + case SamplerWrapType.All: + texture.wrapMode = value; + break; - case SamplerWrapType.U: - texture.wrapModeU = value; - break; + case SamplerWrapType.U: + texture.wrapModeU = value; + break; - case SamplerWrapType.V: - texture.wrapModeV = value; - break; + case SamplerWrapType.V: + texture.wrapModeV = value; + break; - case SamplerWrapType.W: - texture.wrapModeW = value; - break; + case SamplerWrapType.W: + texture.wrapModeW = value; + break; - default: - throw new NotImplementedException(); + default: + throw new NotImplementedException(); + } } } @@ -229,12 +232,12 @@ namespace VRMShaders if (!m_textureCache.TryGetValue(param.ConvertedName, out TextureLoadInfo info)) { TextureLoadInfo baseTexture = default; - if (param.Index0!=null) + if (param.Index0 != null) { baseTexture = await GetOrCreateBaseTexture(param, param.Index0, RenderTextureReadWrite.Linear, false); } TextureLoadInfo occlusionBaseTexture = default; - if (param.Index1!=null) + if (param.Index1 != null) { occlusionBaseTexture = await GetOrCreateBaseTexture(param, param.Index1, RenderTextureReadWrite.Linear, false); }