public Mesh Build(string name = "Mesh", bool buildSecondaryUVs = false)
        {
            if (!HasMesh())
            {
                return(new Mesh());
            }

            var mesh = new Mesh();

            mesh.name = name;

            mesh.vertices  = vertices.ToArray();
            mesh.normals   = normals.ToArray();
            mesh.uv        = uvs.ToArray();
            mesh.triangles = triangles.ToArray();
            mesh.colors    = colors.ToArray();

            mesh.RecalculateBounds();
            mesh.RecalculateTangents();
            mesh.Optimize();
            mesh.OptimizeIndexBuffers();
            mesh.OptimizeReorderVertexBuffer();

            if (buildSecondaryUVs)
            {
                Unwrapping.GenerateSecondaryUVSet(mesh);
            }

            return(mesh);
        }
        protected void GenerateMesh()
        {
            if (!railMesh && !tieMesh)
            {
                generatedMesh.Clear();
                return;
            }

            Profiler.BeginSample("Track.GenerateMesh", this);

#if UNITY_EDITOR
            if (gameObject.isStatic && Application.isPlaying && !isStartup)
            {
                Debug.LogWarning("Trying to update a mesh on a track marked as static", this);
            }
#endif

            if (meshGenerator == null)
            {
                meshGenerator = new TrackMeshGenerator();
            }
            meshGenerator.SetMeshes(railMesh, tieMesh);
            meshGenerator.GenerateMesh(generatedMesh, this);
#if UNITY_EDITOR
            if (gameObject.isStatic)
            {
                Unwrapping.GenerateSecondaryUVSet(generatedMesh);
            }
#endif
            meshGenerator.GenerateMesh(generatedMesh, this);

            Profiler.EndSample();
        }
    /// <summary>
    /// Method that combine meshes in to One mesh
    /// </summary>
    private void MeshCombine()
    {
        // Array to store child mesh filters on same subMeshIndex
        _childMeshInstances = new CombineInstance[_childMeshFilters.Length];

        for (int i = 0; i < _childMeshFilters.Length; i++)
        {
            // Exclude yourslef
            if (_childMeshFilters[i].transform == transform)
            {
                continue;
            }

            _childMeshInstances[i].subMeshIndex = 0;
            _childMeshInstances[i].mesh         = _childMeshFilters[i].sharedMesh;
            _childMeshInstances[i].transform    = _childMeshFilters[i].transform.localToWorldMatrix;
        }

        // Combine meshes from array and assign it
        Mesh combinedMesh = new Mesh();

        combinedMesh.CombineMeshes(_childMeshInstances);
        GetComponent <MeshFilter>().sharedMesh = combinedMesh;

        //Generate UV for Combined Mesh
        combinedMesh.Optimize();
        Unwrapping.GenerateSecondaryUVSet(combinedMesh);

        // Assign original transform & parent
        transform.parent        = _parent;
        transform.localPosition = _originalPosition;
        transform.localRotation = _originalRotation;

        HideChildren();
    }
 /**
  * This is called after the drag sizing event is complete, and a finalized base start, end, and height hprivate Vector3 size = Vector3.one;ave been established.
  */
 public virtual void OnFinishDragSizing()
 {
     FreezeTransform();
                 #if UNITY_EDITOR
     Unwrapping.GenerateSecondaryUVSet(GetComponent <MeshFilter>().sharedMesh);
                 #endif
 }
	public static void UnwrapUV2(Mesh mesh, float hardAngle, float packingMargin){
			UnwrapParam up = new UnwrapParam();
			UnwrapParam.SetDefaults(out up);
			up.hardAngle = hardAngle;
			up.packMargin = packingMargin;
			Unwrapping.GenerateSecondaryUVSet(mesh,up);
	}
