From 1802915111ee31d8f2c566c5721cd2437b939097 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Mon, 25 Oct 2021 21:47:42 +0900 Subject: [PATCH 01/15] mv gltf buffer access functions to GltfData from GltfExtensions --- .../Runtime/Extensions/glTFExtensions.cs | 141 --------------- .../IO/AnimationIO/AnimationImporterUtil.cs | 24 +-- Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs | 164 ++++++++++++++++++ .../Runtime/UniGLTF/IO/ImporterContext.cs | 6 +- .../UniGLTF/IO/MeshIO/JointsAccessor.cs | 8 +- .../Runtime/UniGLTF/IO/MeshIO/MeshImporter.cs | 70 ++++---- .../UniGLTF/IO/MeshIO/WeightsAccessor.cs | 10 +- .../Runtime/UniGLTF/IO/NodeImporter.cs | 8 +- Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs | 23 +-- 9 files changed, 240 insertions(+), 214 deletions(-) diff --git a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs index bbffdb6aa..8bf042ba8 100644 --- a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs +++ b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs @@ -239,153 +239,12 @@ namespace UniGLTF return index; } - static T[] GetAttrib(this glTF self, int count, int byteOffset, glTFBufferView view) where T : struct - { - var attrib = new T[count]; - var segment = self.buffers[view.buffer].GetBytes(); - var bytes = new ArraySegment(segment.Array, segment.Offset + view.byteOffset + byteOffset, count * view.byteStride); - bytes.MarshalCopyTo(attrib); - return attrib; - } - static T[] GetAttrib(this glTF self, glTFAccessor accessor, glTFBufferView view) where T : struct - { - return self.GetAttrib(accessor.count, accessor.byteOffset, view); - } - static IEnumerable _GetIndices(this glTF self, glTFAccessor accessor, out int count) - { - count = accessor.count; - var view = self.bufferViews[accessor.bufferView]; - switch ((glComponentType)accessor.componentType) - { - case glComponentType.UNSIGNED_BYTE: - { - return self.GetAttrib(accessor, view).Select(x => (int)(x)); - } - case glComponentType.UNSIGNED_SHORT: - { - return self.GetAttrib(accessor, view).Select(x => (int)(x)); - } - case glComponentType.UNSIGNED_INT: - { - return self.GetAttrib(accessor, view).Select(x => (int)(x)); - } - } - throw new NotImplementedException("GetIndices: unknown componenttype: " + accessor.componentType); - } - static IEnumerable _GetIndices(this glTF self, glTFBufferView view, int count, int byteOffset, glComponentType componentType) - { - switch (componentType) - { - case glComponentType.UNSIGNED_BYTE: - { - return self.GetAttrib(count, byteOffset, view).Select(x => (int)(x)); - } - case glComponentType.UNSIGNED_SHORT: - { - return self.GetAttrib(count, byteOffset, view).Select(x => (int)(x)); - } - - case glComponentType.UNSIGNED_INT: - { - return self.GetAttrib(count, byteOffset, view).Select(x => (int)(x)); - } - } - throw new NotImplementedException("GetIndices: unknown componenttype: " + componentType); - } - - public static int[] GetIndices(this glTF self, int accessorIndex) - { - int count; - var result = self._GetIndices(self.accessors[accessorIndex], out count); - var indices = new int[count]; - - // flip triangles - var it = result.GetEnumerator(); - { - for (int i = 0; i < count; i += 3) - { - it.MoveNext(); indices[i + 2] = it.Current; - it.MoveNext(); indices[i + 1] = it.Current; - it.MoveNext(); indices[i] = it.Current; - } - } - - return indices; - } - - public static T[] GetArrayFromAccessor(this glTF self, int accessorIndex) where T : struct - { - var vertexAccessor = self.accessors[accessorIndex]; - - if (vertexAccessor.count <= 0) return new T[] { }; - - var result = (vertexAccessor.bufferView != -1) - ? self.GetAttrib(vertexAccessor, self.bufferViews[vertexAccessor.bufferView]) - : new T[vertexAccessor.count] - ; - - var sparse = vertexAccessor.sparse; - if (sparse != null && sparse.count > 0) - { - // override sparse values - var indices = self._GetIndices(self.bufferViews[sparse.indices.bufferView], sparse.count, sparse.indices.byteOffset, sparse.indices.componentType); - var values = self.GetAttrib(sparse.count, sparse.values.byteOffset, self.bufferViews[sparse.values.bufferView]); - - var it = indices.GetEnumerator(); - for (int i = 0; i < sparse.count; ++i) - { - it.MoveNext(); - result[it.Current] = values[i]; - } - } - return result; - } - - public static float[] FlatternFloatArrayFromAccessor(this glTF self, int accessorIndex) - { - var vertexAccessor = self.accessors[accessorIndex]; - - if (vertexAccessor.count <= 0) return new float[] { }; - - var bufferCount = vertexAccessor.count * vertexAccessor.TypeCount; - - float[] result = null; - if (vertexAccessor.bufferView != -1) - { - var attrib = new float[vertexAccessor.count * vertexAccessor.TypeCount]; - var view = self.bufferViews[vertexAccessor.bufferView]; - var segment = self.buffers[view.buffer].GetBytes(); - var bytes = new ArraySegment(segment.Array, segment.Offset + view.byteOffset + vertexAccessor.byteOffset, vertexAccessor.count * view.byteStride); - bytes.MarshalCopyTo(attrib); - result = attrib; - } - else - { - result = new float[bufferCount]; - } - - var sparse = vertexAccessor.sparse; - if (sparse != null && sparse.count > 0) - { - // override sparse values - var indices = self._GetIndices(self.bufferViews[sparse.indices.bufferView], sparse.count, sparse.indices.byteOffset, sparse.indices.componentType); - var values = self.GetAttrib(sparse.count * vertexAccessor.TypeCount, sparse.values.byteOffset, self.bufferViews[sparse.values.bufferView]); - - var it = indices.GetEnumerator(); - for (int i = 0; i < sparse.count; ++i) - { - it.MoveNext(); - result[it.Current] = values[i]; - } - } - return result; - } public static ArraySegment GetImageBytesFromTextureIndex(this glTF self, IStorage storage, int textureIndex) { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/AnimationIO/AnimationImporterUtil.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/AnimationIO/AnimationImporterUtil.cs index 5914212b6..7d4f16239 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/AnimationIO/AnimationImporterUtil.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/AnimationIO/AnimationImporterUtil.cs @@ -185,7 +185,7 @@ namespace UniGLTF return string.Join("/", path); } - public static AnimationClip ConvertAnimationClip(glTF gltf, glTFAnimation animation, IAxisInverter inverter, glTFNode root = null) + public static AnimationClip ConvertAnimationClip(GltfData data, glTFAnimation animation, IAxisInverter inverter, glTFNode root = null) { var clip = new AnimationClip(); clip.ClearCurves(); @@ -195,14 +195,14 @@ namespace UniGLTF foreach (var channel in animation.channels) { - var relativePath = RelativePathFrom(gltf.nodes, root, gltf.nodes[channel.target.node]); + var relativePath = RelativePathFrom(data.GLTF.nodes, root, data.GLTF.nodes[channel.target.node]); switch (channel.target.path) { case glTFAnimationTarget.PATH_TRANSLATION: { var sampler = animation.samplers[channel.sampler]; - var input = gltf.GetArrayFromAccessor(sampler.input); - var output = gltf.FlatternFloatArrayFromAccessor(sampler.output); + var input = data.GetArrayFromAccessor(sampler.input); + var output = data.FlatternFloatArrayFromAccessor(sampler.output); AnimationImporterUtil.SetAnimationCurve( clip, @@ -224,8 +224,8 @@ namespace UniGLTF case glTFAnimationTarget.PATH_ROTATION: { var sampler = animation.samplers[channel.sampler]; - var input = gltf.GetArrayFromAccessor(sampler.input); - var output = gltf.FlatternFloatArrayFromAccessor(sampler.output); + var input = data.GetArrayFromAccessor(sampler.input); + var output = data.FlatternFloatArrayFromAccessor(sampler.output); AnimationImporterUtil.SetAnimationCurve( clip, @@ -250,8 +250,8 @@ namespace UniGLTF case glTFAnimationTarget.PATH_SCALE: { var sampler = animation.samplers[channel.sampler]; - var input = gltf.GetArrayFromAccessor(sampler.input); - var output = gltf.FlatternFloatArrayFromAccessor(sampler.output); + var input = data.GetArrayFromAccessor(sampler.input); + var output = data.FlatternFloatArrayFromAccessor(sampler.output); AnimationImporterUtil.SetAnimationCurve( clip, @@ -267,8 +267,8 @@ namespace UniGLTF case glTFAnimationTarget.PATH_WEIGHT: { - var node = gltf.nodes[channel.target.node]; - var mesh = gltf.meshes[node.mesh]; + var node = data.GLTF.nodes[channel.target.node]; + var mesh = data.GLTF.meshes[node.mesh]; var primitive = mesh.primitives.FirstOrDefault(); var targets = primitive.targets; @@ -283,8 +283,8 @@ namespace UniGLTF .ToArray(); var sampler = animation.samplers[channel.sampler]; - var input = gltf.GetArrayFromAccessor(sampler.input); - var output = gltf.GetArrayFromAccessor(sampler.output); + var input = data.GetArrayFromAccessor(sampler.input); + var output = data.GetArrayFromAccessor(sampler.output); AnimationImporterUtil.SetAnimationCurve( clip, relativePath, diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs index a1fb057e9..b6a622717 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs @@ -1,8 +1,16 @@ using System; using System.Collections.Generic; +using System.Linq; namespace UniGLTF { + /// + /// gltf の読み込み補助クラス + /// + /// * JSONにパースができている + /// * glbの場合は bin chunk のバイト列が入手出来ている + /// + /// public sealed class GltfData { /// @@ -70,5 +78,161 @@ namespace UniGLTF new MigrationFlags() ); } + + #region bytes access helper methods. buffer, bufferView, accessor(may sparse), image + T[] GetAttrib(int count, int byteOffset, glTFBufferView view) where T : struct + { + var attrib = new T[count]; + var segment = GLTF.buffers[view.buffer].GetBytes(); + var bytes = new ArraySegment(segment.Array, segment.Offset + view.byteOffset + byteOffset, count * view.byteStride); + bytes.MarshalCopyTo(attrib); + return attrib; + } + + T[] GetAttrib(glTFAccessor accessor, glTFBufferView view) where T : struct + { + return GetAttrib(accessor.count, accessor.byteOffset, view); + } + + IEnumerable _GetIndices(glTFBufferView view, int count, int byteOffset, glComponentType componentType) + { + switch (componentType) + { + case glComponentType.UNSIGNED_BYTE: + { + return GetAttrib(count, byteOffset, view).Select(x => (int)(x)); + } + + case glComponentType.UNSIGNED_SHORT: + { + return GetAttrib(count, byteOffset, view).Select(x => (int)(x)); + } + + case glComponentType.UNSIGNED_INT: + { + return GetAttrib(count, byteOffset, view).Select(x => (int)(x)); + } + } + throw new NotImplementedException("GetIndices: unknown componenttype: " + componentType); + } + + /// + /// Get indices and cast to int + /// + /// + /// + /// + IEnumerable _GetIndices(glTFAccessor accessor, out int count) + { + count = accessor.count; + var view = GLTF.bufferViews[accessor.bufferView]; + switch ((glComponentType)accessor.componentType) + { + case glComponentType.UNSIGNED_BYTE: + { + return GetAttrib(accessor, view).Select(x => (int)(x)); + } + + case glComponentType.UNSIGNED_SHORT: + { + return GetAttrib(accessor, view).Select(x => (int)(x)); + } + + case glComponentType.UNSIGNED_INT: + { + return GetAttrib(accessor, view).Select(x => (int)(x)); + } + } + throw new NotImplementedException("GetIndices: unknown componenttype: " + accessor.componentType); + } + + public int[] GetIndices(int accessorIndex) + { + int count; + var result = _GetIndices(GLTF.accessors[accessorIndex], out count); + var indices = new int[count]; + + // flip triangles + var it = result.GetEnumerator(); + { + for (int i = 0; i < count; i += 3) + { + it.MoveNext(); indices[i + 2] = it.Current; + it.MoveNext(); indices[i + 1] = it.Current; + it.MoveNext(); indices[i] = it.Current; + } + } + + return indices; + } + + public T[] GetArrayFromAccessor(int accessorIndex) where T : struct + { + var vertexAccessor = GLTF.accessors[accessorIndex]; + + if (vertexAccessor.count <= 0) return new T[] { }; + + var result = (vertexAccessor.bufferView != -1) + ? GetAttrib(vertexAccessor, GLTF.bufferViews[vertexAccessor.bufferView]) + : new T[vertexAccessor.count] + ; + + var sparse = vertexAccessor.sparse; + if (sparse != null && sparse.count > 0) + { + // override sparse values + var indices = _GetIndices(GLTF.bufferViews[sparse.indices.bufferView], sparse.count, sparse.indices.byteOffset, sparse.indices.componentType); + var values = GetAttrib(sparse.count, sparse.values.byteOffset, GLTF.bufferViews[sparse.values.bufferView]); + + var it = indices.GetEnumerator(); + for (int i = 0; i < sparse.count; ++i) + { + it.MoveNext(); + result[it.Current] = values[i]; + } + } + return result; + } + + public float[] FlatternFloatArrayFromAccessor(int accessorIndex) + { + var vertexAccessor = GLTF.accessors[accessorIndex]; + + if (vertexAccessor.count <= 0) return new float[] { }; + + var bufferCount = vertexAccessor.count * vertexAccessor.TypeCount; + + float[] result = null; + if (vertexAccessor.bufferView != -1) + { + var attrib = new float[vertexAccessor.count * vertexAccessor.TypeCount]; + var view = GLTF.bufferViews[vertexAccessor.bufferView]; + var segment = GLTF.buffers[view.buffer].GetBytes(); + var bytes = new ArraySegment(segment.Array, segment.Offset + view.byteOffset + vertexAccessor.byteOffset, vertexAccessor.count * view.byteStride); + bytes.MarshalCopyTo(attrib); + result = attrib; + } + else + { + result = new float[bufferCount]; + } + + var sparse = vertexAccessor.sparse; + if (sparse != null && sparse.count > 0) + { + // override sparse values + var indices = _GetIndices(GLTF.bufferViews[sparse.indices.bufferView], sparse.count, sparse.indices.byteOffset, sparse.indices.componentType); + var values = GetAttrib(sparse.count * vertexAccessor.TypeCount, sparse.values.byteOffset, GLTF.bufferViews[sparse.values.bufferView]); + + var it = indices.GetEnumerator(); + for (int i = 0; i < sparse.count; ++i) + { + it.MoveNext(); + result[it.Current] = values[i]; + } + } + return result; + } + #endregion } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index dbded652e..0484501af 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -135,7 +135,7 @@ namespace UniGLTF { await AnimationClipFactory.LoadAnimationClipAsync(key, () => { - var clip = AnimationImporterUtil.ConvertAnimationClip(GLTF, gltfAnimation, InvertAxis.Create()); + var clip = AnimationImporterUtil.ConvertAnimationClip(Data, gltfAnimation, InvertAxis.Create()); return Task.FromResult(clip); }); } @@ -178,7 +178,7 @@ namespace UniGLTF var index = i; using (MeasureTime("ReadMesh")) { - var x = await awaitCaller.Run(() => meshImporter.ReadMesh(GLTF, index, inverter)); + var x = await awaitCaller.Run(() => meshImporter.ReadMesh(Data, index, inverter)); var y = await BuildMeshAsync(awaitCaller, MeasureTime, x, index); Meshes.Add(y); } @@ -225,7 +225,7 @@ namespace UniGLTF Profiler.BeginSample("NodeImporter.SetupSkinning"); for (var i = 0; i < nodes.Count; ++i) { - NodeImporter.SetupSkinning(GLTF, nodes, i, inverter); + NodeImporter.SetupSkinning(Data, nodes, i, inverter); } Profiler.EndSample(); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/JointsAccessor.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/JointsAccessor.cs index b20a94a21..b5d8a14a0 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/JointsAccessor.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/JointsAccessor.cs @@ -9,14 +9,14 @@ namespace UniGLTF { public delegate (ushort x, ushort y, ushort z, ushort w) Getter(int index); - public static (Getter, int) GetAccessor(glTF gltf, int accessorIndex) + public static (Getter, int) GetAccessor(GltfData data, int accessorIndex) { - var gltfAccessor = gltf.accessors[accessorIndex]; + var gltfAccessor = data.GLTF.accessors[accessorIndex]; switch (gltfAccessor.componentType) { case glComponentType.UNSIGNED_BYTE: { - var array = gltf.GetArrayFromAccessor(accessorIndex); + var array = data.GetArrayFromAccessor(accessorIndex); Getter getter = (i) => { var value = array[i]; @@ -27,7 +27,7 @@ namespace UniGLTF case glComponentType.UNSIGNED_SHORT: { - var array = gltf.GetArrayFromAccessor(accessorIndex); + var array = data.GetArrayFromAccessor(accessorIndex); Getter getter = (i) => { var value = array[i]; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshImporter.cs index 3e0601726..4cbeea347 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshImporter.cs @@ -139,7 +139,7 @@ namespace UniGLTF /// /// /// - public void ImportMeshIndependentVertexBuffer(glTF gltf, glTFMesh gltfMesh, IAxisInverter inverter) + public void ImportMeshIndependentVertexBuffer(GltfData data, glTFMesh gltfMesh, IAxisInverter inverter) { foreach (var prim in gltfMesh.primitives) { @@ -147,14 +147,14 @@ namespace UniGLTF var indexBuffer = prim.indices; // position は必ずある - var positions = gltf.GetArrayFromAccessor(prim.attributes.POSITION); + var positions = data.GetArrayFromAccessor(prim.attributes.POSITION); m_positions.AddRange(positions.Select(inverter.InvertVector3)); var fillLength = m_positions.Count; // normal if (prim.attributes.NORMAL != -1) { - var normals = gltf.GetArrayFromAccessor(prim.attributes.NORMAL); + var normals = data.GetArrayFromAccessor(prim.attributes.NORMAL); if (normals.Length != positions.Length) { throw new Exception("different length"); @@ -166,12 +166,12 @@ namespace UniGLTF // uv if (prim.attributes.TEXCOORD_0 != -1) { - var uvs = gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_0); + var uvs = data.GetArrayFromAccessor(prim.attributes.TEXCOORD_0); if (uvs.Length != positions.Length) { throw new Exception("different length"); } - if (gltf.IsGeneratedUniGLTFAndOlder(1, 16)) + if (data.GLTF.IsGeneratedUniGLTFAndOlder(1, 16)) { #pragma warning disable 0612 // backward compatibility @@ -189,7 +189,7 @@ namespace UniGLTF // uv2 if (prim.attributes.TEXCOORD_1 != -1) { - var uvs = gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_1); + var uvs = data.GetArrayFromAccessor(prim.attributes.TEXCOORD_1); if (uvs.Length != positions.Length) { throw new Exception("different length"); @@ -201,7 +201,7 @@ namespace UniGLTF // color if (prim.attributes.COLOR_0 != -1) { - var colors = gltf.GetArrayFromAccessor(prim.attributes.COLOR_0); + var colors = data.GetArrayFromAccessor(prim.attributes.COLOR_0); if (colors.Length != positions.Length) { throw new Exception("different length"); @@ -213,8 +213,8 @@ namespace UniGLTF // skin if (prim.attributes.JOINTS_0 != -1 && prim.attributes.WEIGHTS_0 != -1) { - var (joints0, jointsLength) = JointsAccessor.GetAccessor(gltf, prim.attributes.JOINTS_0); - var (weights0, weightsLength) = WeightsAccessor.GetAccessor(gltf, prim.attributes.WEIGHTS_0); + var (joints0, jointsLength) = JointsAccessor.GetAccessor(data, prim.attributes.JOINTS_0); + var (weights0, weightsLength) = WeightsAccessor.GetAccessor(data, prim.attributes.WEIGHTS_0); if (jointsLength != positions.Length) { throw new Exception("different length"); @@ -258,7 +258,7 @@ namespace UniGLTF var blendShape = GetOrCreateBlendShape(i); if (primTarget.POSITION != -1) { - var array = gltf.GetArrayFromAccessor(primTarget.POSITION); + var array = data.GetArrayFromAccessor(primTarget.POSITION); if (array.Length != positions.Length) { throw new Exception("different length"); @@ -268,7 +268,7 @@ namespace UniGLTF } if (primTarget.NORMAL != -1) { - var array = gltf.GetArrayFromAccessor(primTarget.NORMAL); + var array = data.GetArrayFromAccessor(primTarget.NORMAL); if (array.Length != positions.Length) { throw new Exception("different length"); @@ -278,7 +278,7 @@ namespace UniGLTF } if (primTarget.TANGENT != -1) { - var array = gltf.GetArrayFromAccessor(primTarget.TANGENT); + var array = data.GetArrayFromAccessor(primTarget.TANGENT); if (array.Length != positions.Length) { throw new Exception("different length"); @@ -291,7 +291,7 @@ namespace UniGLTF var indices = (indexBuffer >= 0) - ? gltf.GetIndices(indexBuffer) + ? data.GetIndices(indexBuffer) : TriangleUtil.FlipTriangle(Enumerable.Range(0, m_positions.Count)).ToArray() // without index array ; for (int i = 0; i < indices.Length; ++i) @@ -314,17 +314,17 @@ namespace UniGLTF /// /// /// - public void ImportMeshSharingVertexBuffer(glTF gltf, glTFMesh gltfMesh, IAxisInverter inverter) + public void ImportMeshSharingVertexBuffer(GltfData data, glTFMesh gltfMesh, IAxisInverter inverter) { { // 同じVertexBufferを共有しているので先頭のモノを使う var prim = gltfMesh.primitives.First(); - m_positions.AddRange(gltf.GetArrayFromAccessor(prim.attributes.POSITION).SelectInplace(inverter.InvertVector3)); + m_positions.AddRange(data.GetArrayFromAccessor(prim.attributes.POSITION).SelectInplace(inverter.InvertVector3)); // normal if (prim.attributes.NORMAL != -1) { - m_normals.AddRange(gltf.GetArrayFromAccessor(prim.attributes.NORMAL).SelectInplace(inverter.InvertVector3)); + m_normals.AddRange(data.GetArrayFromAccessor(prim.attributes.NORMAL).SelectInplace(inverter.InvertVector3)); } #if false @@ -338,31 +338,31 @@ namespace UniGLTF // uv if (prim.attributes.TEXCOORD_0 != -1) { - if (gltf.IsGeneratedUniGLTFAndOlder(1, 16)) + if (data.GLTF.IsGeneratedUniGLTFAndOlder(1, 16)) { #pragma warning disable 0612 // backward compatibility - m_uv.AddRange(gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_0).SelectInplace(x => x.ReverseY())); + m_uv.AddRange(data.GetArrayFromAccessor(prim.attributes.TEXCOORD_0).SelectInplace(x => x.ReverseY())); #pragma warning restore 0612 } else { - m_uv.AddRange(gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_0).SelectInplace(x => x.ReverseUV())); + m_uv.AddRange(data.GetArrayFromAccessor(prim.attributes.TEXCOORD_0).SelectInplace(x => x.ReverseUV())); } } // uv2 if (prim.attributes.TEXCOORD_1 != -1) { - m_uv2.AddRange(gltf.GetArrayFromAccessor(prim.attributes.TEXCOORD_1).SelectInplace(x => x.ReverseUV())); + m_uv2.AddRange(data.GetArrayFromAccessor(prim.attributes.TEXCOORD_1).SelectInplace(x => x.ReverseUV())); } // color if (prim.attributes.COLOR_0 != -1) { - if (gltf.accessors[prim.attributes.COLOR_0].TypeCount == 3) + if (data.GLTF.accessors[prim.attributes.COLOR_0].TypeCount == 3) { - var vec3Color = gltf.GetArrayFromAccessor(prim.attributes.COLOR_0); + var vec3Color = data.GetArrayFromAccessor(prim.attributes.COLOR_0); m_colors.AddRange(new Color[vec3Color.Length]); for (int i = 0; i < vec3Color.Length; i++) @@ -371,21 +371,21 @@ namespace UniGLTF m_colors[i] = new Color(color.x, color.y, color.z); } } - else if (gltf.accessors[prim.attributes.COLOR_0].TypeCount == 4) + else if (data.GLTF.accessors[prim.attributes.COLOR_0].TypeCount == 4) { - m_colors.AddRange(gltf.GetArrayFromAccessor(prim.attributes.COLOR_0)); + m_colors.AddRange(data.GetArrayFromAccessor(prim.attributes.COLOR_0)); } else { - throw new NotImplementedException(string.Format("unknown color type {0}", gltf.accessors[prim.attributes.COLOR_0].type)); + throw new NotImplementedException(string.Format("unknown color type {0}", data.GLTF.accessors[prim.attributes.COLOR_0].type)); } } // skin if (prim.attributes.JOINTS_0 != -1 && prim.attributes.WEIGHTS_0 != -1) { - var (joints0, jointsLength) = JointsAccessor.GetAccessor(gltf, prim.attributes.JOINTS_0); - var (weights0, weightsLength) = WeightsAccessor.GetAccessor(gltf, prim.attributes.WEIGHTS_0); + var (joints0, jointsLength) = JointsAccessor.GetAccessor(data, prim.attributes.JOINTS_0); + var (weights0, weightsLength) = WeightsAccessor.GetAccessor(data, prim.attributes.WEIGHTS_0); for (int j = 0; j < jointsLength; ++j) { @@ -425,17 +425,17 @@ namespace UniGLTF if (primTarget.POSITION != -1) { blendShape.Positions.Assign( - gltf.GetArrayFromAccessor(primTarget.POSITION), inverter.InvertVector3); + data.GetArrayFromAccessor(primTarget.POSITION), inverter.InvertVector3); } if (primTarget.NORMAL != -1) { blendShape.Normals.Assign( - gltf.GetArrayFromAccessor(primTarget.NORMAL), inverter.InvertVector3); + data.GetArrayFromAccessor(primTarget.NORMAL), inverter.InvertVector3); } if (primTarget.TANGENT != -1) { blendShape.Tangents.Assign( - gltf.GetArrayFromAccessor(primTarget.TANGENT), inverter.InvertVector3); + data.GetArrayFromAccessor(primTarget.TANGENT), inverter.InvertVector3); } } } @@ -449,7 +449,7 @@ namespace UniGLTF } else { - var indices = gltf.GetIndices(prim.indices); + var indices = data.GetIndices(prim.indices); m_subMeshes.Add(indices); } @@ -531,18 +531,18 @@ namespace UniGLTF return sharedAttributes; } - public MeshContext ReadMesh(glTF gltf, int meshIndex, IAxisInverter inverter) + public MeshContext ReadMesh(GltfData data, int meshIndex, IAxisInverter inverter) { - var gltfMesh = gltf.meshes[meshIndex]; + var gltfMesh = data.GLTF.meshes[meshIndex]; var meshContext = new MeshContext(gltfMesh.name, meshIndex); if (HasSharedVertexBuffer(gltfMesh)) { - meshContext.ImportMeshSharingVertexBuffer(gltf, gltfMesh, inverter); + meshContext.ImportMeshSharingVertexBuffer(data, gltfMesh, inverter); } else { - meshContext.ImportMeshIndependentVertexBuffer(gltf, gltfMesh, inverter); + meshContext.ImportMeshIndependentVertexBuffer(data, gltfMesh, inverter); } meshContext.RenameBlendShape(gltfMesh); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/WeightsAccessor.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/WeightsAccessor.cs index 7a264b070..a2a78cce3 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/WeightsAccessor.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/WeightsAccessor.cs @@ -10,14 +10,14 @@ namespace UniGLTF /// public delegate (float x, float y, float z, float w) Getter(int index); - public static (Getter, int) GetAccessor(glTF gltf, int accessorIndex) + public static (Getter, int) GetAccessor(GltfData data, int accessorIndex) { - var gltfAccessor = gltf.accessors[accessorIndex]; + var gltfAccessor = data.GLTF.accessors[accessorIndex]; switch (gltfAccessor.componentType) { case glComponentType.UNSIGNED_BYTE: { - var array = gltf.GetArrayFromAccessor(accessorIndex); + var array = data.GetArrayFromAccessor(accessorIndex); Getter getter = (i) => { var value = array[i]; @@ -29,7 +29,7 @@ namespace UniGLTF case glComponentType.UNSIGNED_SHORT: { - var array = gltf.GetArrayFromAccessor(accessorIndex); + var array = data.GetArrayFromAccessor(accessorIndex); Getter getter = (i) => { var value = array[i]; @@ -41,7 +41,7 @@ namespace UniGLTF case glComponentType.FLOAT: { - var array = gltf.GetArrayFromAccessor(accessorIndex); + var array = data.GetArrayFromAccessor(accessorIndex); Getter getter = (i) => { var value = array[i]; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/NodeImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/NodeImporter.cs index e511bca81..48f646e2e 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/NodeImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/NodeImporter.cs @@ -156,7 +156,7 @@ namespace UniGLTF } } - public static void SetupSkinning(glTF gltf, List nodes, int i, IAxisInverter inverter) + public static void SetupSkinning(GltfData data, List nodes, int i, IAxisInverter inverter) { var x = nodes[i]; var skinnedMeshRenderer = x.Transform.GetComponent(); @@ -168,12 +168,12 @@ namespace UniGLTF if (mesh == null) throw new Exception(); if (skinnedMeshRenderer == null) throw new Exception(); - if (x.SkinIndex.Value < gltf.skins.Count) + if (x.SkinIndex.Value < data.GLTF.skins.Count) { // calculate internal values(boundingBox etc...) when sharedMesh assigned ? skinnedMeshRenderer.sharedMesh = null; - var skin = gltf.skins[x.SkinIndex.Value]; + var skin = data.GLTF.skins[x.SkinIndex.Value]; var joints = skin.joints.Select(y => nodes[y].Transform).ToArray(); if (joints.Any()) { @@ -182,7 +182,7 @@ namespace UniGLTF if (skin.inverseBindMatrices != -1) { - var bindPoses = gltf.GetArrayFromAccessor(skin.inverseBindMatrices) + var bindPoses = data.GetArrayFromAccessor(skin.inverseBindMatrices) .Select(inverter.InvertMat4) .ToArray() ; diff --git a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs index d7f7a63b7..ae1435e9e 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs @@ -56,7 +56,7 @@ namespace UniGLTF }; gltf.buffers[0].OpenStorage(storage); - var (getter, len) = WeightsAccessor.GetAccessor(gltf, 0); + var (getter, len) = WeightsAccessor.GetAccessor(GltfData.CreateFromGltfDataForTest(gltf), 0); Assert.AreEqual((1.0f, 2.0f, 3.0f, 4.0f), getter(0)); Assert.AreEqual((5.0f, 6.0f, 7.0f, 8.0f), getter(1)); } @@ -137,11 +137,12 @@ namespace UniGLTF var unityMesh = MeshExportList.Create(go); var (gltfMesh, blendShapeIndexMap) = meshExportSettings.DivideVertexBuffer ? MeshExporter_DividedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, axisInverter, meshExportSettings) - : MeshExporter_SharedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials,axisInverter, meshExportSettings) + : MeshExporter_SharedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, axisInverter, meshExportSettings) ; + var data = GltfData.CreateFromGltfDataForTest(glTF); { - var indices = glTF.GetIndices(gltfMesh.primitives[0].indices); + var indices = data.GetIndices(gltfMesh.primitives[0].indices); Assert.AreEqual(0, indices[0]); Assert.AreEqual(1, indices[1]); Assert.AreEqual(5, indices[2]); @@ -149,8 +150,9 @@ namespace UniGLTF Assert.AreEqual(1, indices[4]); Assert.AreEqual(4, indices[5]); } + { - var indices = glTF.GetIndices(gltfMesh.primitives[1].indices); + var indices = data.GetIndices(gltfMesh.primitives[1].indices); Assert.AreEqual(1, indices[0]); Assert.AreEqual(2, indices[1]); Assert.AreEqual(4, indices[2]); @@ -159,7 +161,7 @@ namespace UniGLTF Assert.AreEqual(3, indices[5]); } - var positions = glTF.GetArrayFromAccessor(gltfMesh.primitives[0].attributes.POSITION); + var positions = data.GetArrayFromAccessor(gltfMesh.primitives[0].attributes.POSITION); Assert.AreEqual(6, positions.Length); } @@ -185,11 +187,12 @@ namespace UniGLTF var unityMesh = MeshExportList.Create(go); var (gltfMesh, blendShapeIndexMap) = meshExportSettings.DivideVertexBuffer ? MeshExporter_DividedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, axisInverter, meshExportSettings) - : MeshExporter_SharedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials,axisInverter, meshExportSettings) + : MeshExporter_SharedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, axisInverter, meshExportSettings) ; + var data = GltfData.CreateFromGltfDataForTest(glTF); { - var indices = glTF.GetIndices(gltfMesh.primitives[0].indices); + var indices = data.GetIndices(gltfMesh.primitives[0].indices); Assert.AreEqual(0, indices[0]); Assert.AreEqual(1, indices[1]); Assert.AreEqual(3, indices[2]); @@ -198,12 +201,12 @@ namespace UniGLTF Assert.AreEqual(2, indices[5]); } { - var positions = glTF.GetArrayFromAccessor(gltfMesh.primitives[0].attributes.POSITION); + var positions = data.GetArrayFromAccessor(gltfMesh.primitives[0].attributes.POSITION); Assert.AreEqual(4, positions.Length); } { - var indices = glTF.GetIndices(gltfMesh.primitives[1].indices); + var indices = data.GetIndices(gltfMesh.primitives[1].indices); Assert.AreEqual(0, indices[0]); Assert.AreEqual(1, indices[1]); Assert.AreEqual(3, indices[2]); @@ -212,7 +215,7 @@ namespace UniGLTF Assert.AreEqual(2, indices[5]); } { - var positions = glTF.GetArrayFromAccessor(gltfMesh.primitives[1].attributes.POSITION); + var positions = data.GetArrayFromAccessor(gltfMesh.primitives[1].attributes.POSITION); Assert.AreEqual(4, positions.Length); } } From 758a9ffff92103eb77c9f17fca129b95171becdf Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 00:39:06 +0900 Subject: [PATCH 02/15] IStorage --- .../ScriptedImporter/TextureExtractor.cs | 1 - .../Runtime/Extensions/glTFExtensions.cs | 18 ------- Assets/UniGLTF/Runtime/UniGLTF/Format/glTF.cs | 7 --- .../Runtime/UniGLTF/IO/FileSystemStorage.cs | 21 ++++++++ Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs | 54 ++++++++++++++++--- .../Runtime/UniGLTF/IO/ImporterContext.cs | 1 - .../IO/TextureIO/GltfTextureImporter.cs | 10 ++-- .../UniGLTF/EditorTextureSerializerTests.cs | 4 +- Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs | 5 +- .../Vrm10TextureDescriptorGenerator.cs | 2 +- Assets/VRM10/Runtime/Migration/MeshUpdater.cs | 2 +- Assets/VRM10/Runtime/Migration/RotateY180.cs | 26 ++++----- 12 files changed, 94 insertions(+), 57 deletions(-) diff --git a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs index d59c81b3c..3824ccd7d 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ScriptedImporter/TextureExtractor.cs @@ -17,7 +17,6 @@ namespace UniGLTF public GltfData Data => m_data; public glTF GLTF => m_data.GLTF; - public IStorage Storage => m_data.Storage; public readonly Dictionary Textures = new Dictionary(); private readonly IReadOnlyDictionary m_subAssets; diff --git a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs index 8bf042ba8..674801c6d 100644 --- a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs +++ b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs @@ -246,24 +246,6 @@ namespace UniGLTF - public static ArraySegment GetImageBytesFromTextureIndex(this glTF self, IStorage storage, int textureIndex) - { - var imageIndex = self.textures[textureIndex].source; - return self.GetImageBytes(storage, imageIndex); - } - - public static ArraySegment GetImageBytes(this glTF self, IStorage storage, int imageIndex) - { - var image = self.images[imageIndex]; - if (string.IsNullOrEmpty(image.uri)) - { - return self.GetViewBytes(image.bufferView); - } - else - { - return storage.Get(image.uri); - } - } static Utf8String s_extensions = Utf8String.From("extensions"); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/glTF.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/glTF.cs index 73aef408a..6cc4a0912 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/glTF.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/glTF.cs @@ -40,13 +40,6 @@ namespace UniGLTF [JsonSchema(MinItems = 1, ExplicitIgnorableItemLength = 0)] public List accessors = new List(); - - public ArraySegment GetViewBytes(int bufferView) - { - var view = bufferViews[bufferView]; - var segment = buffers[view.buffer].GetBytes(); - return new ArraySegment(segment.Array, segment.Offset + view.byteOffset, view.byteLength); - } #endregion [JsonSchema(MinItems = 1, ExplicitIgnorableItemLength = 0)] diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs index 99961fea8..d325bdcda 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; namespace UniGLTF @@ -58,4 +59,24 @@ namespace UniGLTF } } } + + public class GltfStorage : IStorage + { + glTF _gltf; + + public GltfStorage(glTF gltf) + { + _gltf = gltf; + } + + public ArraySegment Get(string url) + { + return _gltf.buffers[0].GetBytes(); + } + + public string GetPath(string url) + { + return null; + } + } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs index b6a622717..886dcbbf9 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs @@ -50,7 +50,7 @@ namespace UniGLTF /// /// URI access /// - public IStorage Storage { get; } + IStorage _storage; /// /// Migration Flags used by ImporterContext @@ -63,27 +63,50 @@ namespace UniGLTF Json = json; GLTF = gltf; Chunks = chunks; - Storage = storage; + _storage = storage; MigrationFlags = migrationFlags; } - public static GltfData CreateFromGltfDataForTest(glTF gltf) + public static GltfData CreateFromGltfDataForTest(glTF gltf, ArraySegment bytes = default) { + IStorage storage = null; + if (bytes.Array != null) + { + storage = new SimpleStorage(bytes); + } + else + { + storage = new GltfStorage(gltf); + } return new GltfData( string.Empty, string.Empty, gltf, new List(), - new SimpleStorage(new ArraySegment()), + storage, new MigrationFlags() ); } #region bytes access helper methods. buffer, bufferView, accessor(may sparse), image + public ArraySegment GetBytes(int bufferIndex) + { + // TODO: + var buffer = GLTF.buffers[bufferIndex]; + return _storage.Get(buffer.uri); + } + + public ArraySegment GetViewBytes(int bufferView) + { + var view = GLTF.bufferViews[bufferView]; + var segment = GetBytes(view.buffer); + return new ArraySegment(segment.Array, segment.Offset + view.byteOffset, view.byteLength); + } + T[] GetAttrib(int count, int byteOffset, glTFBufferView view) where T : struct { + var segment = GetBytes(view.buffer); var attrib = new T[count]; - var segment = GLTF.buffers[view.buffer].GetBytes(); var bytes = new ArraySegment(segment.Array, segment.Offset + view.byteOffset + byteOffset, count * view.byteStride); bytes.MarshalCopyTo(attrib); return attrib; @@ -207,7 +230,7 @@ namespace UniGLTF { var attrib = new float[vertexAccessor.count * vertexAccessor.TypeCount]; var view = GLTF.bufferViews[vertexAccessor.bufferView]; - var segment = GLTF.buffers[view.buffer].GetBytes(); + var segment = GetBytes(view.buffer); var bytes = new ArraySegment(segment.Array, segment.Offset + view.byteOffset + vertexAccessor.byteOffset, vertexAccessor.count * view.byteStride); bytes.MarshalCopyTo(attrib); result = attrib; @@ -233,6 +256,25 @@ namespace UniGLTF } return result; } + + public ArraySegment GetImageBytes(int imageIndex) + { + var image = GLTF.images[imageIndex]; + if (string.IsNullOrEmpty(image.uri)) + { + return GetViewBytes(image.bufferView); + } + else + { + return _storage.Get(image.uri); + } + } + + public ArraySegment GetImageBytesFromTextureIndex(int textureIndex) + { + var imageIndex = GLTF.textures[textureIndex].source; + return GetImageBytes(imageIndex); + } #endregion } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs index 0484501af..e27c409a0 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ImporterContext.cs @@ -57,7 +57,6 @@ namespace UniGLTF public GltfData Data { get; } public String Json => Data.Json; public glTF GLTF => Data.GLTF; - public IStorage Storage => Data.Storage; #endregion // configuration diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureImporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureImporter.cs index 68a89cb87..39e5cea19 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureImporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureImporter.cs @@ -35,7 +35,7 @@ namespace UniGLTF var gltfImage = data.GLTF.images[gltfTexture.source]; var name = TextureImportName.GetUnityObjectName(TextureImportTypes.sRGB, gltfTexture.name, gltfImage.uri); var sampler = TextureSamplerUtil.CreateSampler(data.GLTF, textureIndex); - GetTextureBytesAsync getTextureBytesAsync = () => Task.FromResult(ToArray(data.GLTF.GetImageBytesFromTextureIndex(data.Storage, textureIndex))); + GetTextureBytesAsync getTextureBytesAsync = () => Task.FromResult(ToArray(data.GetImageBytesFromTextureIndex(textureIndex))); var param = new TextureDescriptor(name, gltfImage.GetExt(), gltfImage.uri, offset, scale, sampler, TextureImportTypes.sRGB, default, default, getTextureBytesAsync, default, default, default, default, default); return (param.SubAssetKey, param); } @@ -46,7 +46,7 @@ namespace UniGLTF var gltfImage = data.GLTF.images[gltfTexture.source]; var name = TextureImportName.GetUnityObjectName(TextureImportTypes.Linear, gltfTexture.name, gltfImage.uri); var sampler = TextureSamplerUtil.CreateSampler(data.GLTF, textureIndex); - GetTextureBytesAsync getTextureBytesAsync = () => Task.FromResult(ToArray(data.GLTF.GetImageBytesFromTextureIndex(data.Storage, textureIndex))); + GetTextureBytesAsync getTextureBytesAsync = () => Task.FromResult(ToArray(data.GetImageBytesFromTextureIndex(textureIndex))); var param = new TextureDescriptor(name, gltfImage.GetExt(), gltfImage.uri, offset, scale, sampler, TextureImportTypes.Linear, default, default, getTextureBytesAsync, default, default, default, default, default); return (param.SubAssetKey, param); } @@ -57,7 +57,7 @@ namespace UniGLTF var gltfImage = data.GLTF.images[gltfTexture.source]; var name = TextureImportName.GetUnityObjectName(TextureImportTypes.NormalMap, gltfTexture.name, gltfImage.uri); var sampler = TextureSamplerUtil.CreateSampler(data.GLTF, textureIndex); - GetTextureBytesAsync getTextureBytesAsync = () => Task.FromResult(ToArray(data.GLTF.GetImageBytesFromTextureIndex(data.Storage, textureIndex))); + GetTextureBytesAsync getTextureBytesAsync = () => Task.FromResult(ToArray(data.GetImageBytesFromTextureIndex(textureIndex))); var param = new TextureDescriptor(name, gltfImage.GetExt(), gltfImage.uri, offset, scale, sampler, TextureImportTypes.NormalMap, default, default, getTextureBytesAsync, default, default, default, default, default); return (param.SubAssetKey, param); } @@ -73,7 +73,7 @@ namespace UniGLTF var gltfTexture = data.GLTF.textures[metallicRoughnessTextureIndex.Value]; name = TextureImportName.GetUnityObjectName(TextureImportTypes.StandardMap, gltfTexture.name, data.GLTF.images[gltfTexture.source].uri); sampler = TextureSamplerUtil.CreateSampler(data.GLTF, metallicRoughnessTextureIndex.Value); - getMetallicRoughnessAsync = () => Task.FromResult(ToArray(data.GLTF.GetImageBytesFromTextureIndex(data.Storage, metallicRoughnessTextureIndex.Value))); + getMetallicRoughnessAsync = () => Task.FromResult(ToArray(data.GetImageBytesFromTextureIndex(metallicRoughnessTextureIndex.Value))); } GetTextureBytesAsync getOcclusionAsync = default; @@ -85,7 +85,7 @@ namespace UniGLTF name = TextureImportName.GetUnityObjectName(TextureImportTypes.StandardMap, gltfTexture.name, data.GLTF.images[gltfTexture.source].uri); } sampler = TextureSamplerUtil.CreateSampler(data.GLTF, occlusionTextureIndex.Value); - getOcclusionAsync = () => Task.FromResult(ToArray(data.GLTF.GetImageBytesFromTextureIndex(data.Storage, occlusionTextureIndex.Value))); + getOcclusionAsync = () => Task.FromResult(ToArray(data.GetImageBytesFromTextureIndex(occlusionTextureIndex.Value))); } var texDesc = new TextureDescriptor(name, ".png", null, offset, scale, sampler, TextureImportTypes.StandardMap, metallicFactor, roughnessFactor, getMetallicRoughnessAsync, getOcclusionAsync, default, default, default, default); diff --git a/Assets/UniGLTF/Tests/UniGLTF/EditorTextureSerializerTests.cs b/Assets/UniGLTF/Tests/UniGLTF/EditorTextureSerializerTests.cs index d625b3c28..71cd70566 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/EditorTextureSerializerTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/EditorTextureSerializerTests.cs @@ -142,8 +142,10 @@ namespace UniGLTF UnityEngine.Object.DestroyImmediate(mat); UnityEngine.Object.DestroyImmediate(root); + var data = GltfData.CreateFromGltfDataForTest(gltf); + // Extract Image to Texture2D - var exportedBytes = gltf.GetViewBytes(exportedImage.bufferView).ToArray(); + var exportedBytes = data.GetViewBytes(exportedImage.bufferView).ToArray(); var exportedTexture = new Texture2D(2, 2, TextureFormat.ARGB32, mipChain: false, linear: false); Assert.IsTrue(exportedTexture.LoadImage(exportedBytes)); // Always true ? Assert.AreEqual(srcTex.width, exportedTexture.width); diff --git a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs index ae1435e9e..ef310e0d5 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs @@ -25,7 +25,6 @@ namespace UniGLTF w.Write(8.0f); bytes = ms.ToArray(); } - var storage = new SimpleStorage(new ArraySegment(bytes)); var gltf = new glTF { @@ -54,9 +53,9 @@ namespace UniGLTF } } }; - gltf.buffers[0].OpenStorage(storage); - var (getter, len) = WeightsAccessor.GetAccessor(GltfData.CreateFromGltfDataForTest(gltf), 0); + var data = GltfData.CreateFromGltfDataForTest(gltf, new ArraySegment(bytes)); + var (getter, len) = WeightsAccessor.GetAccessor(data, 0); Assert.AreEqual((1.0f, 2.0f, 3.0f, 4.0f), getter(0)); Assert.AreEqual((5.0f, 6.0f, 7.0f, 8.0f), getter(1)); } diff --git a/Assets/VRM10/Runtime/IO/Texture/Vrm10TextureDescriptorGenerator.cs b/Assets/VRM10/Runtime/IO/Texture/Vrm10TextureDescriptorGenerator.cs index 9541a5d0b..ea1aaf321 100644 --- a/Assets/VRM10/Runtime/IO/Texture/Vrm10TextureDescriptorGenerator.cs +++ b/Assets/VRM10/Runtime/IO/Texture/Vrm10TextureDescriptorGenerator.cs @@ -110,7 +110,7 @@ namespace UniVRM10 GetTextureBytesAsync getThumbnailImageBytesAsync = () => { - var bytes = data.GLTF.GetImageBytes(data.Storage, imageIndex); + var bytes = data.GetImageBytes(imageIndex); return Task.FromResult(GltfTextureImporter.ToArray(bytes)); }; var texDesc = new TextureDescriptor(objectName, gltfImage.GetExt(), gltfImage.uri, Vector2.zero, Vector2.one, default, TextureImportTypes.sRGB, default, default, diff --git a/Assets/VRM10/Runtime/Migration/MeshUpdater.cs b/Assets/VRM10/Runtime/Migration/MeshUpdater.cs index 34c5300da..86b6c5f66 100644 --- a/Assets/VRM10/Runtime/Migration/MeshUpdater.cs +++ b/Assets/VRM10/Runtime/Migration/MeshUpdater.cs @@ -69,7 +69,7 @@ namespace UniVRM10 // copy images foreach (var image in gltf.images) { - var bytes = gltf.GetViewBytes(image.bufferView); + var bytes = _data.GetViewBytes(image.bufferView); image.bufferView = AddBuffer(bytes); } diff --git a/Assets/VRM10/Runtime/Migration/RotateY180.cs b/Assets/VRM10/Runtime/Migration/RotateY180.cs index 5b7550481..fb7ca77c2 100644 --- a/Assets/VRM10/Runtime/Migration/RotateY180.cs +++ b/Assets/VRM10/Runtime/Migration/RotateY180.cs @@ -47,7 +47,7 @@ namespace UniVRM10 } } - static void ReverseVector3Array(glTF gltf, int accessorIndex, HashSet used) + static void ReverseVector3Array(GltfData data, int accessorIndex, HashSet used) { if (accessorIndex == -1) { @@ -59,7 +59,7 @@ namespace UniVRM10 return; } - var accessor = gltf.accessors[accessorIndex]; + var accessor = data.GLTF.accessors[accessorIndex]; var bufferViewIndex = -1; if (accessor.bufferView != -1) { @@ -72,7 +72,7 @@ namespace UniVRM10 if (bufferViewIndex != -1) { - var buffer = gltf.GetViewBytes(bufferViewIndex); + var buffer = data.GetViewBytes(bufferViewIndex); var span = SpanLike.Wrap(buffer); for (int i = 0; i < span.Length; ++i) { @@ -85,35 +85,35 @@ namespace UniVRM10 /// シーンをY軸で180度回転する /// /// - public static void Rotate(glTF gltf) + public static void Rotate(GltfData data) { - foreach (var node in gltf.nodes) + foreach (var node in data.GLTF.nodes) { Rotate(node); } // mesh の回転のみでよい var used = new HashSet(); - foreach (var mesh in gltf.meshes) + foreach (var mesh in data.GLTF.meshes) { foreach (var prim in mesh.primitives) { - ReverseVector3Array(gltf, prim.attributes.POSITION, used); - ReverseVector3Array(gltf, prim.attributes.NORMAL, used); + ReverseVector3Array(data, prim.attributes.POSITION, used); + ReverseVector3Array(data, prim.attributes.NORMAL, used); foreach (var target in prim.targets) { - ReverseVector3Array(gltf, target.POSITION, used); - ReverseVector3Array(gltf, target.NORMAL, used); + ReverseVector3Array(data, target.POSITION, used); + ReverseVector3Array(data, target.NORMAL, used); } } } - foreach (var skin in gltf.skins) + foreach (var skin in data.GLTF.skins) { if (used.Add(skin.inverseBindMatrices)) { - var accessor = gltf.accessors[skin.inverseBindMatrices]; - var buffer = gltf.GetViewBytes(accessor.bufferView); + var accessor = data.GLTF.accessors[skin.inverseBindMatrices]; + var buffer = data.GetViewBytes(accessor.bufferView); var span = SpanLike.Wrap(buffer); for (int i = 0; i < span.Length; ++i) { From 1c2180793b6bffefac6017838b1416ad318a4d78 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 13:09:30 +0900 Subject: [PATCH 03/15] remove unused IStorage.GetPath --- Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs index b7495b2be..c997c928c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs @@ -5,12 +5,5 @@ namespace UniGLTF public interface IStorage { ArraySegment Get(string url = default); - - /// - /// Get original filepath if exists - /// - /// - /// - string GetPath(string url); } } From 81c6c743dbbeb00115d6ca45c6bbcd2c2174b9f1 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 13:14:07 +0900 Subject: [PATCH 04/15] rename IStorage to IUrlGetter --- .../Format/{IStorage.cs => IUrlGetter.cs} | 2 +- .../{IStorage.cs.meta => IUrlGetter.cs.meta} | 2 +- .../Runtime/UniGLTF/Format/glTFBuffer.cs | 4 ++-- .../Runtime/UniGLTF/IO/FileSystemStorage.cs | 6 +++--- Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs | 18 +++++++++--------- .../UniGLTF/IO/Parser/GlbLowLevelParser.cs | 6 +++--- .../UniGLTF/IO/Parser/JsonWithStorageParser.cs | 8 ++++---- .../Runtime/UniGLTF/IO/ZipArchiveStorage.cs | 2 +- 8 files changed, 24 insertions(+), 24 deletions(-) rename Assets/UniGLTF/Runtime/UniGLTF/Format/{IStorage.cs => IUrlGetter.cs} (76%) rename Assets/UniGLTF/Runtime/UniGLTF/Format/{IStorage.cs.meta => IUrlGetter.cs.meta} (83%) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs similarity index 76% rename from Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs rename to Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs index c997c928c..e1052d157 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs @@ -2,7 +2,7 @@ using System; namespace UniGLTF { - public interface IStorage + public interface IUrlGetter { ArraySegment Get(string url = default); } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs.meta similarity index 83% rename from Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs.meta index d065e98f4..f416db4ca 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs.meta +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 6e3316b83a7396047839d12538e5db52 +guid: aed87db763d65564e96f23fc8bebd382 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs index ed5dbb166..8f5ffe939 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs @@ -9,9 +9,9 @@ namespace UniGLTF IBytesBuffer m_buffer; public IBytesBuffer Buffer => m_buffer; - public void OpenStorage(IStorage storage) + public void OpenStorage(IUrlGetter urlGetter) { - m_buffer = new ArraySegmentByteBuffer(storage.Get(uri)); + m_buffer = new ArraySegmentByteBuffer(urlGetter.Get(uri)); } public glTFBuffer() diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs index d325bdcda..5712f4c95 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs @@ -4,7 +4,7 @@ using System.IO; namespace UniGLTF { - public class SimpleStorage : IStorage + public class SimpleStorage : IUrlGetter { ArraySegment m_bytes; @@ -28,7 +28,7 @@ namespace UniGLTF } } - public class FileSystemStorage : IStorage + public class FileSystemStorage : IUrlGetter { string m_root; @@ -60,7 +60,7 @@ namespace UniGLTF } } - public class GltfStorage : IStorage + public class GltfStorage : IUrlGetter { glTF _gltf; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs index 886dcbbf9..5ce28428d 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs @@ -50,40 +50,40 @@ namespace UniGLTF /// /// URI access /// - IStorage _storage; + IUrlGetter _urlGetter; /// /// Migration Flags used by ImporterContext /// public MigrationFlags MigrationFlags { get; } - public GltfData(string targetPath, string json, glTF gltf, IReadOnlyList chunks, IStorage storage, MigrationFlags migrationFlags) + public GltfData(string targetPath, string json, glTF gltf, IReadOnlyList chunks, IUrlGetter urlGetter, MigrationFlags migrationFlags) { TargetPath = targetPath; Json = json; GLTF = gltf; Chunks = chunks; - _storage = storage; + _urlGetter = urlGetter; MigrationFlags = migrationFlags; } public static GltfData CreateFromGltfDataForTest(glTF gltf, ArraySegment bytes = default) { - IStorage storage = null; + IUrlGetter urlGetter = null; if (bytes.Array != null) { - storage = new SimpleStorage(bytes); + urlGetter = new SimpleStorage(bytes); } else { - storage = new GltfStorage(gltf); + urlGetter = new GltfStorage(gltf); } return new GltfData( string.Empty, string.Empty, gltf, new List(), - storage, + urlGetter, new MigrationFlags() ); } @@ -93,7 +93,7 @@ namespace UniGLTF { // TODO: var buffer = GLTF.buffers[bufferIndex]; - return _storage.Get(buffer.uri); + return _urlGetter.Get(buffer.uri); } public ArraySegment GetViewBytes(int bufferView) @@ -266,7 +266,7 @@ namespace UniGLTF } else { - return _storage.Get(image.uri); + return _urlGetter.Get(image.uri); } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/GlbLowLevelParser.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/GlbLowLevelParser.cs index a0ecdfd51..8c206e782 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/GlbLowLevelParser.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/GlbLowLevelParser.cs @@ -71,7 +71,7 @@ namespace UniGLTF return chunks; } - public static GltfData ParseGltf(string path, string json, IReadOnlyList chunks, IStorage storage, MigrationFlags migrationFlags) + public static GltfData ParseGltf(string path, string json, IReadOnlyList chunks, IUrlGetter urlGetter, MigrationFlags migrationFlags) { var GLTF = GltfDeserializer.Deserialize(json.ParseAsJson()); if (GLTF.asset.version != "2.0") @@ -96,10 +96,10 @@ namespace UniGLTF //GLTF.baseDir = System.IO.Path.GetDirectoryName(Path); foreach (var buffer in GLTF.buffers) { - buffer.OpenStorage(storage); + buffer.OpenStorage(urlGetter); } - return new GltfData(path, json, GLTF, chunks, storage, migrationFlags); + return new GltfData(path, json, GLTF, chunks, urlGetter, migrationFlags); } private static void FixMeshNameUnique(glTF GLTF) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/JsonWithStorageParser.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/JsonWithStorageParser.cs index 53cb0ebfb..c04d8f2f4 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/JsonWithStorageParser.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/JsonWithStorageParser.cs @@ -10,12 +10,12 @@ namespace UniGLTF public sealed class JsonWithStorageParser { private readonly string _json; - private readonly IStorage _storage; - - public JsonWithStorageParser(string json, IStorage storage = null) + private readonly IUrlGetter _storage; + + public JsonWithStorageParser(string json, IUrlGetter urlGetter = null) { _json = json; - _storage = storage ?? new SimpleStorage(new ArraySegment()); + _storage = urlGetter ?? new SimpleStorage(new ArraySegment()); } public GltfData Parse() diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs index 9a15ace8b..fe284e16e 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs @@ -292,7 +292,7 @@ namespace UniGLTF.Zip } } - class ZipArchiveStorage : IStorage + class ZipArchiveStorage : IUrlGetter { public override string ToString() { From 767aeeb9bdf9d0c91aed5e8dbde0e3e964949b4f Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 14:11:06 +0900 Subject: [PATCH 05/15] Separate Byte4.cs and UShort4.cs --- .../Runtime/Extensions/glTFExtensions.cs | 43 ------------------- Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs | 21 +++++++++ .../UniGLTF/Runtime/UniGLTF/IO/Byte4.cs.meta | 11 +++++ Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs | 22 ++++++++++ .../Runtime/UniGLTF/IO/UShort4.cs.meta | 11 +++++ 5 files changed, 65 insertions(+), 43 deletions(-) create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs.meta create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs.meta diff --git a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs index 674801c6d..b5bfc72f6 100644 --- a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs +++ b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs @@ -1,46 +1,11 @@ using System; -using System.Linq; using System.Collections.Generic; -using System.Runtime.InteropServices; using UnityEngine; using System.IO; using UniJSON; namespace UniGLTF { - [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct Byte4 - { - public readonly byte x; - public readonly byte y; - public readonly byte z; - public readonly byte w; - public Byte4(byte _x, byte _y, byte _z, byte _w) - { - x = _x; - y = _y; - z = _z; - w = _w; - } - } - - [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct UShort4 - { - public readonly ushort x; - public readonly ushort y; - public readonly ushort z; - public readonly ushort w; - - public UShort4(ushort _x, ushort _y, ushort _z, ushort _w) - { - x = _x; - y = _y; - z = _z; - w = _w; - } - } - public static class glTFExtensions { struct ComponentVec @@ -239,14 +204,6 @@ namespace UniGLTF return index; } - - - - - - - - static Utf8String s_extensions = Utf8String.From("extensions"); static bool UsedExtension(this glTF self, string key) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs new file mode 100644 index 000000000..7df1446b6 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs @@ -0,0 +1,21 @@ +using System; +using System.Runtime.InteropServices; + +namespace UniGLTF +{ + [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct Byte4 + { + public readonly byte x; + public readonly byte y; + public readonly byte z; + public readonly byte w; + public Byte4(byte _x, byte _y, byte _z, byte _w) + { + x = _x; + y = _y; + z = _z; + w = _w; + } + } +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs.meta new file mode 100644 index 000000000..fcbebceec --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7d396586954b6d34a84d9af8638e492e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs new file mode 100644 index 000000000..d13c87c93 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs @@ -0,0 +1,22 @@ +using System; +using System.Runtime.InteropServices; + +namespace UniGLTF +{ + [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct UShort4 + { + public readonly ushort x; + public readonly ushort y; + public readonly ushort z; + public readonly ushort w; + + public UShort4(ushort _x, ushort _y, ushort _z, ushort _w) + { + x = _x; + y = _y; + z = _z; + w = _w; + } + } +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs.meta new file mode 100644 index 000000000..9c925e07b --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b1f199669bb47f747865a96bcd7bcbfb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 58678776b56339cce51f4b702b9dc1630ac305da Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 17:33:20 +0900 Subject: [PATCH 06/15] add GltfBufferWriter --- .../UniGLTF/ExportDialog/GltfExportWindow.cs | 7 +- .../Runtime/Extensions/glTFExtensions.cs | 194 --------------- .../Runtime/UniGLTF/IO/GltfBufferWriter.cs | 230 ++++++++++++++++++ .../UniGLTF/IO/GltfBufferWriter.cs.meta | 11 + .../UniGLTF/IO/MeshIO/BlendShapeExporter.cs | 18 +- .../UniGLTF/IO/MeshIO/MeshExportUtil.cs | 18 +- .../MeshExporter_DividedVertexBuffer.cs | 6 +- .../MeshIO/MeshExporter_SharedVertexBuffer.cs | 30 +-- .../IO/TextureIO/GltfTextureExporter.cs | 17 +- .../Runtime/UniGLTF/IO/gltfExporter.cs | 23 +- .../UniGLTF/Tests/UniGLTF/GlbParserTests.cs | 16 +- Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs | 4 +- Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs | 14 +- Assets/VRM/Editor/Format/VRMEditorExporter.cs | 5 +- Assets/VRM/Runtime/IO/VRMExporter.cs | 9 +- .../Tests/SampleTests/VRMImportExportTests.cs | 2 +- Assets/VRM10/Runtime/IO/Model/MeshWriter.cs | 11 +- Assets/VRM10/Runtime/IO/Vrm10Exporter.cs | 10 +- Assets/VRM10/Runtime/IO/Vrm10Storage.cs | 16 +- 19 files changed, 342 insertions(+), 299 deletions(-) create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs.meta diff --git a/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs b/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs index b99a31ab9..d330c3933 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs @@ -101,20 +101,21 @@ namespace UniGLTF } var gltf = new glTF(); + GltfBufferWriter writer = default; using (var exporter = new gltfExporter(gltf, Settings)) { exporter.Prepare(State.ExportRoot); - exporter.Export(new EditorTextureSerializer()); + writer = exporter.Export(new EditorTextureSerializer()); } if (isGlb) { - var bytes = gltf.ToGlbBytes(); + var bytes = writer.ToGlbBytes(); File.WriteAllBytes(path, bytes); } else { - var (json, buffers) = gltf.ToGltf(path); + var (json, buffers) = writer.ToGltf(path); // without BOM var encoding = new System.Text.UTF8Encoding(false); File.WriteAllText(path, json, encoding); diff --git a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs index b5bfc72f6..aeeb57da5 100644 --- a/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs +++ b/Assets/UniGLTF/Runtime/Extensions/glTFExtensions.cs @@ -96,200 +96,6 @@ namespace UniGLTF } } - public static int ExtendBufferAndGetAccessorIndex(this glTF gltf, int bufferIndex, T[] array, - glBufferTarget target = glBufferTarget.NONE) where T : struct - { - return gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, new ArraySegment(array), target); - } - - public static int ExtendBufferAndGetAccessorIndex(this glTF gltf, int bufferIndex, - ArraySegment array, - glBufferTarget target = glBufferTarget.NONE) where T : struct - { - if (array.Count == 0) - { - return -1; - } - var viewIndex = ExtendBufferAndGetViewIndex(gltf, bufferIndex, array, target); - - // index buffer's byteStride is unnecessary - gltf.bufferViews[viewIndex].byteStride = 0; - - var accessorIndex = gltf.accessors.Count; - gltf.accessors.Add(new glTFAccessor - { - bufferView = viewIndex, - byteOffset = 0, - componentType = GetComponentType(), - type = GetAccessorType(), - count = array.Count, - }); - return accessorIndex; - } - - public static int ExtendBufferAndGetViewIndex(this glTF gltf, int bufferIndex, - T[] array, - glBufferTarget target = glBufferTarget.NONE) where T : struct - { - return ExtendBufferAndGetViewIndex(gltf, bufferIndex, new ArraySegment(array), target); - } - - public static int ExtendBufferAndGetViewIndex(this glTF gltf, int bufferIndex, - ArraySegment array, - glBufferTarget target = glBufferTarget.NONE) where T : struct - { - if (array.Count == 0) - { - return -1; - } - var view = gltf.buffers[bufferIndex].Append(array, target); - var viewIndex = gltf.bufferViews.Count; - gltf.bufferViews.Add(view); - return viewIndex; - } - - /// - /// sparseValues は間引かれた配列 - /// - public static int ExtendSparseBufferAndGetAccessorIndex(this glTF gltf, int bufferIndex, - int accessorCount, - T[] sparseValues, int[] sparseIndices, int sparseViewIndex, - glBufferTarget target = glBufferTarget.NONE) where T : struct - { - return ExtendSparseBufferAndGetAccessorIndex(gltf, bufferIndex, - accessorCount, - new ArraySegment(sparseValues), sparseIndices, sparseViewIndex, - target); - } - - public static int ExtendSparseBufferAndGetAccessorIndex(this glTF gltf, int bufferIndex, - int accessorCount, - ArraySegment sparseValues, int[] sparseIndices, int sparseIndicesViewIndex, - glBufferTarget target = glBufferTarget.NONE) where T : struct - { - if (sparseValues.Count == 0) - { - return -1; - } - var sparseValuesViewIndex = ExtendBufferAndGetViewIndex(gltf, bufferIndex, sparseValues, target); - var accessorIndex = gltf.accessors.Count; - gltf.accessors.Add(new glTFAccessor - { - byteOffset = 0, - componentType = GetComponentType(), - type = GetAccessorType(), - count = accessorCount, - - sparse = new glTFSparse - { - count = sparseIndices.Length, - indices = new glTFSparseIndices - { - bufferView = sparseIndicesViewIndex, - componentType = glComponentType.UNSIGNED_INT - }, - values = new glTFSparseValues - { - bufferView = sparseValuesViewIndex, - } - } - }); - return accessorIndex; - } - - public static int AddBuffer(this glTF self, IBytesBuffer bytesBuffer) - { - var index = self.buffers.Count; - self.buffers.Add(new glTFBuffer(bytesBuffer)); - return index; - } - - static Utf8String s_extensions = Utf8String.From("extensions"); - - static bool UsedExtension(this glTF self, string key) - { - if (self.extensionsUsed.Contains(key)) - { - return true; - } - - return false; - } - - static void Traverse(this glTF self, JsonNode node, JsonFormatter f, Utf8String parentKey) - { - if (node.IsMap()) - { - f.BeginMap(); - foreach (var kv in node.ObjectItems()) - { - if (parentKey == s_extensions) - { - if (!self.UsedExtension(kv.Key.GetString())) - { - continue; - } - } - f.Key(kv.Key.GetUtf8String()); - self.Traverse(kv.Value, f, kv.Key.GetUtf8String()); - } - f.EndMap(); - } - else if (node.IsArray()) - { - f.BeginList(); - foreach (var x in node.ArrayItems()) - { - self.Traverse(x, f, default(Utf8String)); - } - f.EndList(); - } - else - { - f.Value(node); - } - } - - static string RemoveUnusedExtensions(this glTF self, string json) - { - var f = new JsonFormatter(); - self.Traverse(JsonParser.Parse(json), f, default(Utf8String)); - return f.ToString(); - } - - public static byte[] ToGlbBytes(this glTF self) - { - var f = new JsonFormatter(); - GltfSerializer.Serialize(f, self); - - // remove unused extenions - var json = f.ToString().ParseAsJson().ToString(" "); - self.RemoveUnusedExtensions(json); - - return Glb.Create(json, self.buffers[0].GetBytes()).ToBytes(); - } - - public static (string, List) ToGltf(this glTF self, string gltfPath) - { - var f = new JsonFormatter(); - - // fix buffer path - if (self.buffers.Count == 1) - { - var withoutExt = Path.GetFileNameWithoutExtension(gltfPath); - self.buffers[0].uri = $"{withoutExt}.bin"; - } - else - { - throw new NotImplementedException(); - } - - GltfSerializer.Serialize(f, self); - var json = f.ToString().ParseAsJson().ToString(" "); - self.RemoveUnusedExtensions(json); - return (json, self.buffers); - } - public static bool IsGeneratedUniGLTFAndOlderThan(string generatorVersion, int major, int minor) { if (string.IsNullOrEmpty(generatorVersion)) return false; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs new file mode 100644 index 000000000..27b34e24e --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UniJSON; + +namespace UniGLTF +{ + public class GltfBufferWriter + { + readonly glTF _gltf; + + public glTF GLTF => _gltf; + + public GltfBufferWriter(glTF gltf, int reserved = default) + { + if (reserved == 0) + { + reserved = 50 * 1024 * 1024; + } + _gltf = gltf; + // glb body と gltf の bin 兼用 + _gltf.buffers.Add(new glTFBuffer(new ArrayByteBuffer(new byte[reserved]))); + } + + #region Buffer management for export + public int ExtendBufferAndGetViewIndex( + ArraySegment array, + glBufferTarget target = glBufferTarget.NONE) where T : struct + { + if (array.Count == 0) + { + return -1; + } + var view = _gltf.buffers[0].Append(array, target); + var viewIndex = _gltf.bufferViews.Count; + _gltf.bufferViews.Add(view); + return viewIndex; + } + + public int ExtendBufferAndGetViewIndex( + T[] array, + glBufferTarget target = glBufferTarget.NONE) where T : struct + { + return ExtendBufferAndGetViewIndex(new ArraySegment(array), target); + } + + public int ExtendBufferAndGetAccessorIndex( + ArraySegment array, + glBufferTarget target = glBufferTarget.NONE) where T : struct + { + if (array.Count == 0) + { + return -1; + } + var viewIndex = ExtendBufferAndGetViewIndex(array, target); + + // index buffer's byteStride is unnecessary + _gltf.bufferViews[viewIndex].byteStride = 0; + + var accessorIndex = _gltf.accessors.Count; + _gltf.accessors.Add(new glTFAccessor + { + bufferView = viewIndex, + byteOffset = 0, + componentType = glTFExtensions.GetComponentType(), + type = glTFExtensions.GetAccessorType(), + count = array.Count, + }); + return accessorIndex; + } + + public int ExtendBufferAndGetAccessorIndex(T[] array, + glBufferTarget target = glBufferTarget.NONE) where T : struct + { + return ExtendBufferAndGetAccessorIndex(new ArraySegment(array), target); + } + + /// + /// sparseValues は間引かれた配列 + /// + public int ExtendSparseBufferAndGetAccessorIndex( + int accessorCount, + T[] sparseValues, int[] sparseIndices, int sparseViewIndex, + glBufferTarget target = glBufferTarget.NONE) where T : struct + { + return ExtendSparseBufferAndGetAccessorIndex( + accessorCount, + new ArraySegment(sparseValues), sparseIndices, sparseViewIndex, + target); + } + + public int ExtendSparseBufferAndGetAccessorIndex( + int accessorCount, + ArraySegment sparseValues, int[] sparseIndices, int sparseIndicesViewIndex, + glBufferTarget target = glBufferTarget.NONE) where T : struct + { + if (sparseValues.Count == 0) + { + return -1; + } + var sparseValuesViewIndex = ExtendBufferAndGetViewIndex(sparseValues, target); + var accessorIndex = _gltf.accessors.Count; + _gltf.accessors.Add(new glTFAccessor + { + byteOffset = 0, + componentType = glTFExtensions.GetComponentType(), + type = glTFExtensions.GetAccessorType(), + count = accessorCount, + + sparse = new glTFSparse + { + count = sparseIndices.Length, + indices = new glTFSparseIndices + { + bufferView = sparseIndicesViewIndex, + componentType = glComponentType.UNSIGNED_INT + }, + values = new glTFSparseValues + { + bufferView = sparseValuesViewIndex, + } + } + }); + return accessorIndex; + } + #endregion + + #region ToGltf & ToGlb + static Utf8String s_extensions = Utf8String.From("extensions"); + + static bool UsedExtension(glTF self, string key) + { + if (self.extensionsUsed.Contains(key)) + { + return true; + } + + return false; + } + + static void Traverse(glTF self, JsonNode node, JsonFormatter f, Utf8String parentKey) + { + if (node.IsMap()) + { + f.BeginMap(); + foreach (var kv in node.ObjectItems()) + { + if (parentKey == s_extensions) + { + if (!UsedExtension(self, kv.Key.GetString())) + { + // skip extension not in used + continue; + } + } + f.Key(kv.Key.GetUtf8String()); + Traverse(self, kv.Value, f, kv.Key.GetUtf8String()); + } + f.EndMap(); + } + else if (node.IsArray()) + { + f.BeginList(); + foreach (var x in node.ArrayItems()) + { + Traverse(self, x, f, default(Utf8String)); + } + f.EndList(); + } + else + { + f.Value(node); + } + } + + /// + /// 出力前に不要な extension を削除する + /// + /// + /// + /// + static string RemoveUnusedExtensions(glTF self, string json) + { + var f = new JsonFormatter(); + Traverse(self, JsonParser.Parse(json), f, default(Utf8String)); + return f.ToString(); + } + + /// + /// GLBバイト列 + /// + /// + public byte[] ToGlbBytes() + { + var f = new JsonFormatter(); + GltfSerializer.Serialize(f, _gltf); + + // remove unused extenions + var json = f.ToString().ParseAsJson().ToString(" "); + RemoveUnusedExtensions(_gltf, json); + return Glb.Create(json, _gltf.buffers[0].GetBytes()).ToBytes(); + } + + /// + /// glTF 形式で出力する? + /// + /// + /// + public (string, List) ToGltf(string gltfPath) + { + // fix buffer path + if (_gltf.buffers.Count == 1) + { + var withoutExt = Path.GetFileNameWithoutExtension(gltfPath); + _gltf.buffers[0].uri = $"{withoutExt}.bin"; + } + else + { + throw new NotImplementedException(); + } + + var f = new JsonFormatter(); + GltfSerializer.Serialize(f, _gltf); + var json = f.ToString().ParseAsJson().ToString(" "); + RemoveUnusedExtensions(_gltf, json); + return (json, _gltf.buffers); + } + #endregion + } +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs.meta new file mode 100644 index 000000000..980207bf2 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d36812806fac1f041af501f1d2ad2dbb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs index 84effdfb2..d1a83bb60 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs @@ -7,7 +7,7 @@ namespace UniGLTF { public static class BlendShapeExporter { - public static gltfMorphTarget Export(glTF gltf, int gltfBuffer, Vector3[] positions, Vector3[] normals, bool useSparse) + public static gltfMorphTarget Export(GltfBufferWriter w, Vector3[] positions, Vector3[] normals, bool useSparse) { var accessorCount = positions.Length; if (normals != null && positions.Length != normals.Length) @@ -44,8 +44,8 @@ namespace UniGLTF var positionAccessorIndex = -1; if (sparseIndices.Length > 0) { - var sparseIndicesViewIndex = gltf.ExtendBufferAndGetViewIndex(gltfBuffer, sparseIndices); - positionAccessorIndex = gltf.ExtendSparseBufferAndGetAccessorIndex(gltfBuffer, accessorCount, + var sparseIndicesViewIndex = w.ExtendBufferAndGetViewIndex(sparseIndices); + positionAccessorIndex = w.ExtendSparseBufferAndGetAccessorIndex(accessorCount, sparseIndices.Select(x => positions[x]).ToArray(), sparseIndices, sparseIndicesViewIndex, glBufferTarget.NONE); } @@ -57,8 +57,8 @@ namespace UniGLTF var sparseNormalIndices = Enumerable.Range(0, positions.Length).Where(x => normals[x] != Vector3.zero).ToArray(); if (sparseNormalIndices.Length > 0) { - var sparseNormalIndicesViewIndex = gltf.ExtendBufferAndGetViewIndex(gltfBuffer, sparseNormalIndices); - normalAccessorIndex = gltf.ExtendSparseBufferAndGetAccessorIndex(gltfBuffer, accessorCount, + var sparseNormalIndicesViewIndex = w.ExtendBufferAndGetViewIndex(sparseNormalIndices); + normalAccessorIndex = w.ExtendSparseBufferAndGetAccessorIndex(accessorCount, sparseNormalIndices.Select(x => normals[x]).ToArray(), sparseNormalIndices, sparseNormalIndicesViewIndex, glBufferTarget.NONE); } @@ -73,15 +73,15 @@ namespace UniGLTF else { // position - var positionAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(gltfBuffer, positions, glBufferTarget.ARRAY_BUFFER); - gltf.accessors[positionAccessorIndex].min = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Min(a.x, b.x), Math.Min(a.y, b.y), Mathf.Min(a.z, b.z))).ToArray(); - gltf.accessors[positionAccessorIndex].max = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Max(a.x, b.x), Math.Max(a.y, b.y), Mathf.Max(a.z, b.z))).ToArray(); + var positionAccessorIndex = w.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); + w.GLTF.accessors[positionAccessorIndex].min = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Min(a.x, b.x), Math.Min(a.y, b.y), Mathf.Min(a.z, b.z))).ToArray(); + w.GLTF.accessors[positionAccessorIndex].max = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Max(a.x, b.x), Math.Max(a.y, b.y), Mathf.Max(a.z, b.z))).ToArray(); // normal var normalAccessorIndex = -1; if (normals != null) { - normalAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(gltfBuffer, normals, glBufferTarget.ARRAY_BUFFER); + normalAccessorIndex = w.ExtendBufferAndGetAccessorIndex(normals, glBufferTarget.ARRAY_BUFFER); } return new gltfMorphTarget diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs index 9d3a7eac1..1fce0743b 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs @@ -30,9 +30,9 @@ namespace UniGLTF m_normals[index] = normal; } - public gltfMorphTarget ToGltf(glTF gltf, int gltfBuffer, bool useNormal, bool useSparse) + public gltfMorphTarget ToGltf(GltfBufferWriter w, bool useNormal, bool useSparse) { - return BlendShapeExporter.Export(gltf, gltfBuffer, + return BlendShapeExporter.Export(w, m_positions, useNormal ? m_normals : null, useSparse); @@ -103,24 +103,24 @@ namespace UniGLTF m_weights.Add(new Vector4(boneWeight.weight0, boneWeight.weight1, boneWeight.weight2, boneWeight.weight3)); } - public glTFPrimitives ToGltfPrimitive(glTF gltf, int bufferIndex, int materialIndex, IEnumerable indices) + public glTFPrimitives ToGltfPrimitive(GltfBufferWriter w, int materialIndex, IEnumerable indices) { - var indicesAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, indices.Select(x => (uint)m_vertexIndexMap[x]).ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); + var indicesAccessorIndex = w.ExtendBufferAndGetAccessorIndex(indices.Select(x => (uint)m_vertexIndexMap[x]).ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); var positions = m_positions.ToArray(); - var positionAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, positions, glBufferTarget.ARRAY_BUFFER); + var positionAccessorIndex = w.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); var normals = m_normals.ToArray(); - var normalAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, normals, glBufferTarget.ARRAY_BUFFER); - var uvAccessorIndex0 = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, m_uv.ToArray(), glBufferTarget.ARRAY_BUFFER); + var normalAccessorIndex = w.ExtendBufferAndGetAccessorIndex(normals, glBufferTarget.ARRAY_BUFFER); + var uvAccessorIndex0 = w.ExtendBufferAndGetAccessorIndex(m_uv.ToArray(), glBufferTarget.ARRAY_BUFFER); int? jointsAccessorIndex = default; if (m_joints != null) { - jointsAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, m_joints.ToArray(), glBufferTarget.ARRAY_BUFFER); + jointsAccessorIndex = w.ExtendBufferAndGetAccessorIndex(m_joints.ToArray(), glBufferTarget.ARRAY_BUFFER); } int? weightAccessorIndex = default; if (m_weights != null) { - weightAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, m_weights.ToArray(), glBufferTarget.ARRAY_BUFFER); + weightAccessorIndex = w.ExtendBufferAndGetAccessorIndex(m_weights.ToArray(), glBufferTarget.ARRAY_BUFFER); } var primitive = new glTFPrimitives diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs index 39fede909..ef4051563 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs @@ -17,7 +17,7 @@ namespace UniGLTF /// /// /// - public static (glTFMesh, Dictionary) Export(glTF gltf, int gltfBuffer, + public static (glTFMesh, Dictionary) Export(GltfBufferWriter w, MeshExportInfo unityMesh, List unityMaterials, IAxisInverter axisInverter, GltfExportSettings settings) { @@ -84,7 +84,7 @@ namespace UniGLTF flipped.Add(t1); flipped.Add(t0); } - var gltfPrimitive = buffer.ToGltfPrimitive(gltf, gltfBuffer, materialIndex, flipped); + var gltfPrimitive = buffer.ToGltfPrimitive(w, materialIndex, flipped); // blendShape(morph target) for (int j = 0; j < mesh.blendShapeCount; ++j) @@ -101,7 +101,7 @@ namespace UniGLTF axisInverter.InvertVector3(blendShapeNormals[k])); } - gltfPrimitive.targets.Add(blendShape.ToGltf(gltf, gltfBuffer, !settings.ExportOnlyBlendShapePosition, + gltfPrimitive.targets.Add(blendShape.ToGltf(w, !settings.ExportOnlyBlendShapePosition, settings.UseSparseAccessorForMorphTarget)); } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs index 192077151..0f39041a4 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs @@ -24,27 +24,27 @@ namespace UniGLTF /// /// /// - public static (glTFMesh, Dictionary blendShapeIndexMap) Export(glTF gltf, int bufferIndex, + public static (glTFMesh, Dictionary blendShapeIndexMap) Export(GltfBufferWriter w, MeshExportInfo unityMesh, List unityMaterials, IAxisInverter axisInverter, GltfExportSettings settings) { var mesh = unityMesh.Mesh; var materials = unityMesh.Materials; var positions = mesh.vertices.Select(axisInverter.InvertVector3).ToArray(); - var positionAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, positions, glBufferTarget.ARRAY_BUFFER); - gltf.accessors[positionAccessorIndex].min = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Min(a.x, b.x), Math.Min(a.y, b.y), Mathf.Min(a.z, b.z))).ToArray(); - gltf.accessors[positionAccessorIndex].max = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Max(a.x, b.x), Math.Max(a.y, b.y), Mathf.Max(a.z, b.z))).ToArray(); + var positionAccessorIndex = w.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); + w.GLTF.accessors[positionAccessorIndex].min = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Min(a.x, b.x), Math.Min(a.y, b.y), Mathf.Min(a.z, b.z))).ToArray(); + w.GLTF.accessors[positionAccessorIndex].max = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Max(a.x, b.x), Math.Max(a.y, b.y), Mathf.Max(a.z, b.z))).ToArray(); - var normalAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, mesh.normals.Select(y => axisInverter.InvertVector3(y.normalized)).ToArray(), glBufferTarget.ARRAY_BUFFER); + var normalAccessorIndex = w.ExtendBufferAndGetAccessorIndex(mesh.normals.Select(y => axisInverter.InvertVector3(y.normalized)).ToArray(), glBufferTarget.ARRAY_BUFFER); int? tangentAccessorIndex = default; if (settings.ExportTangents) { - tangentAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, mesh.tangents.Select(axisInverter.InvertVector4).ToArray(), glBufferTarget.ARRAY_BUFFER); + tangentAccessorIndex = w.ExtendBufferAndGetAccessorIndex(mesh.tangents.Select(axisInverter.InvertVector4).ToArray(), glBufferTarget.ARRAY_BUFFER); } - var uvAccessorIndex0 = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, mesh.uv.Select(y => y.ReverseUV()).ToArray(), glBufferTarget.ARRAY_BUFFER); - var uvAccessorIndex1 = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, mesh.uv2.Select(y => y.ReverseUV()).ToArray(), glBufferTarget.ARRAY_BUFFER); + var uvAccessorIndex0 = w.ExtendBufferAndGetAccessorIndex(mesh.uv.Select(y => y.ReverseUV()).ToArray(), glBufferTarget.ARRAY_BUFFER); + var uvAccessorIndex1 = w.ExtendBufferAndGetAccessorIndex(mesh.uv2.Select(y => y.ReverseUV()).ToArray(), glBufferTarget.ARRAY_BUFFER); var colorAccessorIndex = -1; @@ -54,12 +54,12 @@ namespace UniGLTF ) { // UniUnlit で Multiply 設定になっている - colorAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, mesh.colors, glBufferTarget.ARRAY_BUFFER); + colorAccessorIndex = w.ExtendBufferAndGetAccessorIndex(mesh.colors, glBufferTarget.ARRAY_BUFFER); } var boneweights = mesh.boneWeights; - var weightAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, boneweights.Select(y => new Vector4(y.weight0, y.weight1, y.weight2, y.weight3)).ToArray(), glBufferTarget.ARRAY_BUFFER); - var jointsAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, boneweights.Select(y => + var weightAccessorIndex = w.ExtendBufferAndGetAccessorIndex(boneweights.Select(y => new Vector4(y.weight0, y.weight1, y.weight2, y.weight3)).ToArray(), glBufferTarget.ARRAY_BUFFER); + var jointsAccessorIndex = w.ExtendBufferAndGetAccessorIndex(boneweights.Select(y => new UShort4( (ushort)unityMesh.GetJointIndex(y.boneIndex0), (ushort)unityMesh.GetJointIndex(y.boneIndex1), @@ -127,7 +127,7 @@ namespace UniGLTF indices.Add((uint)i0); } - var indicesAccessorIndex = gltf.ExtendBufferAndGetAccessorIndex(bufferIndex, indices.ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); + var indicesAccessorIndex = w.ExtendBufferAndGetAccessorIndex(indices.ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); if (indicesAccessorIndex < 0) { // https://github.com/vrm-c/UniVRM/issues/664 @@ -156,7 +156,7 @@ namespace UniGLTF int exportBlendShapes = 0; for (int j = 0; j < unityMesh.Mesh.blendShapeCount; ++j) { - var morphTarget = ExportMorphTarget(gltf, bufferIndex, + var morphTarget = ExportMorphTarget(w, unityMesh.Mesh, j, settings.UseSparseAccessorForMorphTarget, settings.ExportOnlyBlendShapePosition, axisInverter); @@ -200,7 +200,7 @@ namespace UniGLTF return useSparse; } - static gltfMorphTarget ExportMorphTarget(glTF gltf, int bufferIndex, + static gltfMorphTarget ExportMorphTarget(GltfBufferWriter w, Mesh mesh, int blendShapeIndex, bool useSparseAccessorForMorphTarget, bool exportOnlyBlendShapePosition, @@ -244,7 +244,7 @@ namespace UniGLTF normals[i] = axisInverter.InvertVector3(normals[i]); } - return BlendShapeExporter.Export(gltf, bufferIndex, + return BlendShapeExporter.Export(w, blendShapeVertices, exportOnlyBlendShapePosition && useNormal ? null : blendShapeNormals, useSparseAccessorForMorphTarget); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs index 165ebe058..fe2ae721b 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs @@ -22,17 +22,16 @@ namespace UniGLTF /// /// /// gltf texture index - public static int PushGltfTexture(this glTF gltf, int bufferIndex, Texture2D texture, ColorSpace textureColorSpace, ITextureSerializer textureSerializer) + public static int PushGltfTexture(GltfBufferWriter w, Texture2D texture, ColorSpace textureColorSpace, ITextureSerializer textureSerializer) { var bytesWithMime = textureSerializer.ExportBytesWithMime(texture, textureColorSpace); // add view - var view = gltf.buffers[bufferIndex].Append(bytesWithMime.bytes, glBufferTarget.NONE); - var viewIndex = gltf.AddBufferView(view); + var viewIndex = w.ExtendBufferAndGetViewIndex(bytesWithMime.bytes); // add image - var imageIndex = gltf.images.Count; - gltf.images.Add(new glTFImage + var imageIndex = w.GLTF.images.Count; + w.GLTF.images.Add(new glTFImage { name = TextureImportName.RemoveSuffix(texture.name), bufferView = viewIndex, @@ -40,13 +39,13 @@ namespace UniGLTF }); // add sampler - var samplerIndex = gltf.samplers.Count; + var samplerIndex = w.GLTF.samplers.Count; var sampler = TextureSamplerUtil.Export(texture); - gltf.samplers.Add(sampler); + w.GLTF.samplers.Add(sampler); // add texture - var textureIndex = gltf.textures.Count; - gltf.textures.Add(new glTFTexture + var textureIndex = w.GLTF.textures.Count; + w.GLTF.textures.Add(new glTFTexture { sampler = samplerIndex, source = imageIndex, diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs index 40f073a76..e62bddb18 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs @@ -12,6 +12,8 @@ namespace UniGLTF { protected glTF glTF; + protected GltfBufferWriter _writer; + public GameObject Copy { get; @@ -70,6 +72,7 @@ namespace UniGLTF public gltfExporter(glTF gltf, GltfExportSettings settings) { glTF = gltf; + _writer = new GltfBufferWriter(gltf); glTF.extensionsUsed.AddRange(ExtensionUsed); @@ -222,11 +225,8 @@ namespace UniGLTF // do nothing } - public virtual void Export(ITextureSerializer textureSerializer) + public virtual GltfBufferWriter Export(ITextureSerializer textureSerializer) { - var bytesBuffer = new ArrayByteBuffer(new byte[50 * 1024 * 1024]); - var bufferIndex = glTF.AddBuffer(bytesBuffer); - Nodes = Copy.transform.Traverse() .Skip(1) // exclude root object for the symmetry with the importer .ToList(); @@ -253,8 +253,8 @@ namespace UniGLTF } var (gltfMesh, blendShapeIndexMap) = m_settings.DivideVertexBuffer - ? MeshExporter_DividedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, m_settings.InverseAxis.Create(), m_settings) - : MeshExporter_SharedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, m_settings.InverseAxis.Create(), m_settings) + ? MeshExporter_DividedVertexBuffer.Export(_writer, unityMesh, Materials, m_settings.InverseAxis.Create(), m_settings) + : MeshExporter_SharedVertexBuffer.Export(_writer, unityMesh, Materials, m_settings.InverseAxis.Create(), m_settings) ; glTF.meshes.Add(gltfMesh); Meshes.Add(unityMesh.Mesh); @@ -293,7 +293,7 @@ namespace UniGLTF if (uniqueBones != null && renderer is SkinnedMeshRenderer smr) { var matrices = x.GetBindPoses().Select(m_settings.InverseAxis.Create().InvertMat4).ToArray(); - var accessor = glTF.ExtendBufferAndGetAccessorIndex(bufferIndex, matrices, glBufferTarget.NONE); + var accessor = _writer.ExtendBufferAndGetAccessorIndex(matrices, glBufferTarget.NONE); var skin = new glTFSkin { inverseBindMatrices = accessor, @@ -339,10 +339,10 @@ namespace UniGLTF { var sampler = animationWithCurve.Animation.samplers[kv.Key]; - var inputAccessorIndex = glTF.ExtendBufferAndGetAccessorIndex(bufferIndex, kv.Value.Input); + var inputAccessorIndex = _writer.ExtendBufferAndGetAccessorIndex(kv.Value.Input); sampler.input = inputAccessorIndex; - var outputAccessorIndex = glTF.ExtendBufferAndGetAccessorIndex(bufferIndex, kv.Value.Output); + var outputAccessorIndex = _writer.ExtendBufferAndGetAccessorIndex(kv.Value.Output); sampler.output = outputAccessorIndex; // modify accessors @@ -371,6 +371,7 @@ namespace UniGLTF animationWithCurve.Animation.name = clip.name; glTF.animations.Add(animationWithCurve.Animation); } + } #endregion #endif @@ -382,10 +383,12 @@ namespace UniGLTF for (var exportedTextureIdx = 0; exportedTextureIdx < exported.Count; ++exportedTextureIdx) { var (unityTexture, colorSpace) = exported[exportedTextureIdx]; - glTF.PushGltfTexture(bufferIndex, unityTexture, colorSpace, textureSerializer); + GltfTextureExporter.PushGltfTexture(_writer, unityTexture, colorSpace, textureSerializer); } FixName(glTF); + + return _writer; } /// diff --git a/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs b/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs index 4e3b2e505..c71d32a5e 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs @@ -8,29 +8,29 @@ namespace UniGLTF [Test] public void TextureNameUniqueness() { - var gltfData = new glTF(); - gltfData.asset.version = "2.0"; - gltfData.buffers.Add(new glTFBuffer(new ArrayByteBuffer(Array.Empty()))); - gltfData.textures.Add(new glTFTexture + var gltf = new glTF(); + gltf.asset.version = "2.0"; + gltf.buffers.Add(new glTFBuffer(new ArrayByteBuffer(Array.Empty()))); + gltf.textures.Add(new glTFTexture { name = "FooBar", source = 0, }); - gltfData.textures.Add(new glTFTexture + gltf.textures.Add(new glTFTexture { name = "foobar", source = 1, }); - gltfData.images.Add(new glTFImage + gltf.images.Add(new glTFImage { name = "HogeFuga", }); - gltfData.images.Add(new glTFImage + gltf.images.Add(new glTFImage { name = "hogefuga", }); - var parser = new GlbLowLevelParser("Test", gltfData.ToGlbBytes()); + var parser = new GlbLowLevelParser("Test", new GltfBufferWriter(gltf).ToGlbBytes()); var data = parser.Parse(); Assert.AreEqual("FooBar", data.GLTF.textures[0].name); diff --git a/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs b/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs index c9432c047..f89103bf1 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs @@ -61,8 +61,8 @@ namespace UniGLTF using (var exporter = new gltfExporter(gltf, new GltfExportSettings())) { exporter.Prepare(root); - exporter.Export(new EditorTextureSerializer()); - return gltf.ToGlbBytes(); + var w = exporter.Export(new EditorTextureSerializer()); + return w.ToGlbBytes(); } } diff --git a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs index ef310e0d5..a5bd20602 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs @@ -118,8 +118,7 @@ namespace UniGLTF public void SharedVertexBufferTest() { var glTF = new glTF(); - var bytesBuffer = new ArrayByteBuffer(new byte[50 * 1024 * 1024]); - var bufferIndex = glTF.AddBuffer(bytesBuffer); + var w = new GltfBufferWriter(glTF, 50 * 1024 * 1024); var Materials = new List{ new Material(Shader.Find("Standard")), // A @@ -135,8 +134,8 @@ namespace UniGLTF var unityMesh = MeshExportList.Create(go); var (gltfMesh, blendShapeIndexMap) = meshExportSettings.DivideVertexBuffer - ? MeshExporter_DividedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, axisInverter, meshExportSettings) - : MeshExporter_SharedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, axisInverter, meshExportSettings) + ? MeshExporter_DividedVertexBuffer.Export(w, unityMesh, Materials, axisInverter, meshExportSettings) + : MeshExporter_SharedVertexBuffer.Export(w, unityMesh, Materials, axisInverter, meshExportSettings) ; var data = GltfData.CreateFromGltfDataForTest(glTF); @@ -168,8 +167,7 @@ namespace UniGLTF public void DividedVertexBufferTest() { var glTF = new glTF(); - var bytesBuffer = new ArrayByteBuffer(new byte[50 * 1024 * 1024]); - var bufferIndex = glTF.AddBuffer(bytesBuffer); + var w = new GltfBufferWriter(glTF, 50 * 1024 * 1024); var Materials = new List{ new Material(Shader.Find("Standard")), // A @@ -185,8 +183,8 @@ namespace UniGLTF var unityMesh = MeshExportList.Create(go); var (gltfMesh, blendShapeIndexMap) = meshExportSettings.DivideVertexBuffer - ? MeshExporter_DividedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, axisInverter, meshExportSettings) - : MeshExporter_SharedVertexBuffer.Export(glTF, bufferIndex, unityMesh, Materials, axisInverter, meshExportSettings) + ? MeshExporter_DividedVertexBuffer.Export(w, unityMesh, Materials, axisInverter, meshExportSettings) + : MeshExporter_SharedVertexBuffer.Export(w, unityMesh, Materials, axisInverter, meshExportSettings) ; var data = GltfData.CreateFromGltfDataForTest(glTF); diff --git a/Assets/VRM/Editor/Format/VRMEditorExporter.cs b/Assets/VRM/Editor/Format/VRMEditorExporter.cs index e7a4d3ae1..27cee46b5 100644 --- a/Assets/VRM/Editor/Format/VRMEditorExporter.cs +++ b/Assets/VRM/Editor/Format/VRMEditorExporter.cs @@ -223,12 +223,13 @@ namespace VRM // 出力 var sw = System.Diagnostics.Stopwatch.StartNew(); var gltf = new UniGLTF.glTF(); + GltfBufferWriter writer = default; using (var exporter = new VRMExporter(gltf, settings.MeshExportSettings)) { exporter.Prepare(target); - exporter.Export(new EditorTextureSerializer()); + writer = exporter.Export(new EditorTextureSerializer()); } - var bytes = gltf.ToGlbBytes(); + var bytes = writer.ToGlbBytes(); Debug.LogFormat("Export elapsed {0}", sw.Elapsed); return bytes; } diff --git a/Assets/VRM/Runtime/IO/VRMExporter.cs b/Assets/VRM/Runtime/IO/VRMExporter.cs index bb6e0a96d..98b1e19cc 100644 --- a/Assets/VRM/Runtime/IO/VRMExporter.cs +++ b/Assets/VRM/Runtime/IO/VRMExporter.cs @@ -12,15 +12,14 @@ namespace VRM { public const Axes Vrm0xSpecificationInverseAxis = Axes.Z; - public static glTF Export(GltfExportSettings configuration, GameObject go, ITextureSerializer textureSerializer) + public static GltfBufferWriter Export(GltfExportSettings configuration, GameObject go, ITextureSerializer textureSerializer) { var gltf = new glTF(); using (var exporter = new VRMExporter(gltf, configuration)) { exporter.Prepare(go); - exporter.Export(textureSerializer); + return exporter.Export(textureSerializer); } - return gltf; } public readonly VRM.glTF_VRM_extensions VRM = new glTF_VRM_extensions(); @@ -29,7 +28,7 @@ namespace VRM { if (exportSettings == null || exportSettings.InverseAxis != Vrm0xSpecificationInverseAxis) { - throw new Exception( $"VRM specification requires InverseAxis settings as {Vrm0xSpecificationInverseAxis}"); + throw new Exception($"VRM specification requires InverseAxis settings as {Vrm0xSpecificationInverseAxis}"); } gltf.extensionsUsed.Add(glTF_VRM_extensions.ExtensionName); @@ -118,7 +117,7 @@ namespace VRM VRM.meta.title = meta.Title; if (meta.Thumbnail != null) { - VRM.meta.texture = glTF.PushGltfTexture(glTF.buffers.Count - 1, meta.Thumbnail, ColorSpace.sRGB, textureSerializer); + VRM.meta.texture = GltfTextureExporter.PushGltfTexture(_writer, meta.Thumbnail, ColorSpace.sRGB, textureSerializer); } VRM.meta.licenseType = meta.LicenseType; diff --git a/Assets/VRM/Tests/SampleTests/VRMImportExportTests.cs b/Assets/VRM/Tests/SampleTests/VRMImportExportTests.cs index ff1e76b5e..ba87552d0 100644 --- a/Assets/VRM/Tests/SampleTests/VRMImportExportTests.cs +++ b/Assets/VRM/Tests/SampleTests/VRMImportExportTests.cs @@ -170,7 +170,7 @@ namespace VRM.Samples // TODO: Check contents in JSON /*var exportJson = */ - JsonParser.Parse(vrm.ToJson()); + JsonParser.Parse(vrm.GLTF.ToJson()); // TODO: Check contents in JSON /*var newExportedJson = */ diff --git a/Assets/VRM10/Runtime/IO/Model/MeshWriter.cs b/Assets/VRM10/Runtime/IO/Model/MeshWriter.cs index 7f2565ad5..3dc82010c 100644 --- a/Assets/VRM10/Runtime/IO/Model/MeshWriter.cs +++ b/Assets/VRM10/Runtime/IO/Model/MeshWriter.cs @@ -65,7 +65,8 @@ namespace UniVRM10 /// /// /// - static IEnumerable ExportMeshDivided(this VrmLib.Mesh mesh, List materials, Vrm10Storage storage, ExportArgs option) + static IEnumerable ExportMeshDivided(this VrmLib.Mesh mesh, List materials, + GltfBufferWriter writer, ExportArgs option) { var bufferIndex = 0; var usedIndices = new List(); @@ -121,7 +122,7 @@ namespace UniVRM10 } } var materialIndex = submesh.Material; - var gltfPrimitive = buffer.ToGltfPrimitive(storage.Gltf, bufferIndex, materialIndex, indices); + var gltfPrimitive = buffer.ToGltfPrimitive(writer, materialIndex, indices); // blendShape for (int j = 0; j < mesh.MorphTargets.Count; ++j) @@ -145,7 +146,7 @@ namespace UniVRM10 ); } - gltfPrimitive.targets.Add(blendShape.ToGltf(storage.Gltf, bufferIndex, !option.removeMorphNormal, option.sparse)); + gltfPrimitive.targets.Add(blendShape.ToGltf(writer, !option.removeMorphNormal, option.sparse)); } yield return gltfPrimitive; @@ -160,7 +161,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, GltfBufferWriter writer, ExportArgs option) { var gltfMesh = new glTFMesh { @@ -172,7 +173,7 @@ namespace UniVRM10 throw new NotImplementedException(); } - foreach (var prim in src.Meshes[0].ExportMeshDivided(materials, storage, option)) + foreach (var prim in src.Meshes[0].ExportMeshDivided(materials, writer, option)) { gltfMesh.primitives.Add(prim); } diff --git a/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs b/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs index 72ebd7ce7..440bb1309 100644 --- a/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs +++ b/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs @@ -37,10 +37,6 @@ namespace UniVRM10 Storage.Gltf.extensionsUsed.Add(UniGLTF.Extensions.VRMC_materials_mtoon.VRMC_materials_mtoon.ExtensionName); Storage.Gltf.extensionsUsed.Add(UniGLTF.Extensions.VRMC_springBone.VRMC_springBone.ExtensionName); Storage.Gltf.extensionsUsed.Add(UniGLTF.Extensions.VRMC_node_constraint.VRMC_node_constraint.ExtensionName); - Storage.Gltf.buffers.Add(new glTFBuffer - { - - }); m_textureSerializer = textureSerializer; m_textureExporter = new TextureExporter(m_textureSerializer); @@ -61,11 +57,11 @@ namespace UniVRM10 return asset; } - public static IEnumerable ExportMeshes(List groups, List materials, Vrm10Storage storage, ExportArgs option) + public static IEnumerable ExportMeshes(List groups, List materials, GltfBufferWriter w, ExportArgs option) { foreach (var group in groups) { - yield return group.ExportMeshGroup(materials, storage, option); + yield return group.ExportMeshGroup(materials, w, option); } } @@ -201,7 +197,7 @@ namespace UniVRM10 for (var exportedTextureIdx = 0; exportedTextureIdx < exportedTextures.Count; ++exportedTextureIdx) { var (unityTexture, texColorSpace) = exportedTextures[exportedTextureIdx]; - Storage.Gltf.PushGltfTexture(0, unityTexture, texColorSpace, m_textureSerializer); + GltfTextureExporter.PushGltfTexture(Storage, unityTexture, texColorSpace, m_textureSerializer); } if (thumbnailTextureIndex.HasValue) diff --git a/Assets/VRM10/Runtime/IO/Vrm10Storage.cs b/Assets/VRM10/Runtime/IO/Vrm10Storage.cs index 9c356f4fb..39b902e99 100644 --- a/Assets/VRM10/Runtime/IO/Vrm10Storage.cs +++ b/Assets/VRM10/Runtime/IO/Vrm10Storage.cs @@ -10,7 +10,7 @@ using VrmLib; namespace UniVRM10 { - public class Vrm10Storage + public class Vrm10Storage : GltfBufferWriter { UniGLTF.GltfData m_data; public UniGLTF.glTF Gltf => m_data.GLTF; @@ -24,15 +24,15 @@ namespace UniVRM10 /// /// for export /// - public Vrm10Storage() + public Vrm10Storage() : base(new glTF + { + extensionsUsed = new List(), + }) { m_data = new GltfData( string.Empty, string.Empty, - new glTF - { - extensionsUsed = new List(), - }, + GLTF, new List(), new SimpleStorage(new ArraySegment()), new MigrationFlags() @@ -41,8 +41,6 @@ namespace UniVRM10 { new UniGLTF.ArrayByteBuffer() }; - - Gltf.AddBuffer(Buffers[0]); } /// @@ -50,7 +48,7 @@ namespace UniVRM10 /// /// /// - public Vrm10Storage(UniGLTF.GltfData data) + public Vrm10Storage(UniGLTF.GltfData data) : base(data.GLTF) { m_data = data; From cc1e10c5bdc2a825488d9c74697fdf8979a273b1 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 19:04:18 +0900 Subject: [PATCH 07/15] Update GltfData comment. --- Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs index 5ce28428d..8c1092edc 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs @@ -5,11 +5,8 @@ using System.Linq; namespace UniGLTF { /// - /// gltf の読み込み補助クラス - /// - /// * JSONにパースができている - /// * glbの場合は bin chunk のバイト列が入手出来ている - /// + /// * JSON is parsed but not validated as glTF + /// * For glb, bin chunks are already available /// public sealed class GltfData { From 766bac70c745028dbe40671feebafd05f95d47f0 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 19:14:50 +0900 Subject: [PATCH 08/15] Rename IUrlGetter to IStorage again. --- .../Runtime/UniGLTF/Format/IStorage.cs | 24 +++++++++++++++++++ .../{IUrlGetter.cs.meta => IStorage.cs.meta} | 2 +- .../Runtime/UniGLTF/Format/IUrlGetter.cs | 9 ------- .../Runtime/UniGLTF/Format/glTFBuffer.cs | 4 ++-- .../Runtime/UniGLTF/IO/FileSystemStorage.cs | 15 +++++++++--- Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs | 18 +++++++------- .../UniGLTF/IO/Parser/GlbLowLevelParser.cs | 6 ++--- .../IO/Parser/JsonWithStorageParser.cs | 6 ++--- .../Runtime/UniGLTF/IO/ZipArchiveStorage.cs | 5 +++- 9 files changed, 58 insertions(+), 31 deletions(-) create mode 100644 Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs rename Assets/UniGLTF/Runtime/UniGLTF/Format/{IUrlGetter.cs.meta => IStorage.cs.meta} (83%) delete mode 100644 Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs new file mode 100644 index 000000000..4d4d65774 --- /dev/null +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs @@ -0,0 +1,24 @@ +using System; + +namespace UniGLTF +{ + /// + /// Represents bytes access by URL in gltf + /// + public interface IStorage + { + /// + /// gltf の buffer の バイト列アクセス を実装する。 + /// 1. url による相対パス + /// 2. url によるbase64 encoding + /// 3. url がnullのときに bin chunk(buffers[0]) にアクセスする + /// + /// TODO: + /// 1. url による相対パス + /// 以外をやめて、呼び出し側で分岐させる。 + /// + /// + /// + ArraySegment Get(string url = default); + } +} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs.meta similarity index 83% rename from Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs.meta index f416db4ca..f70761485 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs.meta +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/IStorage.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: aed87db763d65564e96f23fc8bebd382 +guid: f87f7ed809642e0429061fd5f6c169f3 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs deleted file mode 100644 index e1052d157..000000000 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/IUrlGetter.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace UniGLTF -{ - public interface IUrlGetter - { - ArraySegment Get(string url = default); - } -} diff --git a/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs index 8f5ffe939..ed5dbb166 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/Format/glTFBuffer.cs @@ -9,9 +9,9 @@ namespace UniGLTF IBytesBuffer m_buffer; public IBytesBuffer Buffer => m_buffer; - public void OpenStorage(IUrlGetter urlGetter) + public void OpenStorage(IStorage storage) { - m_buffer = new ArraySegmentByteBuffer(urlGetter.Get(uri)); + m_buffer = new ArraySegmentByteBuffer(storage.Get(uri)); } public glTFBuffer() diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs index 5712f4c95..2ffb85872 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs @@ -4,7 +4,10 @@ using System.IO; namespace UniGLTF { - public class SimpleStorage : IUrlGetter + /// + /// Implement bin chunk access + /// + public class SimpleStorage : IStorage { ArraySegment m_bytes; @@ -28,7 +31,10 @@ namespace UniGLTF } } - public class FileSystemStorage : IUrlGetter + /// + /// Implement url that represnet relative path + /// + public class FileSystemStorage : IStorage { string m_root; @@ -60,7 +66,10 @@ namespace UniGLTF } } - public class GltfStorage : IUrlGetter + /// + /// for UnitTest + /// + public class GltfStorage : IStorage { glTF _gltf; diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs index 8c1092edc..068530dc3 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs @@ -47,40 +47,40 @@ namespace UniGLTF /// /// URI access /// - IUrlGetter _urlGetter; + public IStorage _storage; /// /// Migration Flags used by ImporterContext /// public MigrationFlags MigrationFlags { get; } - public GltfData(string targetPath, string json, glTF gltf, IReadOnlyList chunks, IUrlGetter urlGetter, MigrationFlags migrationFlags) + public GltfData(string targetPath, string json, glTF gltf, IReadOnlyList chunks, IStorage storage, MigrationFlags migrationFlags) { TargetPath = targetPath; Json = json; GLTF = gltf; Chunks = chunks; - _urlGetter = urlGetter; + _storage = storage; MigrationFlags = migrationFlags; } public static GltfData CreateFromGltfDataForTest(glTF gltf, ArraySegment bytes = default) { - IUrlGetter urlGetter = null; + IStorage storage = null; if (bytes.Array != null) { - urlGetter = new SimpleStorage(bytes); + storage = new SimpleStorage(bytes); } else { - urlGetter = new GltfStorage(gltf); + storage = new GltfStorage(gltf); } return new GltfData( string.Empty, string.Empty, gltf, new List(), - urlGetter, + storage, new MigrationFlags() ); } @@ -90,7 +90,7 @@ namespace UniGLTF { // TODO: var buffer = GLTF.buffers[bufferIndex]; - return _urlGetter.Get(buffer.uri); + return _storage.Get(buffer.uri); } public ArraySegment GetViewBytes(int bufferView) @@ -263,7 +263,7 @@ namespace UniGLTF } else { - return _urlGetter.Get(image.uri); + return _storage.Get(image.uri); } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/GlbLowLevelParser.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/GlbLowLevelParser.cs index 8c206e782..a0ecdfd51 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/GlbLowLevelParser.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/GlbLowLevelParser.cs @@ -71,7 +71,7 @@ namespace UniGLTF return chunks; } - public static GltfData ParseGltf(string path, string json, IReadOnlyList chunks, IUrlGetter urlGetter, MigrationFlags migrationFlags) + public static GltfData ParseGltf(string path, string json, IReadOnlyList chunks, IStorage storage, MigrationFlags migrationFlags) { var GLTF = GltfDeserializer.Deserialize(json.ParseAsJson()); if (GLTF.asset.version != "2.0") @@ -96,10 +96,10 @@ namespace UniGLTF //GLTF.baseDir = System.IO.Path.GetDirectoryName(Path); foreach (var buffer in GLTF.buffers) { - buffer.OpenStorage(urlGetter); + buffer.OpenStorage(storage); } - return new GltfData(path, json, GLTF, chunks, urlGetter, migrationFlags); + return new GltfData(path, json, GLTF, chunks, storage, migrationFlags); } private static void FixMeshNameUnique(glTF GLTF) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/JsonWithStorageParser.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/JsonWithStorageParser.cs index c04d8f2f4..5037dd55b 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/JsonWithStorageParser.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/Parser/JsonWithStorageParser.cs @@ -10,12 +10,12 @@ namespace UniGLTF public sealed class JsonWithStorageParser { private readonly string _json; - private readonly IUrlGetter _storage; + private readonly IStorage _storage; - public JsonWithStorageParser(string json, IUrlGetter urlGetter = null) + public JsonWithStorageParser(string json, IStorage storage = null) { _json = json; - _storage = urlGetter ?? new SimpleStorage(new ArraySegment()); + _storage = storage ?? new SimpleStorage(new ArraySegment()); } public GltfData Parse() diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs index fe284e16e..eaee1d74c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs @@ -292,7 +292,10 @@ namespace UniGLTF.Zip } } - class ZipArchiveStorage : IUrlGetter + /// + /// Implement url that reference zip archive + /// + class ZipArchiveStorage : IStorage { public override string ToString() { From 0d1c1d92fd9082e7694862460aa78ec6c80b9238 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 19:17:53 +0900 Subject: [PATCH 09/15] remove region --- Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs index 068530dc3..64c35f7ee 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfData.cs @@ -85,7 +85,6 @@ namespace UniGLTF ); } - #region bytes access helper methods. buffer, bufferView, accessor(may sparse), image public ArraySegment GetBytes(int bufferIndex) { // TODO: @@ -272,6 +271,5 @@ namespace UniGLTF var imageIndex = GLTF.textures[textureIndex].source; return GetImageBytes(imageIndex); } - #endregion } } From 1e2166eb10ef12c63754a3efae55f4ec57dcc742 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 19:26:50 +0900 Subject: [PATCH 10/15] sealed class GltfStorage --- Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs index 2ffb85872..61208db1e 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs @@ -69,7 +69,7 @@ namespace UniGLTF /// /// for UnitTest /// - public class GltfStorage : IStorage + public sealed class GltfStorage : IStorage { glTF _gltf; From ddcb5af0e3b65ee9608978db06c5ce00bfbb6780 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 19:31:16 +0900 Subject: [PATCH 11/15] readonly struct Byte4 and UShort4. --- Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs | 7 ++++++- Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs index 7df1446b6..57dff1c06 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/Byte4.cs @@ -4,7 +4,7 @@ using System.Runtime.InteropServices; namespace UniGLTF { [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct Byte4 + public readonly struct Byte4 : IEquatable { public readonly byte x; public readonly byte y; @@ -17,5 +17,10 @@ namespace UniGLTF z = _z; w = _w; } + + public bool Equals(Byte4 other) + { + return x == other.x && y == other.y && z == other.z && w == other.w; + } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs index d13c87c93..3dcee0c1e 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/UShort4.cs @@ -4,7 +4,7 @@ using System.Runtime.InteropServices; namespace UniGLTF { [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct UShort4 + public readonly struct UShort4 : IEquatable { public readonly ushort x; public readonly ushort y; @@ -18,5 +18,10 @@ namespace UniGLTF z = _z; w = _w; } + + public bool Equals(UShort4 other) + { + return x == other.x && y == other.y && z == other.z && w == other.w; + } } } From 04a58dc02c47844acb34d7341a02eae96537c033 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 19:33:24 +0900 Subject: [PATCH 12/15] Remove unused IStorage.GetPath --- .../Runtime/UniGLTF/IO/FileSystemStorage.cs | 22 ------------------- .../Runtime/UniGLTF/IO/ZipArchiveStorage.cs | 5 ----- 2 files changed, 27 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs index 61208db1e..748714d8b 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/FileSystemStorage.cs @@ -24,11 +24,6 @@ namespace UniGLTF { return m_bytes; } - - public string GetPath(string url) - { - return null; - } } /// @@ -52,18 +47,6 @@ namespace UniGLTF ; return new ArraySegment(bytes); } - - public string GetPath(string url) - { - if (url.FastStartsWith("data:")) - { - return null; - } - else - { - return Path.Combine(m_root, url).Replace("\\", "/"); - } - } } /// @@ -82,10 +65,5 @@ namespace UniGLTF { return _gltf.buffers[0].GetBytes(); } - - public string GetPath(string url) - { - return null; - } } } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs index eaee1d74c..de38cfc9c 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ZipArchiveStorage.cs @@ -381,10 +381,5 @@ namespace UniGLTF.Zip throw new NotImplementedException(found.CompressionMethod.ToString()); } - - public string GetPath(string url) - { - return null; - } } } From e8f7fdbda7e028facfa54e51da28022623a28e9b Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 20:34:50 +0900 Subject: [PATCH 13/15] Rename GltfBufferWriter to ExportingGltfData --- .../UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs | 2 +- .../IO/{GltfBufferWriter.cs => ExportingGltfData.cs} | 4 ++-- .../{GltfBufferWriter.cs.meta => ExportingGltfData.cs.meta} | 2 +- .../UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs | 2 +- Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs | 4 ++-- .../UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs | 2 +- .../UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs | 4 ++-- .../Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs | 2 +- Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs | 6 +++--- Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs | 2 +- Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs | 4 ++-- Assets/VRM/Editor/Format/VRMEditorExporter.cs | 2 +- Assets/VRM/Runtime/IO/VRMExporter.cs | 2 +- Assets/VRM10/Runtime/IO/Model/MeshWriter.cs | 5 ++--- Assets/VRM10/Runtime/IO/Vrm10Exporter.cs | 2 +- Assets/VRM10/Runtime/IO/Vrm10Storage.cs | 2 +- 16 files changed, 23 insertions(+), 24 deletions(-) rename Assets/UniGLTF/Runtime/UniGLTF/IO/{GltfBufferWriter.cs => ExportingGltfData.cs} (98%) rename Assets/UniGLTF/Runtime/UniGLTF/IO/{GltfBufferWriter.cs.meta => ExportingGltfData.cs.meta} (83%) diff --git a/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs b/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs index d330c3933..7a4f27459 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs @@ -101,7 +101,7 @@ namespace UniGLTF } var gltf = new glTF(); - GltfBufferWriter writer = default; + ExportingGltfData writer = default; using (var exporter = new gltfExporter(gltf, Settings)) { exporter.Prepare(State.ExportRoot); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs similarity index 98% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs rename to Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs index 27b34e24e..99dd7a5a5 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs @@ -5,13 +5,13 @@ using UniJSON; namespace UniGLTF { - public class GltfBufferWriter + public class ExportingGltfData { readonly glTF _gltf; public glTF GLTF => _gltf; - public GltfBufferWriter(glTF gltf, int reserved = default) + public ExportingGltfData(glTF gltf, int reserved = default) { if (reserved == 0) { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs.meta b/Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs.meta similarity index 83% rename from Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs.meta rename to Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs.meta index 980207bf2..38a2c9c91 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/GltfBufferWriter.cs.meta +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: d36812806fac1f041af501f1d2ad2dbb +guid: 8c397b99fe3e0db4fa7a25dc63fff6af MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs index d1a83bb60..637adabcc 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs @@ -7,7 +7,7 @@ namespace UniGLTF { public static class BlendShapeExporter { - public static gltfMorphTarget Export(GltfBufferWriter w, Vector3[] positions, Vector3[] normals, bool useSparse) + public static gltfMorphTarget Export(ExportingGltfData w, Vector3[] positions, Vector3[] normals, bool useSparse) { var accessorCount = positions.Length; if (normals != null && positions.Length != normals.Length) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs index 1fce0743b..b184fbfce 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs @@ -30,7 +30,7 @@ namespace UniGLTF m_normals[index] = normal; } - public gltfMorphTarget ToGltf(GltfBufferWriter w, bool useNormal, bool useSparse) + public gltfMorphTarget ToGltf(ExportingGltfData w, bool useNormal, bool useSparse) { return BlendShapeExporter.Export(w, m_positions, @@ -103,7 +103,7 @@ namespace UniGLTF m_weights.Add(new Vector4(boneWeight.weight0, boneWeight.weight1, boneWeight.weight2, boneWeight.weight3)); } - public glTFPrimitives ToGltfPrimitive(GltfBufferWriter w, int materialIndex, IEnumerable indices) + public glTFPrimitives ToGltfPrimitive(ExportingGltfData w, int materialIndex, IEnumerable indices) { var indicesAccessorIndex = w.ExtendBufferAndGetAccessorIndex(indices.Select(x => (uint)m_vertexIndexMap[x]).ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); var positions = m_positions.ToArray(); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs index ef4051563..215846c37 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs @@ -17,7 +17,7 @@ namespace UniGLTF /// /// /// - public static (glTFMesh, Dictionary) Export(GltfBufferWriter w, + public static (glTFMesh, Dictionary) Export(ExportingGltfData w, MeshExportInfo unityMesh, List unityMaterials, IAxisInverter axisInverter, GltfExportSettings settings) { diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs index 0f39041a4..c11537a80 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs @@ -24,7 +24,7 @@ namespace UniGLTF /// /// /// - public static (glTFMesh, Dictionary blendShapeIndexMap) Export(GltfBufferWriter w, + public static (glTFMesh, Dictionary blendShapeIndexMap) Export(ExportingGltfData w, MeshExportInfo unityMesh, List unityMaterials, IAxisInverter axisInverter, GltfExportSettings settings) { @@ -200,7 +200,7 @@ namespace UniGLTF return useSparse; } - static gltfMorphTarget ExportMorphTarget(GltfBufferWriter w, + static gltfMorphTarget ExportMorphTarget(ExportingGltfData w, Mesh mesh, int blendShapeIndex, bool useSparseAccessorForMorphTarget, bool exportOnlyBlendShapePosition, diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs index fe2ae721b..e3f90fb19 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs @@ -22,7 +22,7 @@ namespace UniGLTF /// /// /// gltf texture index - public static int PushGltfTexture(GltfBufferWriter w, Texture2D texture, ColorSpace textureColorSpace, ITextureSerializer textureSerializer) + public static int PushGltfTexture(ExportingGltfData w, Texture2D texture, ColorSpace textureColorSpace, ITextureSerializer textureSerializer) { var bytesWithMime = textureSerializer.ExportBytesWithMime(texture, textureColorSpace); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs index e62bddb18..c486c5c13 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs @@ -12,7 +12,7 @@ namespace UniGLTF { protected glTF glTF; - protected GltfBufferWriter _writer; + protected ExportingGltfData _writer; public GameObject Copy { @@ -72,7 +72,7 @@ namespace UniGLTF public gltfExporter(glTF gltf, GltfExportSettings settings) { glTF = gltf; - _writer = new GltfBufferWriter(gltf); + _writer = new ExportingGltfData (gltf); glTF.extensionsUsed.AddRange(ExtensionUsed); @@ -225,7 +225,7 @@ namespace UniGLTF // do nothing } - public virtual GltfBufferWriter Export(ITextureSerializer textureSerializer) + public virtual ExportingGltfData Export(ITextureSerializer textureSerializer) { Nodes = Copy.transform.Traverse() .Skip(1) // exclude root object for the symmetry with the importer diff --git a/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs b/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs index c71d32a5e..29e13aac0 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs @@ -30,7 +30,7 @@ namespace UniGLTF name = "hogefuga", }); - var parser = new GlbLowLevelParser("Test", new GltfBufferWriter(gltf).ToGlbBytes()); + var parser = new GlbLowLevelParser("Test", new ExportingGltfData (gltf).ToGlbBytes()); var data = parser.Parse(); Assert.AreEqual("FooBar", data.GLTF.textures[0].name); diff --git a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs index a5bd20602..a014e7fbb 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs @@ -118,7 +118,7 @@ namespace UniGLTF public void SharedVertexBufferTest() { var glTF = new glTF(); - var w = new GltfBufferWriter(glTF, 50 * 1024 * 1024); + var w = new ExportingGltfData (glTF, 50 * 1024 * 1024); var Materials = new List{ new Material(Shader.Find("Standard")), // A @@ -167,7 +167,7 @@ namespace UniGLTF public void DividedVertexBufferTest() { var glTF = new glTF(); - var w = new GltfBufferWriter(glTF, 50 * 1024 * 1024); + var w = new ExportingGltfData (glTF, 50 * 1024 * 1024); var Materials = new List{ new Material(Shader.Find("Standard")), // A diff --git a/Assets/VRM/Editor/Format/VRMEditorExporter.cs b/Assets/VRM/Editor/Format/VRMEditorExporter.cs index 27cee46b5..419912b1b 100644 --- a/Assets/VRM/Editor/Format/VRMEditorExporter.cs +++ b/Assets/VRM/Editor/Format/VRMEditorExporter.cs @@ -223,7 +223,7 @@ namespace VRM // 出力 var sw = System.Diagnostics.Stopwatch.StartNew(); var gltf = new UniGLTF.glTF(); - GltfBufferWriter writer = default; + ExportingGltfData writer = default; using (var exporter = new VRMExporter(gltf, settings.MeshExportSettings)) { exporter.Prepare(target); diff --git a/Assets/VRM/Runtime/IO/VRMExporter.cs b/Assets/VRM/Runtime/IO/VRMExporter.cs index 98b1e19cc..63903b977 100644 --- a/Assets/VRM/Runtime/IO/VRMExporter.cs +++ b/Assets/VRM/Runtime/IO/VRMExporter.cs @@ -12,7 +12,7 @@ namespace VRM { public const Axes Vrm0xSpecificationInverseAxis = Axes.Z; - public static GltfBufferWriter Export(GltfExportSettings configuration, GameObject go, ITextureSerializer textureSerializer) + public static ExportingGltfData Export(GltfExportSettings configuration, GameObject go, ITextureSerializer textureSerializer) { var gltf = new glTF(); using (var exporter = new VRMExporter(gltf, configuration)) diff --git a/Assets/VRM10/Runtime/IO/Model/MeshWriter.cs b/Assets/VRM10/Runtime/IO/Model/MeshWriter.cs index 3dc82010c..bf16b16b6 100644 --- a/Assets/VRM10/Runtime/IO/Model/MeshWriter.cs +++ b/Assets/VRM10/Runtime/IO/Model/MeshWriter.cs @@ -66,9 +66,8 @@ namespace UniVRM10 /// /// static IEnumerable ExportMeshDivided(this VrmLib.Mesh mesh, List materials, - GltfBufferWriter writer, ExportArgs option) + ExportingGltfData writer, ExportArgs option) { - var bufferIndex = 0; var usedIndices = new List(); var meshIndices = SpanLike.CopyFrom(mesh.IndexBuffer.GetAsIntArray()); var positions = mesh.VertexBuffer.Positions.GetSpan().ToArray(); @@ -161,7 +160,7 @@ namespace UniVRM10 /// /// /// - public static glTFMesh ExportMeshGroup(this MeshGroup src, List materials, GltfBufferWriter writer, ExportArgs option) + public static glTFMesh ExportMeshGroup(this MeshGroup src, List materials, ExportingGltfData writer, ExportArgs option) { var gltfMesh = new glTFMesh { diff --git a/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs b/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs index 440bb1309..f79c2547d 100644 --- a/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs +++ b/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs @@ -57,7 +57,7 @@ namespace UniVRM10 return asset; } - public static IEnumerable ExportMeshes(List groups, List materials, GltfBufferWriter w, ExportArgs option) + public static IEnumerable ExportMeshes(List groups, List materials, ExportingGltfData w, ExportArgs option) { foreach (var group in groups) { diff --git a/Assets/VRM10/Runtime/IO/Vrm10Storage.cs b/Assets/VRM10/Runtime/IO/Vrm10Storage.cs index 39b902e99..f863d017a 100644 --- a/Assets/VRM10/Runtime/IO/Vrm10Storage.cs +++ b/Assets/VRM10/Runtime/IO/Vrm10Storage.cs @@ -10,7 +10,7 @@ using VrmLib; namespace UniVRM10 { - public class Vrm10Storage : GltfBufferWriter + public class Vrm10Storage : ExportingGltfData { UniGLTF.GltfData m_data; public UniGLTF.glTF Gltf => m_data.GLTF; From 1eec47deddeafee22d7caf715796cdd2262969f5 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 21:02:09 +0900 Subject: [PATCH 14/15] Update exporter interface. use ExportingGltfData --- .../UniGLTF/ExportDialog/GltfExportWindow.cs | 11 ++-- .../Runtime/UniGLTF/IO/ExportingGltfData.cs | 5 +- .../Runtime/UniGLTF/IO/gltfExporter.cs | 49 ++++++++--------- .../UniGLTF/EditorTextureSerializerTests.cs | 9 ++-- .../UniGLTF/Tests/UniGLTF/GlbParserTests.cs | 11 ++-- Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs | 8 +-- Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs | 33 ++++++------ Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs | 53 ++++++++++--------- Assets/VRM/Editor/Format/VRMEditorExporter.cs | 9 ++-- Assets/VRM/Runtime/IO/VRMExporter.cs | 17 +++--- Assets/VRM10/Runtime/IO/Vrm10Storage.cs | 9 ++-- 11 files changed, 105 insertions(+), 109 deletions(-) diff --git a/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs b/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs index 7a4f27459..d567ef00a 100644 --- a/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs +++ b/Assets/UniGLTF/Editor/UniGLTF/ExportDialog/GltfExportWindow.cs @@ -100,22 +100,21 @@ namespace UniGLTF default: throw new System.Exception(); } - var gltf = new glTF(); - ExportingGltfData writer = default; - using (var exporter = new gltfExporter(gltf, Settings)) + var data = new ExportingGltfData(); + using (var exporter = new gltfExporter(data, Settings)) { exporter.Prepare(State.ExportRoot); - writer = exporter.Export(new EditorTextureSerializer()); + exporter.Export(new EditorTextureSerializer()); } if (isGlb) { - var bytes = writer.ToGlbBytes(); + var bytes = data.ToGlbBytes(); File.WriteAllBytes(path, bytes); } else { - var (json, buffers) = writer.ToGltf(path); + var (json, buffers) = data.ToGltf(path); // without BOM var encoding = new System.Text.UTF8Encoding(false); File.WriteAllText(path, json, encoding); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs index 99dd7a5a5..faed324c7 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/ExportingGltfData.cs @@ -7,17 +7,16 @@ namespace UniGLTF { public class ExportingGltfData { - readonly glTF _gltf; + readonly glTF _gltf = new glTF(); public glTF GLTF => _gltf; - public ExportingGltfData(glTF gltf, int reserved = default) + public ExportingGltfData(int reserved = default) { if (reserved == 0) { reserved = 50 * 1024 * 1024; } - _gltf = gltf; // glb body と gltf の bin 兼用 _gltf.buffers.Add(new glTFBuffer(new ArrayByteBuffer(new byte[reserved]))); } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs index c486c5c13..11552c84a 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/gltfExporter.cs @@ -10,9 +10,9 @@ namespace UniGLTF { public class gltfExporter : IDisposable { - protected glTF glTF; + protected ExportingGltfData _data; - protected ExportingGltfData _writer; + protected glTF _gltf => _data.GLTF; public GameObject Copy { @@ -69,14 +69,13 @@ namespace UniGLTF GltfExportSettings m_settings; - public gltfExporter(glTF gltf, GltfExportSettings settings) + public gltfExporter(ExportingGltfData data, GltfExportSettings settings) { - glTF = gltf; - _writer = new ExportingGltfData (gltf); + _data = data; - glTF.extensionsUsed.AddRange(ExtensionUsed); + _gltf.extensionsUsed.AddRange(ExtensionUsed); - glTF.asset = new glTFAssets + _gltf.asset = new glTFAssets { generator = "UniGLTF-" + UniGLTFVersion.VERSION, version = "2.0", @@ -225,7 +224,7 @@ namespace UniGLTF // do nothing } - public virtual ExportingGltfData Export(ITextureSerializer textureSerializer) + public virtual void Export(ITextureSerializer textureSerializer) { Nodes = Copy.transform.Traverse() .Skip(1) // exclude root object for the symmetry with the importer @@ -240,7 +239,7 @@ namespace UniGLTF m_textureExporter = new TextureExporter(textureSerializer); var materialExporter = CreateMaterialExporter(); - glTF.materials = Materials.Select(x => materialExporter.ExportMaterial(x, TextureExporter, m_settings)).ToList(); + _gltf.materials = Materials.Select(x => materialExporter.ExportMaterial(x, TextureExporter, m_settings)).ToList(); #endregion #region Meshes @@ -253,10 +252,10 @@ namespace UniGLTF } var (gltfMesh, blendShapeIndexMap) = m_settings.DivideVertexBuffer - ? MeshExporter_DividedVertexBuffer.Export(_writer, unityMesh, Materials, m_settings.InverseAxis.Create(), m_settings) - : MeshExporter_SharedVertexBuffer.Export(_writer, unityMesh, Materials, m_settings.InverseAxis.Create(), m_settings) + ? MeshExporter_DividedVertexBuffer.Export(_data, unityMesh, Materials, m_settings.InverseAxis.Create(), m_settings) + : MeshExporter_SharedVertexBuffer.Export(_data, unityMesh, Materials, m_settings.InverseAxis.Create(), m_settings) ; - glTF.meshes.Add(gltfMesh); + _gltf.meshes.Add(gltfMesh); Meshes.Add(unityMesh.Mesh); if (!MeshBlendShapeIndexMap.ContainsKey(unityMesh.Mesh)) { @@ -276,9 +275,9 @@ namespace UniGLTF foreach (var node in Nodes) { var gltfNode = ExportNode(node, Nodes, uniqueUnityMeshes, skins); - glTF.nodes.Add(gltfNode); + _gltf.nodes.Add(gltfNode); } - glTF.scenes = new List + _gltf.scenes = new List { new gltfScene { @@ -293,20 +292,20 @@ namespace UniGLTF if (uniqueBones != null && renderer is SkinnedMeshRenderer smr) { var matrices = x.GetBindPoses().Select(m_settings.InverseAxis.Create().InvertMat4).ToArray(); - var accessor = _writer.ExtendBufferAndGetAccessorIndex(matrices, glBufferTarget.NONE); + var accessor = _data.ExtendBufferAndGetAccessorIndex(matrices, glBufferTarget.NONE); var skin = new glTFSkin { inverseBindMatrices = accessor, joints = uniqueBones.Select(y => Nodes.IndexOf(y)).ToArray(), skeleton = Nodes.IndexOf(smr.rootBone), }; - var skinIndex = glTF.skins.Count; - glTF.skins.Add(skin); + var skinIndex = _gltf.skins.Count; + _gltf.skins.Add(skin); foreach (var z in Nodes.Where(y => y.Has(renderer))) { var nodeIndex = Nodes.IndexOf(z); - var node = glTF.nodes[nodeIndex]; + var node = _gltf.nodes[nodeIndex]; node.skin = skinIndex; } } @@ -339,14 +338,14 @@ namespace UniGLTF { var sampler = animationWithCurve.Animation.samplers[kv.Key]; - var inputAccessorIndex = _writer.ExtendBufferAndGetAccessorIndex(kv.Value.Input); + var inputAccessorIndex = _data.ExtendBufferAndGetAccessorIndex(kv.Value.Input); sampler.input = inputAccessorIndex; - var outputAccessorIndex = _writer.ExtendBufferAndGetAccessorIndex(kv.Value.Output); + var outputAccessorIndex = _data.ExtendBufferAndGetAccessorIndex(kv.Value.Output); sampler.output = outputAccessorIndex; // modify accessors - var outputAccessor = glTF.accessors[outputAccessorIndex]; + var outputAccessor = _gltf.accessors[outputAccessorIndex]; var channel = animationWithCurve.Animation.channels.First(x => x.sampler == kv.Key); switch (glTFAnimationTarget.GetElementCount(channel.target.path)) { @@ -369,7 +368,7 @@ namespace UniGLTF } } animationWithCurve.Animation.name = clip.name; - glTF.animations.Add(animationWithCurve.Animation); + _gltf.animations.Add(animationWithCurve.Animation); } } @@ -383,12 +382,10 @@ namespace UniGLTF for (var exportedTextureIdx = 0; exportedTextureIdx < exported.Count; ++exportedTextureIdx) { var (unityTexture, colorSpace) = exported[exportedTextureIdx]; - GltfTextureExporter.PushGltfTexture(_writer, unityTexture, colorSpace, textureSerializer); + GltfTextureExporter.PushGltfTexture(_data, unityTexture, colorSpace, textureSerializer); } - FixName(glTF); - - return _writer; + FixName(_gltf); } /// diff --git a/Assets/UniGLTF/Tests/UniGLTF/EditorTextureSerializerTests.cs b/Assets/UniGLTF/Tests/UniGLTF/EditorTextureSerializerTests.cs index 71cd70566..463da1c2e 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/EditorTextureSerializerTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/EditorTextureSerializerTests.cs @@ -122,8 +122,8 @@ namespace UniGLTF root.GetComponent().sharedMaterial = mat; // Export glTF - var gltf = new glTF(); - using (var exporter = new gltfExporter(gltf, new GltfExportSettings + var data = new ExportingGltfData(); + using (var exporter = new gltfExporter(data, new GltfExportSettings { InverseAxis = Axes.X, ExportOnlyBlendShapePosition = false, @@ -134,6 +134,7 @@ namespace UniGLTF exporter.Prepare(root); exporter.Export(new EditorTextureSerializer()); } + var gltf = data.GLTF; Assert.AreEqual(1, gltf.images.Count); var exportedImage = gltf.images[0]; Assert.AreEqual("image/png", exportedImage.mimeType); @@ -142,10 +143,10 @@ namespace UniGLTF UnityEngine.Object.DestroyImmediate(mat); UnityEngine.Object.DestroyImmediate(root); - var data = GltfData.CreateFromGltfDataForTest(gltf); + var parsed = GltfData.CreateFromGltfDataForTest(gltf); // Extract Image to Texture2D - var exportedBytes = data.GetViewBytes(exportedImage.bufferView).ToArray(); + var exportedBytes = parsed.GetViewBytes(exportedImage.bufferView).ToArray(); var exportedTexture = new Texture2D(2, 2, TextureFormat.ARGB32, mipChain: false, linear: false); Assert.IsTrue(exportedTexture.LoadImage(exportedBytes)); // Always true ? Assert.AreEqual(srcTex.width, exportedTexture.width); diff --git a/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs b/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs index 29e13aac0..f8265df94 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/GlbParserTests.cs @@ -8,7 +8,8 @@ namespace UniGLTF [Test] public void TextureNameUniqueness() { - var gltf = new glTF(); + var data = new ExportingGltfData(); + var gltf = data.GLTF; gltf.asset.version = "2.0"; gltf.buffers.Add(new glTFBuffer(new ArrayByteBuffer(Array.Empty()))); gltf.textures.Add(new glTFTexture @@ -30,12 +31,12 @@ namespace UniGLTF name = "hogefuga", }); - var parser = new GlbLowLevelParser("Test", new ExportingGltfData (gltf).ToGlbBytes()); - var data = parser.Parse(); + var parser = new GlbLowLevelParser("Test", data.ToGlbBytes()); + var parsed = parser.Parse(); - Assert.AreEqual("FooBar", data.GLTF.textures[0].name); + Assert.AreEqual("FooBar", parsed.GLTF.textures[0].name); // NOTE: 大文字小文字が違うだけの名前は、同一としてみなされ、Suffix が付く。 - Assert.AreEqual("foobar__UNIGLTF__DUPLICATED__2", data.GLTF.textures[1].name); + Assert.AreEqual("foobar__UNIGLTF__DUPLICATED__2", parsed.GLTF.textures[1].name); } } } \ No newline at end of file diff --git a/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs b/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs index f89103bf1..68d4c0c91 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/GltfLoadTests.cs @@ -57,13 +57,13 @@ namespace UniGLTF static Byte[] Export(GameObject root) { - var gltf = new glTF(); - using (var exporter = new gltfExporter(gltf, new GltfExportSettings())) + var data = new ExportingGltfData(); + using (var exporter = new gltfExporter(data, new GltfExportSettings())) { exporter.Prepare(root); - var w = exporter.Export(new EditorTextureSerializer()); - return w.ToGlbBytes(); + exporter.Export(new EditorTextureSerializer()); } + return data.ToGlbBytes(); } // Unsolved Animation Export issue diff --git a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs index a014e7fbb..7d75ea89f 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/MeshTests.cs @@ -117,8 +117,7 @@ namespace UniGLTF [Test] public void SharedVertexBufferTest() { - var glTF = new glTF(); - var w = new ExportingGltfData (glTF, 50 * 1024 * 1024); + var data = new ExportingGltfData(50 * 1024 * 1024); var Materials = new List{ new Material(Shader.Find("Standard")), // A @@ -134,13 +133,14 @@ namespace UniGLTF var unityMesh = MeshExportList.Create(go); var (gltfMesh, blendShapeIndexMap) = meshExportSettings.DivideVertexBuffer - ? MeshExporter_DividedVertexBuffer.Export(w, unityMesh, Materials, axisInverter, meshExportSettings) - : MeshExporter_SharedVertexBuffer.Export(w, unityMesh, Materials, axisInverter, meshExportSettings) + ? MeshExporter_DividedVertexBuffer.Export(data, unityMesh, Materials, axisInverter, meshExportSettings) + : MeshExporter_SharedVertexBuffer.Export(data, unityMesh, Materials, axisInverter, meshExportSettings) ; - var data = GltfData.CreateFromGltfDataForTest(glTF); + + var parsed = GltfData.CreateFromGltfDataForTest(data.GLTF); { - var indices = data.GetIndices(gltfMesh.primitives[0].indices); + var indices = parsed.GetIndices(gltfMesh.primitives[0].indices); Assert.AreEqual(0, indices[0]); Assert.AreEqual(1, indices[1]); Assert.AreEqual(5, indices[2]); @@ -150,7 +150,7 @@ namespace UniGLTF } { - var indices = data.GetIndices(gltfMesh.primitives[1].indices); + var indices = parsed.GetIndices(gltfMesh.primitives[1].indices); Assert.AreEqual(1, indices[0]); Assert.AreEqual(2, indices[1]); Assert.AreEqual(4, indices[2]); @@ -159,15 +159,14 @@ namespace UniGLTF Assert.AreEqual(3, indices[5]); } - var positions = data.GetArrayFromAccessor(gltfMesh.primitives[0].attributes.POSITION); + var positions = parsed.GetArrayFromAccessor(gltfMesh.primitives[0].attributes.POSITION); Assert.AreEqual(6, positions.Length); } [Test] public void DividedVertexBufferTest() { - var glTF = new glTF(); - var w = new ExportingGltfData (glTF, 50 * 1024 * 1024); + var data = new ExportingGltfData(50 * 1024 * 1024); var Materials = new List{ new Material(Shader.Find("Standard")), // A @@ -183,13 +182,13 @@ namespace UniGLTF var unityMesh = MeshExportList.Create(go); var (gltfMesh, blendShapeIndexMap) = meshExportSettings.DivideVertexBuffer - ? MeshExporter_DividedVertexBuffer.Export(w, unityMesh, Materials, axisInverter, meshExportSettings) - : MeshExporter_SharedVertexBuffer.Export(w, unityMesh, Materials, axisInverter, meshExportSettings) + ? MeshExporter_DividedVertexBuffer.Export(data, unityMesh, Materials, axisInverter, meshExportSettings) + : MeshExporter_SharedVertexBuffer.Export(data, unityMesh, Materials, axisInverter, meshExportSettings) ; - var data = GltfData.CreateFromGltfDataForTest(glTF); + var parsed = GltfData.CreateFromGltfDataForTest(data.GLTF); { - var indices = data.GetIndices(gltfMesh.primitives[0].indices); + var indices = parsed.GetIndices(gltfMesh.primitives[0].indices); Assert.AreEqual(0, indices[0]); Assert.AreEqual(1, indices[1]); Assert.AreEqual(3, indices[2]); @@ -198,12 +197,12 @@ namespace UniGLTF Assert.AreEqual(2, indices[5]); } { - var positions = data.GetArrayFromAccessor(gltfMesh.primitives[0].attributes.POSITION); + var positions = parsed.GetArrayFromAccessor(gltfMesh.primitives[0].attributes.POSITION); Assert.AreEqual(4, positions.Length); } { - var indices = data.GetIndices(gltfMesh.primitives[1].indices); + var indices = parsed.GetIndices(gltfMesh.primitives[1].indices); Assert.AreEqual(0, indices[0]); Assert.AreEqual(1, indices[1]); Assert.AreEqual(3, indices[2]); @@ -212,7 +211,7 @@ namespace UniGLTF Assert.AreEqual(2, indices[5]); } { - var positions = data.GetArrayFromAccessor(gltfMesh.primitives[1].attributes.POSITION); + var positions = parsed.GetArrayFromAccessor(gltfMesh.primitives[1].attributes.POSITION); Assert.AreEqual(4, positions.Length); } } diff --git a/Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs b/Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs index 985a5e8c6..d521af24b 100644 --- a/Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs +++ b/Assets/UniGLTF/Tests/UniGLTF/UniGLTFTests.cs @@ -100,25 +100,25 @@ namespace UniGLTF var go = CreateSimpleScene(); // export - var gltf = new glTF(); + var data = new ExportingGltfData(); string json = null; - using (var exporter = new gltfExporter(gltf, new GltfExportSettings())) + using (var exporter = new gltfExporter(data, new GltfExportSettings())) { exporter.Prepare(go); exporter.Export(new EditorTextureSerializer()); // remove empty buffer - gltf.buffers.Clear(); + data.GLTF.buffers.Clear(); - json = gltf.ToJson(); + json = data.GLTF.ToJson(); } // parse - var data = new JsonWithStorageParser(json).Parse(); + var parsed = new JsonWithStorageParser(json).Parse(); // import - using (var context = new ImporterContext(data)) + using (var context = new ImporterContext(parsed)) using (var loaded = context.Load()) { AssertAreEqual(go.transform, loaded.transform); @@ -293,14 +293,14 @@ namespace UniGLTF [Test] public void GlTFToJsonTest() { - var gltf = new glTF(); - using (var exporter = new gltfExporter(gltf, new GltfExportSettings())) + var data = new ExportingGltfData(); + using (var exporter = new gltfExporter(data, new GltfExportSettings())) { exporter.Prepare(CreateSimpleScene()); exporter.Export(new EditorTextureSerializer()); } - var expected = gltf.ToJson().ParseAsJson(); + var expected = data.GLTF.ToJson().ParseAsJson(); expected.AddKey(Utf8String.From("meshes")); expected.AddValue(default(ArraySegment), ValueNodeType.Array); expected["meshes"].AddValue(default(ArraySegment), ValueNodeType.Object); @@ -334,7 +334,7 @@ namespace UniGLTF primitive["targets"][1].AddKey(Utf8String.From("TANGENT")); primitive["targets"][1].AddValue(Utf8String.From("0").Bytes, ValueNodeType.Integer); - gltf.meshes.Add(new glTFMesh("test") + data.GLTF.meshes.Add(new glTFMesh("test") { primitives = new List { @@ -362,7 +362,7 @@ namespace UniGLTF } } }); - var actual = gltf.ToJson().ParseAsJson(); + var actual = data.GLTF.ToJson().ParseAsJson(); Assert.AreEqual(expected, actual); } @@ -528,9 +528,10 @@ namespace UniGLTF } // export - var gltf = new glTF(); + var data = new ExportingGltfData(); + var gltf = data.GLTF; var json = default(string); - using (var exporter = new gltfExporter(gltf, new GltfExportSettings())) + using (var exporter = new gltfExporter(data, new GltfExportSettings())) { exporter.Prepare(go); exporter.Export(new EditorTextureSerializer()); @@ -553,9 +554,9 @@ namespace UniGLTF // import { var storage = new SimpleStorage(new ArraySegment(new byte[1024 * 1024])); - var data = new JsonWithStorageParser(json, storage).Parse(); + var parsed = new JsonWithStorageParser(json, storage).Parse(); - using (var context = new ImporterContext(data)) + using (var context = new ImporterContext(parsed)) using (var loaded = context.Load()) { var importedRed = loaded.transform.GetChild(0); @@ -573,10 +574,10 @@ namespace UniGLTF // import new version { var storage = new SimpleStorage(new ArraySegment(new byte[1024 * 1024])); - var data = new JsonWithStorageParser(json, storage).Parse(); + var parsed = new JsonWithStorageParser(json, storage).Parse(); //Debug.LogFormat("{0}", context.Json); - using (var context = new ImporterContext(data)) + using (var context = new ImporterContext(parsed)) using (var loaded = context.Load()) { var importedRed = loaded.transform.GetChild(0); @@ -610,9 +611,10 @@ namespace UniGLTF } // export - var gltf = new glTF(); + var data = new ExportingGltfData(); + var gltf = data.GLTF; string json; - using (var exporter = new gltfExporter(gltf, new GltfExportSettings())) + using (var exporter = new gltfExporter(data, new GltfExportSettings())) { exporter.Prepare(go); exporter.Export(new EditorTextureSerializer()); @@ -627,9 +629,9 @@ namespace UniGLTF // import { var storage = new SimpleStorage(new ArraySegment(new byte[1024 * 1024])); - var data = new JsonWithStorageParser(json, storage).Parse(); + var parsed = new JsonWithStorageParser(json, storage).Parse(); - using (var context = new ImporterContext(data)) + using (var context = new ImporterContext(parsed)) using (var loaded = context.Load()) { Assert.AreEqual(1, loaded.transform.GetChildren().Count()); @@ -674,9 +676,10 @@ namespace UniGLTF Assert.True(vs.All(x => x.CanExport)); // export - var gltf = new glTF(); + var data = new ExportingGltfData(); + var gltf = data.GLTF; string json; - using (var exporter = new gltfExporter(gltf, new GltfExportSettings())) + using (var exporter = new gltfExporter(data, new GltfExportSettings())) { exporter.Prepare(root); exporter.Export(new EditorTextureSerializer()); @@ -692,9 +695,9 @@ namespace UniGLTF // import { var storage = new SimpleStorage(new ArraySegment(new byte[1024 * 1024])); - var data = new JsonWithStorageParser(json, storage).Parse(); + var parsed = new JsonWithStorageParser(json, storage).Parse(); - using (var context = new ImporterContext(data)) + using (var context = new ImporterContext(parsed)) using (var loaded = context.Load()) { Assert.AreEqual(2, loaded.transform.GetChildren().Count()); diff --git a/Assets/VRM/Editor/Format/VRMEditorExporter.cs b/Assets/VRM/Editor/Format/VRMEditorExporter.cs index 419912b1b..4003ba880 100644 --- a/Assets/VRM/Editor/Format/VRMEditorExporter.cs +++ b/Assets/VRM/Editor/Format/VRMEditorExporter.cs @@ -222,14 +222,13 @@ namespace VRM // 出力 var sw = System.Diagnostics.Stopwatch.StartNew(); - var gltf = new UniGLTF.glTF(); - ExportingGltfData writer = default; - using (var exporter = new VRMExporter(gltf, settings.MeshExportSettings)) + var data = new UniGLTF.ExportingGltfData(); + using (var exporter = new VRMExporter(data, settings.MeshExportSettings)) { exporter.Prepare(target); - writer = exporter.Export(new EditorTextureSerializer()); + exporter.Export(new EditorTextureSerializer()); } - var bytes = writer.ToGlbBytes(); + var bytes = data.ToGlbBytes(); Debug.LogFormat("Export elapsed {0}", sw.Elapsed); return bytes; } diff --git a/Assets/VRM/Runtime/IO/VRMExporter.cs b/Assets/VRM/Runtime/IO/VRMExporter.cs index 63903b977..741d31ad9 100644 --- a/Assets/VRM/Runtime/IO/VRMExporter.cs +++ b/Assets/VRM/Runtime/IO/VRMExporter.cs @@ -12,26 +12,27 @@ namespace VRM { public const Axes Vrm0xSpecificationInverseAxis = Axes.Z; - public static ExportingGltfData Export(GltfExportSettings configuration, GameObject go, ITextureSerializer textureSerializer) + public static ExportingGltfData Export(GltfExportSettings configuration, GameObject go, ITextureSerializer textureSerializer) { - var gltf = new glTF(); - using (var exporter = new VRMExporter(gltf, configuration)) + var data = new ExportingGltfData(); + using (var exporter = new VRMExporter(data, configuration)) { exporter.Prepare(go); - return exporter.Export(textureSerializer); + exporter.Export(textureSerializer); } + return data; } public readonly VRM.glTF_VRM_extensions VRM = new glTF_VRM_extensions(); - public VRMExporter(glTF gltf, GltfExportSettings exportSettings) : base(gltf, exportSettings) + public VRMExporter(ExportingGltfData data, GltfExportSettings exportSettings) : base(data, exportSettings) { if (exportSettings == null || exportSettings.InverseAxis != Vrm0xSpecificationInverseAxis) { throw new Exception($"VRM specification requires InverseAxis settings as {Vrm0xSpecificationInverseAxis}"); } - gltf.extensionsUsed.Add(glTF_VRM_extensions.ExtensionName); + _gltf.extensionsUsed.Add(glTF_VRM_extensions.ExtensionName); } protected override IMaterialExporter CreateMaterialExporter() @@ -117,7 +118,7 @@ namespace VRM VRM.meta.title = meta.Title; if (meta.Thumbnail != null) { - VRM.meta.texture = GltfTextureExporter.PushGltfTexture(_writer, meta.Thumbnail, ColorSpace.sRGB, textureSerializer); + VRM.meta.texture = GltfTextureExporter.PushGltfTexture(_data, meta.Thumbnail, ColorSpace.sRGB, textureSerializer); } VRM.meta.licenseType = meta.LicenseType; @@ -212,7 +213,7 @@ namespace VRM var f = new JsonFormatter(); VRMSerializer.Serialize(f, VRM); var bytes = f.GetStoreBytes(); - glTFExtensionExport.GetOrCreate(ref glTF.extensions).Add("VRM", bytes); + glTFExtensionExport.GetOrCreate(ref _gltf.extensions).Add("VRM", bytes); } } } diff --git a/Assets/VRM10/Runtime/IO/Vrm10Storage.cs b/Assets/VRM10/Runtime/IO/Vrm10Storage.cs index f863d017a..3bccfbc21 100644 --- a/Assets/VRM10/Runtime/IO/Vrm10Storage.cs +++ b/Assets/VRM10/Runtime/IO/Vrm10Storage.cs @@ -10,7 +10,7 @@ using VrmLib; namespace UniVRM10 { - public class Vrm10Storage : ExportingGltfData + public class Vrm10Storage : ExportingGltfData { UniGLTF.GltfData m_data; public UniGLTF.glTF Gltf => m_data.GLTF; @@ -24,10 +24,7 @@ namespace UniVRM10 /// /// for export /// - public Vrm10Storage() : base(new glTF - { - extensionsUsed = new List(), - }) + public Vrm10Storage() { m_data = new GltfData( string.Empty, @@ -48,7 +45,7 @@ namespace UniVRM10 /// /// /// - public Vrm10Storage(UniGLTF.GltfData data) : base(data.GLTF) + public Vrm10Storage(UniGLTF.GltfData data) { m_data = data; From 1070168d64833400edd8e9c371fac6b5be7d3538 Mon Sep 17 00:00:00 2001 From: ousttrue Date: Tue, 26 Oct 2021 21:05:42 +0900 Subject: [PATCH 15/15] w to data --- .../UniGLTF/IO/MeshIO/BlendShapeExporter.cs | 18 +++++------ .../UniGLTF/IO/MeshIO/MeshExportUtil.cs | 18 +++++------ .../MeshExporter_DividedVertexBuffer.cs | 6 ++-- .../MeshIO/MeshExporter_SharedVertexBuffer.cs | 30 +++++++++---------- .../IO/TextureIO/GltfTextureExporter.cs | 16 +++++----- Assets/VRM10/Runtime/IO/Vrm10Exporter.cs | 4 +-- 6 files changed, 46 insertions(+), 46 deletions(-) diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs index 637adabcc..205b630ed 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/BlendShapeExporter.cs @@ -7,7 +7,7 @@ namespace UniGLTF { public static class BlendShapeExporter { - public static gltfMorphTarget Export(ExportingGltfData w, Vector3[] positions, Vector3[] normals, bool useSparse) + public static gltfMorphTarget Export(ExportingGltfData data, Vector3[] positions, Vector3[] normals, bool useSparse) { var accessorCount = positions.Length; if (normals != null && positions.Length != normals.Length) @@ -44,8 +44,8 @@ namespace UniGLTF var positionAccessorIndex = -1; if (sparseIndices.Length > 0) { - var sparseIndicesViewIndex = w.ExtendBufferAndGetViewIndex(sparseIndices); - positionAccessorIndex = w.ExtendSparseBufferAndGetAccessorIndex(accessorCount, + var sparseIndicesViewIndex = data.ExtendBufferAndGetViewIndex(sparseIndices); + positionAccessorIndex = data.ExtendSparseBufferAndGetAccessorIndex(accessorCount, sparseIndices.Select(x => positions[x]).ToArray(), sparseIndices, sparseIndicesViewIndex, glBufferTarget.NONE); } @@ -57,8 +57,8 @@ namespace UniGLTF var sparseNormalIndices = Enumerable.Range(0, positions.Length).Where(x => normals[x] != Vector3.zero).ToArray(); if (sparseNormalIndices.Length > 0) { - var sparseNormalIndicesViewIndex = w.ExtendBufferAndGetViewIndex(sparseNormalIndices); - normalAccessorIndex = w.ExtendSparseBufferAndGetAccessorIndex(accessorCount, + var sparseNormalIndicesViewIndex = data.ExtendBufferAndGetViewIndex(sparseNormalIndices); + normalAccessorIndex = data.ExtendSparseBufferAndGetAccessorIndex(accessorCount, sparseNormalIndices.Select(x => normals[x]).ToArray(), sparseNormalIndices, sparseNormalIndicesViewIndex, glBufferTarget.NONE); } @@ -73,15 +73,15 @@ namespace UniGLTF else { // position - var positionAccessorIndex = w.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); - w.GLTF.accessors[positionAccessorIndex].min = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Min(a.x, b.x), Math.Min(a.y, b.y), Mathf.Min(a.z, b.z))).ToArray(); - w.GLTF.accessors[positionAccessorIndex].max = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Max(a.x, b.x), Math.Max(a.y, b.y), Mathf.Max(a.z, b.z))).ToArray(); + var positionAccessorIndex = data.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); + data.GLTF.accessors[positionAccessorIndex].min = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Min(a.x, b.x), Math.Min(a.y, b.y), Mathf.Min(a.z, b.z))).ToArray(); + data.GLTF.accessors[positionAccessorIndex].max = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Max(a.x, b.x), Math.Max(a.y, b.y), Mathf.Max(a.z, b.z))).ToArray(); // normal var normalAccessorIndex = -1; if (normals != null) { - normalAccessorIndex = w.ExtendBufferAndGetAccessorIndex(normals, glBufferTarget.ARRAY_BUFFER); + normalAccessorIndex = data.ExtendBufferAndGetAccessorIndex(normals, glBufferTarget.ARRAY_BUFFER); } return new gltfMorphTarget diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs index b184fbfce..2f888df29 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExportUtil.cs @@ -30,9 +30,9 @@ namespace UniGLTF m_normals[index] = normal; } - public gltfMorphTarget ToGltf(ExportingGltfData w, bool useNormal, bool useSparse) + public gltfMorphTarget ToGltf(ExportingGltfData data, bool useNormal, bool useSparse) { - return BlendShapeExporter.Export(w, + return BlendShapeExporter.Export(data, m_positions, useNormal ? m_normals : null, useSparse); @@ -103,24 +103,24 @@ namespace UniGLTF m_weights.Add(new Vector4(boneWeight.weight0, boneWeight.weight1, boneWeight.weight2, boneWeight.weight3)); } - public glTFPrimitives ToGltfPrimitive(ExportingGltfData w, int materialIndex, IEnumerable indices) + public glTFPrimitives ToGltfPrimitive(ExportingGltfData data, int materialIndex, IEnumerable indices) { - var indicesAccessorIndex = w.ExtendBufferAndGetAccessorIndex(indices.Select(x => (uint)m_vertexIndexMap[x]).ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); + var indicesAccessorIndex = data.ExtendBufferAndGetAccessorIndex(indices.Select(x => (uint)m_vertexIndexMap[x]).ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); var positions = m_positions.ToArray(); - var positionAccessorIndex = w.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); + var positionAccessorIndex = data.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); var normals = m_normals.ToArray(); - var normalAccessorIndex = w.ExtendBufferAndGetAccessorIndex(normals, glBufferTarget.ARRAY_BUFFER); - var uvAccessorIndex0 = w.ExtendBufferAndGetAccessorIndex(m_uv.ToArray(), glBufferTarget.ARRAY_BUFFER); + var normalAccessorIndex = data.ExtendBufferAndGetAccessorIndex(normals, glBufferTarget.ARRAY_BUFFER); + var uvAccessorIndex0 = data.ExtendBufferAndGetAccessorIndex(m_uv.ToArray(), glBufferTarget.ARRAY_BUFFER); int? jointsAccessorIndex = default; if (m_joints != null) { - jointsAccessorIndex = w.ExtendBufferAndGetAccessorIndex(m_joints.ToArray(), glBufferTarget.ARRAY_BUFFER); + jointsAccessorIndex = data.ExtendBufferAndGetAccessorIndex(m_joints.ToArray(), glBufferTarget.ARRAY_BUFFER); } int? weightAccessorIndex = default; if (m_weights != null) { - weightAccessorIndex = w.ExtendBufferAndGetAccessorIndex(m_weights.ToArray(), glBufferTarget.ARRAY_BUFFER); + weightAccessorIndex = data.ExtendBufferAndGetAccessorIndex(m_weights.ToArray(), glBufferTarget.ARRAY_BUFFER); } var primitive = new glTFPrimitives diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs index 215846c37..9e3ce0588 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_DividedVertexBuffer.cs @@ -17,7 +17,7 @@ namespace UniGLTF /// /// /// - public static (glTFMesh, Dictionary) Export(ExportingGltfData w, + public static (glTFMesh, Dictionary) Export(ExportingGltfData data, MeshExportInfo unityMesh, List unityMaterials, IAxisInverter axisInverter, GltfExportSettings settings) { @@ -84,7 +84,7 @@ namespace UniGLTF flipped.Add(t1); flipped.Add(t0); } - var gltfPrimitive = buffer.ToGltfPrimitive(w, materialIndex, flipped); + var gltfPrimitive = buffer.ToGltfPrimitive(data, materialIndex, flipped); // blendShape(morph target) for (int j = 0; j < mesh.blendShapeCount; ++j) @@ -101,7 +101,7 @@ namespace UniGLTF axisInverter.InvertVector3(blendShapeNormals[k])); } - gltfPrimitive.targets.Add(blendShape.ToGltf(w, !settings.ExportOnlyBlendShapePosition, + gltfPrimitive.targets.Add(blendShape.ToGltf(data, !settings.ExportOnlyBlendShapePosition, settings.UseSparseAccessorForMorphTarget)); } diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs index c11537a80..4a9c89c78 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/MeshIO/MeshExporter_SharedVertexBuffer.cs @@ -24,27 +24,27 @@ namespace UniGLTF /// /// /// - public static (glTFMesh, Dictionary blendShapeIndexMap) Export(ExportingGltfData w, + public static (glTFMesh, Dictionary blendShapeIndexMap) Export(ExportingGltfData data, MeshExportInfo unityMesh, List unityMaterials, IAxisInverter axisInverter, GltfExportSettings settings) { var mesh = unityMesh.Mesh; var materials = unityMesh.Materials; var positions = mesh.vertices.Select(axisInverter.InvertVector3).ToArray(); - var positionAccessorIndex = w.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); - w.GLTF.accessors[positionAccessorIndex].min = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Min(a.x, b.x), Math.Min(a.y, b.y), Mathf.Min(a.z, b.z))).ToArray(); - w.GLTF.accessors[positionAccessorIndex].max = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Max(a.x, b.x), Math.Max(a.y, b.y), Mathf.Max(a.z, b.z))).ToArray(); + var positionAccessorIndex = data.ExtendBufferAndGetAccessorIndex(positions, glBufferTarget.ARRAY_BUFFER); + data.GLTF.accessors[positionAccessorIndex].min = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Min(a.x, b.x), Math.Min(a.y, b.y), Mathf.Min(a.z, b.z))).ToArray(); + data.GLTF.accessors[positionAccessorIndex].max = positions.Aggregate(positions[0], (a, b) => new Vector3(Mathf.Max(a.x, b.x), Math.Max(a.y, b.y), Mathf.Max(a.z, b.z))).ToArray(); - var normalAccessorIndex = w.ExtendBufferAndGetAccessorIndex(mesh.normals.Select(y => axisInverter.InvertVector3(y.normalized)).ToArray(), glBufferTarget.ARRAY_BUFFER); + var normalAccessorIndex = data.ExtendBufferAndGetAccessorIndex(mesh.normals.Select(y => axisInverter.InvertVector3(y.normalized)).ToArray(), glBufferTarget.ARRAY_BUFFER); int? tangentAccessorIndex = default; if (settings.ExportTangents) { - tangentAccessorIndex = w.ExtendBufferAndGetAccessorIndex(mesh.tangents.Select(axisInverter.InvertVector4).ToArray(), glBufferTarget.ARRAY_BUFFER); + tangentAccessorIndex = data.ExtendBufferAndGetAccessorIndex(mesh.tangents.Select(axisInverter.InvertVector4).ToArray(), glBufferTarget.ARRAY_BUFFER); } - var uvAccessorIndex0 = w.ExtendBufferAndGetAccessorIndex(mesh.uv.Select(y => y.ReverseUV()).ToArray(), glBufferTarget.ARRAY_BUFFER); - var uvAccessorIndex1 = w.ExtendBufferAndGetAccessorIndex(mesh.uv2.Select(y => y.ReverseUV()).ToArray(), glBufferTarget.ARRAY_BUFFER); + var uvAccessorIndex0 = data.ExtendBufferAndGetAccessorIndex(mesh.uv.Select(y => y.ReverseUV()).ToArray(), glBufferTarget.ARRAY_BUFFER); + var uvAccessorIndex1 = data.ExtendBufferAndGetAccessorIndex(mesh.uv2.Select(y => y.ReverseUV()).ToArray(), glBufferTarget.ARRAY_BUFFER); var colorAccessorIndex = -1; @@ -54,12 +54,12 @@ namespace UniGLTF ) { // UniUnlit で Multiply 設定になっている - colorAccessorIndex = w.ExtendBufferAndGetAccessorIndex(mesh.colors, glBufferTarget.ARRAY_BUFFER); + colorAccessorIndex = data.ExtendBufferAndGetAccessorIndex(mesh.colors, glBufferTarget.ARRAY_BUFFER); } var boneweights = mesh.boneWeights; - var weightAccessorIndex = w.ExtendBufferAndGetAccessorIndex(boneweights.Select(y => new Vector4(y.weight0, y.weight1, y.weight2, y.weight3)).ToArray(), glBufferTarget.ARRAY_BUFFER); - var jointsAccessorIndex = w.ExtendBufferAndGetAccessorIndex(boneweights.Select(y => + var weightAccessorIndex = data.ExtendBufferAndGetAccessorIndex(boneweights.Select(y => new Vector4(y.weight0, y.weight1, y.weight2, y.weight3)).ToArray(), glBufferTarget.ARRAY_BUFFER); + var jointsAccessorIndex = data.ExtendBufferAndGetAccessorIndex(boneweights.Select(y => new UShort4( (ushort)unityMesh.GetJointIndex(y.boneIndex0), (ushort)unityMesh.GetJointIndex(y.boneIndex1), @@ -127,7 +127,7 @@ namespace UniGLTF indices.Add((uint)i0); } - var indicesAccessorIndex = w.ExtendBufferAndGetAccessorIndex(indices.ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); + var indicesAccessorIndex = data.ExtendBufferAndGetAccessorIndex(indices.ToArray(), glBufferTarget.ELEMENT_ARRAY_BUFFER); if (indicesAccessorIndex < 0) { // https://github.com/vrm-c/UniVRM/issues/664 @@ -156,7 +156,7 @@ namespace UniGLTF int exportBlendShapes = 0; for (int j = 0; j < unityMesh.Mesh.blendShapeCount; ++j) { - var morphTarget = ExportMorphTarget(w, + var morphTarget = ExportMorphTarget(data, unityMesh.Mesh, j, settings.UseSparseAccessorForMorphTarget, settings.ExportOnlyBlendShapePosition, axisInverter); @@ -200,7 +200,7 @@ namespace UniGLTF return useSparse; } - static gltfMorphTarget ExportMorphTarget(ExportingGltfData w, + static gltfMorphTarget ExportMorphTarget(ExportingGltfData data, Mesh mesh, int blendShapeIndex, bool useSparseAccessorForMorphTarget, bool exportOnlyBlendShapePosition, @@ -244,7 +244,7 @@ namespace UniGLTF normals[i] = axisInverter.InvertVector3(normals[i]); } - return BlendShapeExporter.Export(w, + return BlendShapeExporter.Export(data, blendShapeVertices, exportOnlyBlendShapePosition && useNormal ? null : blendShapeNormals, useSparseAccessorForMorphTarget); diff --git a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs index e3f90fb19..09ed4ad2b 100644 --- a/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs +++ b/Assets/UniGLTF/Runtime/UniGLTF/IO/TextureIO/GltfTextureExporter.cs @@ -22,16 +22,16 @@ namespace UniGLTF /// /// /// gltf texture index - public static int PushGltfTexture(ExportingGltfData w, Texture2D texture, ColorSpace textureColorSpace, ITextureSerializer textureSerializer) + public static int PushGltfTexture(ExportingGltfData data, Texture2D texture, ColorSpace textureColorSpace, ITextureSerializer textureSerializer) { var bytesWithMime = textureSerializer.ExportBytesWithMime(texture, textureColorSpace); // add view - var viewIndex = w.ExtendBufferAndGetViewIndex(bytesWithMime.bytes); + var viewIndex = data.ExtendBufferAndGetViewIndex(bytesWithMime.bytes); // add image - var imageIndex = w.GLTF.images.Count; - w.GLTF.images.Add(new glTFImage + var imageIndex = data.GLTF.images.Count; + data.GLTF.images.Add(new glTFImage { name = TextureImportName.RemoveSuffix(texture.name), bufferView = viewIndex, @@ -39,13 +39,13 @@ namespace UniGLTF }); // add sampler - var samplerIndex = w.GLTF.samplers.Count; + var samplerIndex = data.GLTF.samplers.Count; var sampler = TextureSamplerUtil.Export(texture); - w.GLTF.samplers.Add(sampler); + data.GLTF.samplers.Add(sampler); // add texture - var textureIndex = w.GLTF.textures.Count; - w.GLTF.textures.Add(new glTFTexture + var textureIndex = data.GLTF.textures.Count; + data.GLTF.textures.Add(new glTFTexture { sampler = samplerIndex, source = imageIndex, diff --git a/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs b/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs index f79c2547d..162ce5456 100644 --- a/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs +++ b/Assets/VRM10/Runtime/IO/Vrm10Exporter.cs @@ -57,11 +57,11 @@ namespace UniVRM10 return asset; } - public static IEnumerable ExportMeshes(List groups, List materials, ExportingGltfData w, ExportArgs option) + public static IEnumerable ExportMeshes(List groups, List materials, ExportingGltfData data, ExportArgs option) { foreach (var group in groups) { - yield return group.ExportMeshGroup(materials, w, option); + yield return group.ExportMeshGroup(materials, data, option); } }