public TriangulatedSurface GetModifiedSurface(TriangulatedSurface surface, IOptions options) { var cutOptions = (TriangulatedSurfaceCutterOptions)options; List <Triangle3D> triangles = new List <Triangle3D>(); foreach (var triangle in surface.Triangles) { if (Equality.AreLessOrEqual(triangle.Points.Max(p => p.Z), cutOptions.CutDepth)) { triangles.Add(triangle); } else if (Equality.AreMoreOrEqual(triangle.Points.Min(p => p.Z), cutOptions.CutDepth)) { continue; } else { Point3D[] pointsToInclude = triangle.Points.Where(p => Equality.Less(p.Z, cutOptions.CutDepth)).ToArray(); List <IntersectionData> intersectionList = new List <IntersectionData>(); var intersect = Intersection(triangle.A, triangle.B, cutOptions.CutDepth); if (intersect != null) { intersectionList.Add(intersect.Value); } intersect = Intersection(triangle.B, triangle.C, cutOptions.CutDepth); if (intersect != null) { intersectionList.Add(intersect.Value); } intersect = Intersection(triangle.A, triangle.C, cutOptions.CutDepth); if (intersect != null) { intersectionList.Add(intersect.Value); } var firstPoint = pointsToInclude[0]; triangles.Add(new Triangle3D(firstPoint, intersectionList[0].Intersection, intersectionList[1].Intersection)); if (pointsToInclude.Length == 2) { var secondPoint = pointsToInclude[1]; if (intersectionList[0].HasPoint(secondPoint)) { triangles.Add(new Triangle3D(firstPoint, secondPoint, intersectionList[0].Intersection)); } else if (intersectionList[1].HasPoint(secondPoint)) { triangles.Add(new Triangle3D(firstPoint, secondPoint, intersectionList[1].Intersection)); } else { throw new Exception("Unexpected program behavior."); } } } } return(new TriangulatedSurface(triangles.ToArray())); }