Exemple #6
0
        public static void AddMeshes(MeshFilter[] filters, SkinnedMeshRenderer[] skinnedRenderers, AssetImportContext ctx, UnwrapParam?lightmapUnwrapInfo)
        {
            HashSet <Mesh> visitedMeshes = new HashSet <Mesh>();

            for (int i = 0; i < filters.Length; i++)
            {
                Mesh mesh = filters[i].sharedMesh;
                if (lightmapUnwrapInfo.HasValue)
                {
                    Unwrapping.GenerateSecondaryUVSet(mesh, lightmapUnwrapInfo.Value);
                }
                if (visitedMeshes.Contains(mesh))
                {
                    continue;
                }
                ctx.AddAsset(mesh.name, mesh);
                visitedMeshes.Add(mesh);
            }
            for (int i = 0; i < skinnedRenderers.Length; i++)
            {
                Mesh mesh = skinnedRenderers[i].sharedMesh;
                if (visitedMeshes.Contains(mesh))
                {
                    continue;
                }
                ctx.AddAsset(mesh.name, mesh);
                visitedMeshes.Add(mesh);
            }
        }
Exemple #7
0
    void Combine(MeshFilter[] meshFilters, int submesh, Transform root)
    {
        GameObject target = new GameObject();


        if (target.GetComponent <MeshFilter> () == null)
        {
            target.AddComponent <MeshFilter> ();
        }
        if (target.GetComponent <MeshRenderer> () == null)
        {
            target.AddComponent <MeshRenderer> ();
        }

        Mesh      finalMesh = new Mesh();
        Matrix4x4 ourMatrix = target.transform.localToWorldMatrix;

        //Material material = null;
        Material[] materials = null;

        CombineInstance[] combiners = new CombineInstance[meshFilters.Length];

        for (int i = 0; i < meshFilters.Length; i++)
        {
            if (meshFilters [i].transform == target.transform)
            {
                continue;
            }

            combiners [i].subMeshIndex = submesh;
            combiners [i].mesh         = meshFilters [i].sharedMesh;
            combiners [i].transform    = meshFilters [i].transform.localToWorldMatrix;
            materials     = new Material[1];
            materials [0] = meshFilters [i].gameObject.GetComponent <MeshRenderer> ().sharedMaterials [submesh];
            if (disableRootafterCombine)
            {
                meshFilters [i].transform.root.gameObject.SetActive(false);
            }
            else
            {
                meshFilters [i].transform.gameObject.SetActive(false);
            }
        }

        finalMesh.CombineMeshes(combiners);
        if (generateUv2)
        {
            Unwrapping.GenerateSecondaryUVSet(finalMesh);
        }

        target.gameObject.isStatic = setStatic;
        target.GetComponent <MeshFilter> ().sharedMesh  = finalMesh;
        target.GetComponent <MeshRenderer> ().materials = materials;
        target.name             = "Group_" + materials [0].name + "_Sub_mesh" + submesh;
        target.transform.parent = root;
        if (target.GetComponent <MeshCollider> ())
        {
            target.GetComponent <MeshCollider> ().sharedMesh = finalMesh;
        }
    }
        public override void OnFinishDragSizing()
        {
            // base.OnFinishDragSizing();	// need to build UVs before assigning the UV2 channel
            FreezeTransform();

            // calc uvs
            Mesh m = GetComponent <MeshFilter>().sharedMesh;

            Vector2[] uvs         = m.uv;
            Vector3[] v           = m.vertices;
            int       vertexCount = m.vertexCount;

            uvs[vertexCount - 1] = Vector2.zero;
            uvs[vertexCount - 2] = Vector2.zero;

            for (int i = 0; i < m.vertices.Length; i++)
            {
                uvs[i] = new Vector2(v[i].x, v[i].z);
            }

            m.uv = uvs;

                        #if UNITY_EDITOR
            Unwrapping.GenerateSecondaryUVSet(m);
                        #endif
        }
 public void Bake(bool makeStatic, bool lightmapUV)
 {
     if (mesh == null)
     {
         return;
     }
     gameObject.isStatic = false;
     UnityEditor.MeshUtility.Optimize(mesh);
     if (computer != null)
     {
         computer.Unsubscribe(this);
     }
     filter            = GetComponent <MeshFilter>();
     meshRenderer      = GetComponent <MeshRenderer>();
     filter.hideFlags  = meshRenderer.hideFlags = HideFlags.None;
     filter.sharedMesh = mesh;
     if (lightmapUV)
     {
         Unwrapping.GenerateSecondaryUVSet(filter.sharedMesh);
     }
     if (makeStatic)
     {
         gameObject.isStatic = true;
     }
     _baked = true;
 }
