#region License /* MIT License Copyright(c) 2019 Mattias Edlund Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion #if UNITY_2018_2_OR_NEWER #define UNITY_8UV_SUPPORT #endif #if UNITY_2017_3_OR_NEWER #define UNITY_MESH_INDEXFORMAT_SUPPORT #endif using System; using System.Collections.Generic; using UnityEngine; #if UNITY_MESH_INDEXFORMAT_SUPPORT using UnityEngine.Rendering; #endif namespace UnityMeshSimplifier { /// /// Contains utility methods for meshes. /// public static class MeshUtils { #region Consts /// /// The count of supported UV channels. /// #if UNITY_8UV_SUPPORT public const int UVChannelCount = 8; #else public const int UVChannelCount = 4; #endif #endregion #region Public Methods /// /// Creates a new mesh. /// /// The mesh vertices. /// The mesh sub-mesh indices. /// The mesh normals. /// The mesh tangents. /// The mesh colors. /// The mesh bone-weights. /// The mesh 4D UV sets. /// The mesh bindposes. /// The created mesh. public static Mesh CreateMesh(Vector3[] vertices, int[][] indices, Vector3[] normals, Vector4[] tangents, Color[] colors, BoneWeight[] boneWeights, List[] uvs, Matrix4x4[] bindposes, BlendShape[] blendShapes) { return CreateMesh(vertices, indices, normals, tangents, colors, boneWeights, uvs, null, null, bindposes, blendShapes); } /// /// Creates a new mesh. /// /// The mesh vertices. /// The mesh sub-mesh indices. /// The mesh normals. /// The mesh tangents. /// The mesh colors. /// The mesh bone-weights. /// The mesh 4D UV sets. /// The mesh bindposes. /// The created mesh. public static Mesh CreateMesh(Vector3[] vertices, int[][] indices, Vector3[] normals, Vector4[] tangents, Color[] colors, BoneWeight[] boneWeights, List[] uvs, Matrix4x4[] bindposes, BlendShape[] blendShapes) { return CreateMesh(vertices, indices, normals, tangents, colors, boneWeights, null, null, uvs, bindposes, blendShapes); } /// /// Creates a new mesh. /// /// The mesh vertices. /// The mesh sub-mesh indices. /// The mesh normals. /// The mesh tangents. /// The mesh colors. /// The mesh bone-weights. /// The mesh 2D UV sets. /// The mesh 3D UV sets. /// The mesh 4D UV sets. /// The mesh bindposes. /// The created mesh. public static Mesh CreateMesh(Vector3[] vertices, int[][] indices, Vector3[] normals, Vector4[] tangents, Color[] colors, BoneWeight[] boneWeights, List[] uvs2D, List[] uvs3D, List[] uvs4D, Matrix4x4[] bindposes, BlendShape[] blendShapes) { var newMesh = new Mesh(); int subMeshCount = indices.Length; #if UNITY_MESH_INDEXFORMAT_SUPPORT IndexFormat indexFormat; var indexMinMax = MeshUtils.GetSubMeshIndexMinMax(indices, out indexFormat); newMesh.indexFormat = indexFormat; #endif if (bindposes != null && bindposes.Length > 0) { newMesh.bindposes = bindposes; } newMesh.subMeshCount = subMeshCount; newMesh.vertices = vertices; // If after assigning normals blendshapes are assigned, then blendshapes do not work correctly // In URP and HDRP configurations, so we add blendshapes first and then assign normals if (blendShapes != null) { MeshUtils.ApplyMeshBlendShapes(newMesh, blendShapes); } if (normals != null && normals.Length > 0) { newMesh.normals = normals; } if (tangents != null && tangents.Length > 0) { newMesh.tangents = tangents; } if (colors != null && colors.Length > 0) { newMesh.colors = colors; } if (boneWeights != null && boneWeights.Length > 0) { newMesh.boneWeights = boneWeights; } if (uvs2D != null) { for (int uvChannel = 0; uvChannel < uvs2D.Length; uvChannel++) { if (uvs2D[uvChannel] != null && uvs2D[uvChannel].Count > 0) { newMesh.SetUVs(uvChannel, uvs2D[uvChannel]); } } } if (uvs3D != null) { for (int uvChannel = 0; uvChannel < uvs3D.Length; uvChannel++) { if (uvs3D[uvChannel] != null && uvs3D[uvChannel].Count > 0) { newMesh.SetUVs(uvChannel, uvs3D[uvChannel]); } } } if (uvs4D != null) { for (int uvChannel = 0; uvChannel < uvs4D.Length; uvChannel++) { if (uvs4D[uvChannel] != null && uvs4D[uvChannel].Count > 0) { newMesh.SetUVs(uvChannel, uvs4D[uvChannel]); } } } //if (blendShapes != null) //{ // MeshUtils.ApplyMeshBlendShapes(newMesh, blendShapes); //baw did //} for (int subMeshIndex = 0; subMeshIndex < subMeshCount; subMeshIndex++) { var subMeshTriangles = indices[subMeshIndex]; #if UNITY_MESH_INDEXFORMAT_SUPPORT var minMax = indexMinMax[subMeshIndex]; if (indexFormat == UnityEngine.Rendering.IndexFormat.UInt16 && minMax.y > ushort.MaxValue) { int baseVertex = minMax.x; for (int index = 0; index < subMeshTriangles.Length; index++) { subMeshTriangles[index] -= baseVertex; } newMesh.SetTriangles(subMeshTriangles, subMeshIndex, false, baseVertex); } else { newMesh.SetTriangles(subMeshTriangles, subMeshIndex, false, 0); } #else newMesh.SetTriangles(subMeshTriangles, subMeshIndex, false); #endif } newMesh.RecalculateBounds(); return newMesh; } /// /// Returns the blend shapes of a mesh. /// /// The mesh. /// The mesh blend shapes. public static BlendShape[] GetMeshBlendShapes(Mesh mesh) { if (mesh == null) throw new ArgumentNullException(nameof(mesh)); int vertexCount = mesh.vertexCount; int blendShapeCount = mesh.blendShapeCount; if (blendShapeCount == 0) return null; var blendShapes = new BlendShape[blendShapeCount]; for (int blendShapeIndex = 0; blendShapeIndex < blendShapeCount; blendShapeIndex++) { string shapeName = mesh.GetBlendShapeName(blendShapeIndex); int frameCount = mesh.GetBlendShapeFrameCount(blendShapeIndex); var frames = new BlendShapeFrame[frameCount]; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { float frameWeight = mesh.GetBlendShapeFrameWeight(blendShapeIndex, frameIndex); var deltaVertices = new Vector3[vertexCount]; var deltaNormals = new Vector3[vertexCount]; var deltaTangents = new Vector3[vertexCount]; mesh.GetBlendShapeFrameVertices(blendShapeIndex, frameIndex, deltaVertices, deltaNormals, deltaTangents); frames[frameIndex] = new BlendShapeFrame(frameWeight, deltaVertices, deltaNormals, deltaTangents); } blendShapes[blendShapeIndex] = new BlendShape(shapeName, frames); } return blendShapes; } public static void LOG(string s) { Debug.Log(s); } /// /// Applies and overrides the specified blend shapes on the specified mesh. /// /// The mesh. /// The mesh blend shapes. public static void ApplyMeshBlendShapes(Mesh mesh, BlendShape[] blendShapes) { if (mesh == null) throw new ArgumentNullException(nameof(mesh)); mesh.ClearBlendShapes(); if (blendShapes == null || blendShapes.Length == 0) return; for (int blendShapeIndex = 0; blendShapeIndex < blendShapes.Length; blendShapeIndex++) { string shapeName = blendShapes[blendShapeIndex].ShapeName; var frames = blendShapes[blendShapeIndex].Frames; if (frames != null) { for (int frameIndex = 0; frameIndex < frames.Length; frameIndex++) { try { mesh.AddBlendShapeFrame(shapeName, frames[frameIndex].frameWeight, frames[frameIndex].deltaVertices, frames[frameIndex].deltaNormals, frames[frameIndex].deltaTangents); } catch (Exception e) { // Make the name of the blendshape unique and then try to add for(int a = 0; a < mesh.blendShapeCount; a++) { string thisShapeName = mesh.GetBlendShapeName(a); if(shapeName == thisShapeName) { shapeName += "_" + Guid.NewGuid().ToString("N"); try { mesh.AddBlendShapeFrame(shapeName, frames[frameIndex].frameWeight, frames[frameIndex].deltaVertices, frames[frameIndex].deltaNormals, frames[frameIndex].deltaTangents); } catch (Exception ex) { throw ex; } break; } } } } } } } /// /// Returns the UV sets for a specific mesh. /// /// The mesh. /// The UV sets. public static List[] GetMeshUVs(Mesh mesh) { if (mesh == null) throw new ArgumentNullException(nameof(mesh)); var uvs = new List[UVChannelCount]; for (int channel = 0; channel < UVChannelCount; channel++) { uvs[channel] = GetMeshUVs(mesh, channel); } return uvs; } /// /// Returns the UV list for a specific mesh and UV channel. /// /// The mesh. /// The UV channel. /// The UV list. public static List GetMeshUVs(Mesh mesh, int channel) { if (mesh == null) throw new ArgumentNullException(nameof(mesh)); else if (channel < 0 || channel >= UVChannelCount) throw new ArgumentOutOfRangeException(nameof(channel)); var uvList = new List(mesh.vertexCount); mesh.GetUVs(channel, uvList); return uvList; } /// /// Returns the number of used UV components in a UV set. /// /// The UV set. /// The number of used UV components. public static int GetUsedUVComponents(List uvs) { if (uvs == null || uvs.Count == 0) return 0; int usedComponents = 0; foreach (var uv in uvs) { if (usedComponents < 1 && uv.x != 0f) { usedComponents = 1; } if (usedComponents < 2 && uv.y != 0f) { usedComponents = 2; } if (usedComponents < 3 && uv.z != 0f) { usedComponents = 3; } if (usedComponents < 4 && uv.w != 0f) { usedComponents = 4; break; } } return usedComponents; } /// /// Converts a list of 4D UVs into 2D. /// /// The list of UVs. /// The array of 2D UVs. public static Vector2[] ConvertUVsTo2D(List uvs) { if (uvs == null) return null; var uv2D = new Vector2[uvs.Count]; for (int i = 0; i < uv2D.Length; i++) { var uv = uvs[i]; uv2D[i] = new Vector2(uv.x, uv.y); } return uv2D; } /// /// Converts a list of 4D UVs into 3D. /// /// The list of UVs. /// The array of 3D UVs. public static Vector3[] ConvertUVsTo3D(List uvs) { if (uvs == null) return null; var uv3D = new Vector3[uvs.Count]; for (int i = 0; i < uv3D.Length; i++) { var uv = uvs[i]; uv3D[i] = new Vector3(uv.x, uv.y, uv.z); } return uv3D; } #if UNITY_MESH_INDEXFORMAT_SUPPORT /// /// Returns the minimum and maximum indices for each submesh along with the needed index format. /// /// The indices for the submeshes. /// The output index format. /// The minimum and maximum indices for each submesh. public static Vector2Int[] GetSubMeshIndexMinMax(int[][] indices, out IndexFormat indexFormat) { if (indices == null) throw new ArgumentNullException(nameof(indices)); var result = new Vector2Int[indices.Length]; indexFormat = IndexFormat.UInt16; for (int subMeshIndex = 0; subMeshIndex < indices.Length; subMeshIndex++) { int minIndex, maxIndex; GetIndexMinMax(indices[subMeshIndex], out minIndex, out maxIndex); result[subMeshIndex] = new Vector2Int(minIndex, maxIndex); int indexRange = (maxIndex - minIndex); if (indexRange > ushort.MaxValue) { indexFormat = IndexFormat.UInt32; } } return result; } #endif #endregion #region Private Methods private static void GetIndexMinMax(int[] indices, out int minIndex, out int maxIndex) { if (indices == null || indices.Length == 0) { minIndex = maxIndex = 0; return; } minIndex = int.MaxValue; maxIndex = int.MinValue; for (int i = 0; i < indices.Length; i++) { if (indices[i] < minIndex) { minIndex = indices[i]; } if (indices[i] > maxIndex) { maxIndex = indices[i]; } } } #endregion } }