Unity-一种提取Mesh边缘的算法

文章目录[x]
  1. 0.1:步骤与原理
  2. 0.2:代码

如图所示找到一个Mesh的边缘并且绘制出来。

步骤与原理

1、获取目标网格上的所有顶点、三角面信息。

2、提取出网格上所有三角面的三条边。

3、比较所边缘信息,清除重复使用的边缘。如果一条边被重复使用,那它肯定不是边缘。

4、将为重复的边缘排序连成线,对有多边缘的形状,返回多条线。

5、使用LineRender组件将线绘制出来。

代码

using System.Collections.Generic;
using UnityEngine;

public class MeshVertexLineRenderer : MonoBehaviour
{
    public Material material;

    private void Start()
    {
        AddLine();
    }

    public void AddLine()
    {
        AddLine(GetComponent<MeshFilter>().sharedMesh, transform);
    }

    public void DeleteLine()
    {
        DeleteLine(transform);
    }

    private void AddLine(Mesh mesh, Transform parent)
    {
        DeleteLine(parent);


        Vector3[] meshVertices = mesh.vertices;
        List<List<Vector3>> vertices = TrianglesAndVerticesEdge(mesh.vertices, mesh.triangles);

        for (int i = 0; i < vertices.Count; i++)
            AddSingleLine(i, vertices[i].ToArray(), parent);
    }
    private void AddSingleLine(int index, Vector3[] vertices, Transform parent)
    {
        LineRenderer lineRenderer = new GameObject("MeshVertexLine_" + index, new System.Type[] { typeof(LineRenderer) }).GetComponent<LineRenderer>();
        lineRenderer.transform.parent = parent;
        lineRenderer.transform.localPosition = Vector3.zero;
        lineRenderer.transform.localRotation = Quaternion.identity;
        lineRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
        lineRenderer.receiveShadows = false;
        lineRenderer.allowOcclusionWhenDynamic = false;
        lineRenderer.motionVectorGenerationMode = MotionVectorGenerationMode.ForceNoMotion;
        lineRenderer.useWorldSpace = false;
        lineRenderer.loop = true;
        lineRenderer.widthMultiplier = 0.02f;
        lineRenderer.sortingLayerName = "GamePlay";
        lineRenderer.sortingOrder = 501;
        lineRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
        lineRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
        lineRenderer.alignment = LineAlignment.View;
        lineRenderer.textureMode = LineTextureMode.Tile;
        lineRenderer.material = material;

        lineRenderer.positionCount = vertices.Length;
        lineRenderer.SetPositions(vertices);
    }
    private void DeleteLine(Transform parent)
    {
        for (int i = 0; i < parent.childCount; i++)
        {
            if (parent.GetChild(i).name.Contains("MeshVertexLine"))
            {
                GameObject gameObject = parent.GetChild(i).gameObject;
                if (gameObject != null)
                {
                    i--;
#if UNITY_EDITOR
                    if (Application.isPlaying)
                    {
                        Object.Destroy(gameObject);
                    }
                    else
                    {
                        Object.DestroyImmediate(gameObject);
                    }
#else
                Object.Destroy(gameObject);
#endif
                }
            }
        }
    }
    /// <summary>
    /// 网格系统边缘查找,支持多边缘
    /// </summary>
    /// <param name="vertices"></param>
    /// <param name="triangles"></param>
    /// <returns></returns>
    private List<List<Vector3>> TrianglesAndVerticesEdge(Vector3[] vertices, int[] triangles)
    {
        List<Vector2Int> edgeLines = TrianglesEdgeAnalysis(triangles);
        List<List<Vector3>> result = SpliteLines(edgeLines, vertices);
        return result;
    }