Exemple #10
0
    public void GenerateSecondaryUVSet()
    {
#if UNITY_EDITOR
        for (int i = 0; i < numberOfCurves; i++)
        {
            TrackBuildRPoint curve = _points[i];

            for (int m = 0; m < curve.dynamicTrackMesh.meshCount; m++)
            {
                Unwrapping.GenerateSecondaryUVSet(curve.dynamicTrackMesh[m].mesh);
            }
            for (int m = 0; m < curve.dynamicOffroadMesh.meshCount; m++)
            {
                Unwrapping.GenerateSecondaryUVSet(curve.dynamicOffroadMesh[m].mesh);
            }
            for (int m = 0; m < curve.dynamicBumperMesh.meshCount; m++)
            {
                Unwrapping.GenerateSecondaryUVSet(curve.dynamicBumperMesh[m].mesh);
            }
            for (int m = 0; m < curve.dynamicBoundaryMesh.meshCount; m++)
            {
                Unwrapping.GenerateSecondaryUVSet(curve.dynamicBoundaryMesh[m].mesh);
            }
            for (int m = 0; m < curve.dynamicBottomMesh.meshCount; m++)
            {
                Unwrapping.GenerateSecondaryUVSet(curve.dynamicBottomMesh[m].mesh);
            }
        }
        _lightmapGenerated = true;
#endif
    }
Exemple #11
0
        public void GenerateLightmapUV(GameObject go)
        {
            if (go == null)
            {
                return;
            }
            var mf = go.GetComponent <MeshFilter>();

            if (mf != null)
            {
                var mesh = mf.sharedMesh;
                if (mesh != null)
                {
                    Unwrapping.GenerateSecondaryUVSet(mesh);
                }
            }
            for (int i = 1; ; ++i)
            {
                var t = go.transform.Find("[" + i + "]");
                if (t == null)
                {
                    break;
                }
                GenerateLightmapUV(t.gameObject);
            }
        }
        public void ToMesh(Mesh m, bool computeLightMapUVs)
        {
            m.Clear();
            m.indexFormat = triangles.Count > 65535 ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16;
            m.SetVertices(vertices);
            m.SetNormals(normals);
            if (uvs0.Count == vertices.Count)
            {
                m.SetUVs(0, uvs0);
            }
            if (color32s.Count == vertices.Count)
            {
                m.SetColors(color32s);
            }

            m.subMeshCount = 1;
            m.SetTriangles(triangles, 0);

            if (computeLightMapUVs)
            {
                UnwrapParam param;
                UnwrapParam.SetDefaults(out param);
                param.packMargin = 0.02f;
                Unwrapping.GenerateSecondaryUVSet(m, param);
            }

            m.RecalculateBounds();
            // TODO: Use bounds
        }
Exemple #13
0
        // IDEA: Combine this with LightProbeProxyVolume generation
        // If object area is too large, use the LightDirect mode
        // Use blended light probes for small objects
        // Use proxy volumes for intermediate sizes

        /// <summary>
        /// Configure MeshRenderer to use baked lighting with secondary UV charts
        /// </summary>
        /// <param name="regenerate">When true, overwrite existing secondary UVs</param>
        public static void ConvertToLightCharts(MeshRenderer meshRenderer, bool regenerate = false)
        {
            var staticFlags = GameObjectUtility.GetStaticEditorFlags(meshRenderer.gameObject);

            staticFlags |= StaticEditorFlags.ContributeGI;
            GameObjectUtility.SetStaticEditorFlags(meshRenderer.gameObject, staticFlags);
            meshRenderer.receiveGI       = ReceiveGI.Lightmaps;
            meshRenderer.scaleInLightmap = 1f;

            meshRenderer.receiveShadows    = true;
            meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;

            meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.BlendProbes;

            var sharedMesh = SharedMesh(meshRenderer);

            if (!sharedMesh)
            {
                return;
            }
            if (regenerate || sharedMesh.uv2.Length == 0)
            {
                Unwrapping.GenerateSecondaryUVSet(sharedMesh, unwrapParam);
            }
        }
