Exemple #1
0
        public void SortVerticesCW()
        {
            // calculate center of polygon
            Vec3 center = Vec3.zero;

            for (int i = 0; i < NumberOfVertices; i++)
            {
                center += Verts[i].P;
            }

            center /= NumberOfVertices;

            // sort vertices
            for (int i = 0; i < NumberOfVertices - 2; i++)
            {
                Vec3  a = Vec3.zero;
                Plane p;
                float smallestAngle = -1;
                int   smallest      = -1;

                a = Verts[i].P - center;
                a.Normalize();

                p = new Plane(Verts[i].P, center, center + P.Normal);
                for (int j = i + 1; j < NumberOfVertices; j++)
                {
                    if (p.ClassifyPoint(Verts[j].P) != PointClassification.BACK)
                    {
                        Vec3  b = Vec3.zero;
                        float angle;

                        b = Verts[j].P - center;
                        b.Normalize();

                        angle = Vec3.Dot(a, b);

                        if (angle > smallestAngle)
                        {
                            smallestAngle = angle;
                            smallest      = j;
                        }
                    }
                }

                if (smallest == -1)
                {
                    //throw new MalformedPolyException("Polygon has less than 3 vertices!");
                    return;
                }

                Vertex t = Verts[smallest];
                Verts[smallest] = Verts[i + 1];
                Verts[i + 1]    = t;
            }

            // check if vertex order needs to be reversed for back-facing polygon
            Plane oldPlane = P;

            CalculatePlane();
            if (Vec3.Dot(P.Normal, oldPlane.Normal) < 0)
            {
                int j = NumberOfVertices;
                for (int i = 0; i < j / 2; i++)
                {
                    Vertex v = Verts[i];
                    Verts[i]     = Verts[j - i];
                    Verts[j - i] = v;
                }
            }
        }