    /// <summary>
    /// 三角面组边缘提取
    /// 适用于1.mesh顶点数量不太多的情况下。2.能共用顶点是同一个顶点(注意Unity中法线不同,顶点就不同)。
    /// </summary>
    /// <param name="triangles"></param>
    /// <param name="edges"></param>
    /// <param name="invalidFlag"></param>
    /// <returns></returns>
    private List<Vector2Int> TrianglesEdgeAnalysis(int[] triangles)
    {
        int[,] edges = new int[triangles.Length, 2];//把三角形分成三个线段
        for (int i = 0; i < triangles.Length; i += 3)
        {
            for (int j = 0; j < 3; j++)
            {
                for (int k = 0; k < 2; k++)
                {
                    int index = (j + k) % 3;
                    edges[i + j, k] = triangles[i + index];
                }
            }
        }
        bool[] invalidFlag = new bool[triangles.Length];
        for (int i = 0; i < triangles.Length; i++)
        {
            for (int j = i + 1; j < triangles.Length; j++)
            {
                //查找一个三角面的边是否与其他三角面共用一条边,如果是的话肯定不是边缘
                if ((edges[i, 0] == edges[j, 0] && edges[i, 1] == edges[j, 1]) || (edges[i, 0] == edges[j, 1] && edges[i, 1] == edges[j, 0]))
                {
                    invalidFlag[i] = true;
                    invalidFlag[j] = true;
                }
            }
        }
        List<Vector2Int> edgeLines = new List<Vector2Int>();
        for (int i = 0; i < triangles.Length; i++)
        {
            if (!invalidFlag[i])
            {
                edgeLines.Add(new Vector2Int(edges[i, 0], edges[i, 1]));
            }
        }
        if (edgeLines.Count == 0)
        {
            Debug.Log("Calculate wrong, there is not any valid line");
        }
        return edgeLines;
    }

    /// <summary>
    /// 边缘排序与分离
    /// </summary>
    /// <param name="edgeLines"></param>
    /// <param name="vertices"></param>
    /// <returns></returns>
    private List<List<Vector3>> SpliteLines(List<Vector2Int> edgeLines, Vector3[] vertices)
    {
        List<List<Vector3>> result = new List<List<Vector3>>();

        List<int> edgeIndex = new List<int>();
        int startIndex = edgeLines[0].x;
        edgeIndex.Add(edgeLines[0].x);
        int removeIndex = 0;
        int currentIndex = edgeLines[0].y;

        while (true)
        {
            edgeLines.RemoveAt(removeIndex);
            edgeIndex.Add(currentIndex);

            bool findNew = false;
            for (int i = 0; i < edgeLines.Count && !findNew; i++)
            {
                if (currentIndex == edgeLines[i].x)
                {
                    currentIndex = edgeLines[i].y;
                    removeIndex = i;
                    findNew = true;
                }
                else if (currentIndex == edgeLines[i].y)
                {
                    currentIndex = edgeLines[i].x;
                    removeIndex = i;
                    findNew = true;
                }
            }

            if (findNew && currentIndex == startIndex)
            {
                Debug.Log("Complete Closed curve");
                edgeLines.RemoveAt(removeIndex);
                List<Vector3> singleVertices = new List<Vector3>();
                for (int i = 0; i < edgeIndex.Count; i++)
                    singleVertices.Add(vertices[edgeIndex[i]]);
                result.Add(singleVertices);

                if (edgeLines.Count > 0)
                {
                    edgeIndex = new List<int>();
                    startIndex = edgeLines[0].x;
                    edgeIndex.Add(edgeLines[0].x);
                    removeIndex = 0;
                    currentIndex = edgeLines[0].y;
                }
                else
                {
                    break;
                }
            }
            else if (!findNew)
            {
                Debug.Log("Complete curve, but not closed");
                List<Vector3> singleVertices = new List<Vector3>();
                for (int i = 0; i < edgeIndex.Count; i++)
                    singleVertices.Add(vertices[edgeIndex[i]]);
                result.Add(singleVertices);

                if (edgeLines.Count > 0)
                {
                    edgeIndex = new List<int>();
                    startIndex = edgeLines[0].x;
                    edgeIndex.Add(edgeLines[0].x);
                    removeIndex = 0;
                    currentIndex = edgeLines[0].y;
                }
                else
                {
                    break;
                }
            }
        }

        return result;
    }
}

原文链接:https://blog.csdn.net/qq_37043683/article/details/81029979

相关链接:https://answers.unity.com/questions/566779/how-to-find-the-vertices-of-each-edge-on-mesh.html

源码下载:http://horse7.cn/download/meshedgedetection.unitypackage

点赞
  1. 宇哥说道:

    3D模型边缘重线,有什么好的解决方法吗?

    1. Alan Alan说道:

      这种算法不能去除重线。

发表回复

昵称和uid可以选填一个,填邮箱必填(留言回复后将会发邮件给你)
tips:输入uid可以快速获得你的昵称和头像(已失效)