Exemple #14
0
        /// <summary>
        /// Apply all the mest details to the object
        /// </summary>
        /// <param name="baseobject">The object to add the mesh too</param>
        public void ApplyMeshDetails(GameObject baseobject)
        {
#if DEBUG
            CenterMesh(baseobject);

            Mesh mesh = new Mesh();
            mesh.name = baseobject.name + "Mesh";
            baseobject.GetComponent <MeshFilter>().mesh = mesh;
            mesh.vertices = MeshVertices.ToArray();
            mesh.uv       = MeshUVs.ToArray();

            // Create the material and assign triangles
            Renderer        r         = baseobject.GetComponent <Renderer>();
            List <Material> materials = new List <Material>();
            int             count     = 0;
            mesh.subMeshCount = _meshMaterialsTriangles.Count;

            foreach (MaterialFrequency mf in RoadConstructorHelper.MaterialFrequencySet.GetDetails)
            {
                int[] tris = GetTriangles(mf.Material.name).ToArray();
                if (tris.Length == 0)
                {
                    continue;
                }

                materials.Add(mf.Material);
                mesh.SetTriangles(tris, count++);
            }

            mesh.subMeshCount = count; // just in case we didn't add all of them

            r.materials = materials.ToArray();

            mesh.RecalculateNormals();
            mesh.RecalculateTangents();
            mesh.RecalculateBounds();

            if (RoadConstructorHelper.Lighting.BakedLighting)
            {
                if (count != 0)
                {
                    UnwrapParam up = new UnwrapParam();
                    up.hardAngle  = RoadConstructorHelper.Lighting.HardAngle;
                    up.packMargin = RoadConstructorHelper.Lighting.PackMargin;
                    up.angleError = RoadConstructorHelper.Lighting.AngleError;
                    up.areaError  = RoadConstructorHelper.Lighting.AngleError;

                    Unwrapping.GenerateSecondaryUVSet(mesh, up);
                }
            }

#if UNITY_5_5_OR_NEWER
#if UNITY_EDITOR
            UnityEditor.MeshUtility.Optimize(mesh);
#endif
#else
            mesh.Optimize();
#endif
#endif
        }
        /// <summary>
        ///     The work on item.
        /// </summary>
        /// <param name="item">
        ///     The item.
        /// </param>
        protected override void WorkOnItem(GameObject item)
        {
#if UNITY_EDITOR
            if (item == null)
            {
                return;
            }

            var mf = item.GetComponent <MeshFilter>();

            if (mf == null)
            {
                return;
            }

            var sm = mf.sharedMesh;

            if (sm == null)
            {
                return;
            }

            Unwrapping.GenerateSecondaryUVSet(sm);
#endif
        }
Exemple #16
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        CustomMeshLightmap script = (CustomMeshLightmap)target;

        if (GUILayout.Button("Add Lightmaps"))
        {
            if (!AssetDatabase.IsValidFolder("Assets/Courses/LightmapFriendly/" + script.transform.parent.name))
            {
                AssetDatabase.CreateFolder("Assets/Courses/LightmapFriendly", script.transform.parent.name);
            }

            Mesh m = script.GetComponent <MeshFilter>().mesh;

            Mesh mesh = new Mesh();
            mesh.vertices  = m.vertices;
            mesh.uv        = m.uv;
            mesh.normals   = m.normals;
            mesh.tangents  = m.tangents;
            mesh.colors    = m.colors;
            mesh.triangles = m.triangles;
            Unwrapping.GeneratePerTriangleUV(mesh);
            Unwrapping.GenerateSecondaryUVSet(mesh);

            AssetDatabase.CreateAsset(mesh, "Assets/Courses/LightmapFriendly/" + script.transform.parent.name + "/" + script.gameObject.name + ".asset");
        }
    }
