重心插值算法(三角形像素插值算法)

重心插值算法

    /// 
    /// 获取三角形内某点的颜色
    /// 
    /// 三角形顶点位置列表
    /// 三角形顶点颜色列表
    /// 三角形内某位置
    /// 
    public Color GetTriangleBarycenterColor(Vector3[] triangles, Color[] trianglesColor, Vector3 pointPosition)
    {
        var A = triangles[0];
        var B = triangles[1];
        var C = triangles[2];

        float a = (-(pointPosition.x - B.x) * (C.y - B.y) + (pointPosition.y - B.y) * (C.x - B.x)) / (-(A.x - B.x) * (C.y - B.y) + (A.y - B.y) * (C.x - B.x));
        float b = (-(pointPosition.x - C.x) * (A.y - C.y) + (pointPosition.y - C.y) * (A.x - C.x)) / (-(B.x - C.x) * (A.x - C.y) + (B.y - C.y) * (A.x - C.x));
        float c = 1 - a - b;

        //Debug.LogError($"a : {a}  b :{b}  c:{c}");

        Color colorA = trianglesColor[0];
        Color colorB = trianglesColor[1];
        Color colorC = trianglesColor[2];
        return colorA * a + colorB * b + colorC * c;
    }

    /// 
    /// 顶点是否位于三角形内
    /// 
    /// 顶点位置
    /// 三角形顶点
    /// 
    private bool IsPointInTriangle(Vector3 point, Vector3[] triangles)
    {
        var A = triangles[0];
        var B = triangles[1];
        var C = triangles[2];
        var v0 = C - A;
        var v1 = B - A;
        var v2 = point - A;

        float dot00 = Vector3.Dot(v0, v0);
        float dot01 = Vector3.Dot(v0, v1);
        float dot02 = Vector3.Dot(v0, v2);
        float dot11 = Vector3.Dot(v1, v1);
        float dot12 = Vector3.Dot(v1, v2);

        float inverDeno = 1 / (dot00 * dot11 - dot01 * dot01);

        float u = (dot11 * dot02 - dot01 * dot12) * inverDeno;
        if (u < 0 || u > 1) // if u out of range, return directly
        {
            return false;
        }

        float v = (dot00 * dot12 - dot01 * dot02) * inverDeno;
        if (v < 0 || v > 1) // if v out of range, return directly
        {
            return false;
        }

        return u + v <= 1;
    }

你可能感兴趣的:(重心插值算法(三角形像素插值算法))