/// <summary> /// Constructs a new polygon. /// </summary> /// <remarks>A plane is created using first three vertices.</remarks> /// <param name="vertices">A list of vertices that define the outline of the polygon.</param> /// <param name="shared"> An identifier of shared properties.</param> public Polygon(IList<Vertex> vertices, int shared) { if (vertices == null || vertices.Count < 3) { throw new ArgumentException("Not enough vertices."); } #if DEBUG if (vertices.Count == 3) // No need to check triangles. { // Check if all vertices are on the same plane. List<Vector3> edgeVectors = new List<Vector3>(vertices.Count); for (int i = 1; i < vertices.Count; i++) { edgeVectors.Insert(i - 1, vertices[i].Position - vertices[i - 1].Position); } // Insert last edge. edgeVectors.Add(vertices[0].Position - vertices[vertices.Count - 1].Position); // Check if all edges are coplanar. for (int i = 2; i < edgeVectors.Count; i++) { if (Vector3.Mixed(edgeVectors[i], edgeVectors[i - 1], edgeVectors[i - 2]) > MathHelpers.ZeroTolerance) { throw new ArgumentException("Vertices are not coplanar."); } } } #endif this.Plane = new Plane(vertices[0].Position, vertices[1].Position, vertices[2].Position); #if DEBUG Plane.PlaneRelativePositionClass position = Plane.PlaneRelativePositionClass.Coplanar; // Check if the polygon is convex. for (int i = 0; i < vertices.Count; i++) { Vector3 previousVertex = vertices[(i == 0) ? vertices.Count - 1 : i - 1].Position; Vector3 currentVertex = vertices[i].Position; Vector3 nextVertex = vertices[(i + 1) % vertices.Count].Position; // Plane formed by edge between previous vertex and current one and a vector // that is parallel to polygon's normal and originates from current vertex. ConstructiveSolidGeometry.Plane planeBefore = new Plane(currentVertex, previousVertex, this.Plane.Normal + currentVertex); position |= planeBefore.RelativePosition(nextVertex); if (position == Plane.PlaneRelativePositionClass.Spanning) { throw new ArgumentException("Given list of vertices does not form a convex polygon."); } } #endif this.Vertices = vertices.ToList(); this.Shared = shared; }