Exemple #17
0
//    /// <summary>
//    /// Mark the pit lane as dirty so it will be recalculated/rebuilt
//    /// </summary>
//    public void SetPitDirty()
//    {
//        for (int i = 0; i < pitlane.numberOfPoints; i++)
//        {
//            pitlane[i].isDirty = true;
//        }
//    }
//
//    /// <summary>
//    /// Set pit lane point data to rerender
//    /// </summary>
//    public void ReRenderPit()
//    {
//        for (int i = 0; i < pitlane.numberOfPoints; i++)
//        {
//            pitlane[i].shouldReRender = true;
//        }
//    }

    public void GenerateSecondaryUVSet()
    {
#if UNITY_EDITOR
        for (int i = 0; i < numberOfCurves; i++)
        {
            TrackBuildRPoint curve = _points[i];

            List <Mesh> unwrapList = new List <Mesh>();
            unwrapList.AddRange(curve.dynamicTrackMesh.meshes);
            unwrapList.AddRange(curve.dynamicOffroadMesh.meshes);
            unwrapList.AddRange(curve.dynamicBumperMesh.meshes);
            unwrapList.AddRange(curve.dynamicBoundaryMesh.meshes);
            unwrapList.AddRange(curve.dynamicBottomMesh.meshes);

            int count = unwrapList.Count;
            for (int m = 0; m < count; m++)
            {
                if (unwrapList[m].vertexCount == 0)
                {
                    continue;
                }
                Unwrapping.GenerateSecondaryUVSet(unwrapList[m]);
            }
        }
        _lightmapGenerated = true;
#endif
    }
Exemple #18
0
 public void OnGUI(PaintJob[] jobs)
 {
     EditorGUILayout.BeginHorizontal();
     generateUV2 = EditorGUILayout.Toggle("Generate Lightmap UVs", generateUV2);
     if (GUILayout.Button("Combine Meshes"))
     {
         VertexPainterUtilities.MergeMeshes(jobs);
     }
     if (GUILayout.Button("Combine and Save"))
     {
         if (jobs.Length != 0)
         {
             string path = EditorUtility.SaveFilePanel("Save Asset", Application.dataPath, "models", "asset");
             if (!string.IsNullOrEmpty(path))
             {
                 path = FileUtil.GetProjectRelativePath(path);
                 GameObject go = VertexPainterUtilities.MergeMeshes(jobs);
                 Mesh       m  = go.GetComponent <MeshFilter>().sharedMesh;
                 if (generateUV2)
                 {
                     Unwrapping.GenerateSecondaryUVSet(m);
                 }
                 AssetDatabase.CreateAsset(m, path);
                 AssetDatabase.SaveAssets();
                 AssetDatabase.ImportAsset(path);
                 GameObject.DestroyImmediate(go);
             }
         }
     }
     EditorGUILayout.EndHorizontal();
 }
    void Init()
    {
        Component[] meshFilters = GetComponentsInChildren <MeshFilter>(true);
        Dictionary <Material, List <CombineInstance> > combineMeshInstanceDictionary = new Dictionary <Material, List <CombineInstance> > ();

        foreach (var mesh in meshFilters)
        {
            var mat = mesh.GetComponent <Renderer>().sharedMaterial;
            if (mat == null)
            {
                continue;
            }
            if (!combineMeshInstanceDictionary.ContainsKey(mat))
            {
                combineMeshInstanceDictionary.Add(mat, new List <CombineInstance>());
            }
            var instance = combineMeshInstanceDictionary[mat];
            var cmesh    = new CombineInstance();
            cmesh.transform = mesh.transform.localToWorldMatrix;
            cmesh.mesh      = ((MeshFilter)mesh).sharedMesh;
            instance.Add(cmesh);
        }
        gameObject.SetActive(false);
        gameObject.tag = "EditorOnly";
        if (generatedObject == null)
        {
            generatedObject = new GameObject(name);
        }

        foreach (var item in generatedObject.GetComponentsInChildren <Transform>())
        {
            if (item == generatedObject.transform)
            {
                continue;
            }
            DestroyImmediate(item.gameObject);
        }
        generatedObject.isStatic = true;
        foreach (var dic in combineMeshInstanceDictionary)
        {
            var newObject = new GameObject(dic.Key.name);
            newObject.isStatic = true;
            var meshrenderer = newObject.AddComponent <MeshRenderer>();
            var meshfilter   = newObject.AddComponent <MeshFilter>();
            meshrenderer.material = dic.Key;
            var mesh = new Mesh();
            mesh.CombineMeshes(dic.Value.ToArray());
            Unwrapping.GenerateSecondaryUVSet(mesh);
            meshfilter.sharedMesh      = mesh;
            newObject.transform.parent = generatedObject.transform;

            string sceneName = System.IO.Path.GetFileNameWithoutExtension(EditorApplication.currentScene);
            Debug.Log(sceneName);


            System.IO.Directory.CreateDirectory("Assets/" + sceneName + "/" + name);
            AssetDatabase.CreateAsset(mesh, "Assets/" + sceneName + "/" + name + "/" + dic.Key.name + ".asset");
        }
    }
Exemple #20
0
        public static void RebuildUV2(qe_Mesh mesh)
        {
            Unwrapping.GenerateSecondaryUVSet(mesh.cloneMesh);

            // GenerateSecondaryUVSet may add vertices, so rebuild the
            // internal stores.
            mesh.CacheElements();
        }
Exemple #21
0
 // Use this for initialization
 void Start()
 {
     rend     = GetComponent <Renderer>();
     material = rend.material;
     material.SetColor("_Colour", Color.magenta);
     mesh = GetComponent <Mesh>();
     Unwrapping.GenerateSecondaryUVSet(mesh);
 }
Exemple #22
0
 protected void GenerateLightmappingUVs(MeshFilter mf)
 {
     // make null check because if not enough meshes are present no combined mesh would have been created!
     if (mf != null)
     {
         Unwrapping.GenerateSecondaryUVSet(mf.sharedMesh);
     }
 }
 public void GenerateLightmapUV()
 {
     #if UNITY_EDITOR
     EditorUtility.DisplayProgressBar("Creating Lightmap UV's", "This might take some time", 5f);
     Unwrapping.GenerateSecondaryUVSet(combined.GetComponent <MeshFilter>().sharedMesh);
     combined.isStatic = true;
     EditorUtility.ClearProgressBar();
     #endif
 }
Exemple #24
0
        private static void StepLast()
        {
            int end = Class.index - Class.subIndex;
            List <CombineInstance> range = new List <CombineInstance>(Class.combines).GetRange(Class.subIndex, end);
            Mesh finalMesh = Class.meshes.Last();

            finalMesh.CombineMeshes(range.ToArray());
            Unwrapping.GenerateSecondaryUVSet(finalMesh);
        }
Exemple #25
0
 public void End()
 {
     Mesh.Clear();
     Mesh.vertices  = vertices.ToArray();
     Mesh.uv        = uvs.ToArray();
     Mesh.triangles = triangles.ToArray();
     Unwrapping.GenerateSecondaryUVSet(Mesh);
     Mesh.RecalculateBounds();
     Mesh.RecalculateNormals();
 }
        private void GenerateSecondUVs(Mesh mesh)
        {
            UnwrapParam unwrapParam = new UnwrapParam();

            unwrapParam.hardAngle  = this.tileSystem.SecondUVsHardAngle;
            unwrapParam.packMargin = this.tileSystem.SecondUVsPackMargin;
            unwrapParam.angleError = this.tileSystem.SecondUVsAngleError;
            unwrapParam.areaError  = this.tileSystem.SecondUVsAreaError;
            Unwrapping.GenerateSecondaryUVSet(mesh, unwrapParam);
        }
		public static void GenerateSecondaryUVSet(Mesh meshsrc)
		{
#if UNITY_EDITOR
			UnwrapParam param;
			UnwrapParam.SetDefaults(out param);
			Unwrapping.GenerateSecondaryUVSet(meshsrc, param);
#else
			Debug.LogWarning("GenerateSecondaryUVSet is unavailable at runtime!");
#endif
		}
Exemple #28
0
    public void SaveOutCombineMesh(CombinedMesh cMesh)
    {
        Mesh outPutMesh = new Mesh();

        outPutMesh.vertices     = cMesh.vertexList.ToArray();
        outPutMesh.normals      = cMesh.normalList.ToArray();
        outPutMesh.uv           = cMesh.uvList.ToArray();
        outPutMesh.colors       = cMesh.colorList.ToArray();
        outPutMesh.subMeshCount = 1;

        outPutMesh.SetIndices(cMesh.indices.ToArray(), MeshTopology.Triangles, 0);

        if (!Directory.Exists(Application.dataPath + "/intermediate"))
        {
            Directory.CreateDirectory(Application.dataPath + "/intermediate");
        }


        string tempCombineSpriteMeshFolderFinal = "Assets/intermediate/CombineSpritMesh";

        if (!Directory.Exists(tempCombineSpriteMeshFolderFinal))
        {
            Directory.CreateDirectory(tempCombineSpriteMeshFolderFinal);
        }

        string finalName = tempCombineSpriteMeshFolderFinal + "/" + cMesh.mat.name + "_CombineSpriteMesh.asset";


        Unwrapping.GenerateSecondaryUVSet(outPutMesh);


        if (!File.Exists(finalName))
        {
            AssetDatabase.CreateAsset(outPutMesh, finalName);
        }
        else
        {
            Mesh existMesh = (Mesh)AssetDatabase.LoadAssetAtPath(finalName, typeof(Mesh));
            existMesh.Clear();
            existMesh.vertices = outPutMesh.vertices;
            existMesh.normals  = outPutMesh.normals;
            existMesh.uv       = outPutMesh.uv;
            existMesh.colors   = outPutMesh.colors;
            //existMesh.triangles = outPutMesh.triangles;
            existMesh.subMeshCount = outPutMesh.subMeshCount;
            for (int i = 0; i < outPutMesh.subMeshCount; i++)
            {
                existMesh.SetIndices(outPutMesh.GetIndices(i), MeshTopology.Triangles, i);
            }

            Unwrapping.GenerateSecondaryUVSet(existMesh);
        }

        Debug.Log("生成" + cMesh.mat.name + "_CombineSpriteMesh");
    }
Exemple #29
0
        public static void GenerateUV2(this Mesh mesh, bool forceUpdate)
        {
            // SetUVParams(8f, 15f, 15f, 20f);
            UnwrapParam param;

            UnwrapParam.SetDefaults(out param);

            Unwrapping.GenerateSecondaryUVSet(mesh, param);

            EditorUtility.SetDirty(mesh as Object);
        }
    private static Mesh CombineAllMesh(List <MeshFilter> meshes)
    {
        List <Vector3> verts        = new List <Vector3>(1000);
        List <Vector3> norms        = new List <Vector3>(1000);
        List <Vector4> tans         = new List <Vector4>(1000);
        List <Vector2> uv0s         = new List <Vector2>(1000);
        List <int>     tris         = new List <int>(1000);
        float4x4       worldToLocal = meshes[0].transform.worldToLocalMatrix;

        foreach (var i in meshes)
        {
            float4x4  localToWorld    = mul(worldToLocal, i.transform.localToWorldMatrix);
            float3x3  localToWorldRot = float3x3(localToWorld.c0.xyz, localToWorld.c1.xyz, localToWorld.c2.xyz);
            Vector3[] vertices        = i.sharedMesh.vertices;
            for (int j = 0; j < vertices.Length; ++j)
            {
                vertices[j] = mul(localToWorld, float4(vertices[j], 1)).xyz;
            }
            Vector3[] normals = i.sharedMesh.normals;
            for (int j = 0; j < vertices.Length; ++j)
            {
                normals[j] = mul(localToWorldRot, normals[j]);
            }
            Vector4[] tangents = i.sharedMesh.tangents;
            for (int j = 0; j < vertices.Length; ++j)
            {
                float3 tan  = (Vector3)tangents[j];
                float  tanW = tangents[j].w;
                tangents[j]   = (Vector3)mul(localToWorldRot, tan);
                tangents[j].w = tanW;
            }
            Vector2[] uv0       = i.sharedMesh.uv;
            int[]     triangles = i.sharedMesh.triangles;
            for (int j = 0; j < triangles.Length; ++j)
            {
                triangles[j] += verts.Count;
            }
            tris.AddRange(triangles);
            verts.AddRange(vertices);
            norms.AddRange(normals.Length == vertices.Length ? normals : new Vector3[vertices.Length]);
            tans.AddRange(tangents.Length == vertices.Length ? tangents : new Vector4[vertices.Length]);
            uv0s.AddRange(uv0.Length == vertices.Length ? uv0 : new Vector2[vertices.Length]);
        }
        Mesh newMesh = new Mesh();

        newMesh.SetVertices(verts);
        newMesh.SetUVs(0, uv0s);
        newMesh.SetNormals(norms);
        newMesh.SetTangents(tans);
        newMesh.SetTriangles(tris, 0);
        Unwrapping.GenerateSecondaryUVSet(newMesh);
        return(newMesh);
    }