From ea83b9ba67ca61b54c9e720a868da2fbdaef2dfc Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:15:08 +0300 Subject: [PATCH] Triangulate faceted IFC faces with holes and concave bounds --- CHANGELOG.md | 2 + docs/public-api.md | 3 + src/IfcIO/Geometry/IfcFaceTriangulator.cs | 367 ++++++++++++++++++++++ src/IfcIO/IfcModel.BrepFaces.cs | 111 +++++++ src/IfcIO/IfcModel.cs | 59 +--- tests/IfcIO.Tests/BrepFaceTests.cs | 199 ++++++++++++ 6 files changed, 683 insertions(+), 58 deletions(-) create mode 100644 src/IfcIO/Geometry/IfcFaceTriangulator.cs create mode 100644 src/IfcIO/IfcModel.BrepFaces.cs create mode 100644 tests/IfcIO.Tests/BrepFaceTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index aa9b29e..ee929f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes to the `IfcIO` library are documented in this file. ## [Unreleased] ### Fixed +- Faceted face import triangulates concave polygons and holes, keeps disjoint bounds as separate regions, + and omits invalid contours rather than substituting zero coordinates. - IFC import reads wrapped and direct surface colours, rendering transparency and material definition styles. Explicit geometry styles take precedence over associated material colours. - IFC import recognizes IFC4.3 separately and reports unknown, missing and multiple schema identifiers. IFC4.3 diff --git a/docs/public-api.md b/docs/public-api.md index e79058f..fe58c4f 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -46,6 +46,9 @@ among generated product GlobalIds and does not rewrite explicit GlobalIds. | `IfcProfileDef` | Base type for rectangular, circular, arbitrary closed polygon, I-, L-, and U-shaped profiles. | | `IfcExtrudedAreaSolid` | Extrudes a profile and exposes a triangulated mesh through `ToMesh`. | +For faceted faces, the reader triangulates planar concave bounds and holes without adding vertices. Disjoint +bounds remain separate regions. Invalid contours or faces that exceed the triangulation work limit are omitted. + ## Import & Export | Type | Description | diff --git a/src/IfcIO/Geometry/IfcFaceTriangulator.cs b/src/IfcIO/Geometry/IfcFaceTriangulator.cs new file mode 100644 index 0000000..68ce892 --- /dev/null +++ b/src/IfcIO/Geometry/IfcFaceTriangulator.cs @@ -0,0 +1,367 @@ +namespace IfcIO.Geometry; + +/// Triangulates the planar bounds of a faceted IFC face without adding vertices. +internal static class IfcFaceTriangulator +{ + internal readonly record struct Bound(IReadOnlyList Indices, bool IsOuter); + private readonly record struct Point(int Index, double X, double Y); + private readonly record struct Box(double MinX, double MinY, double MaxX, double MaxY) + { + internal bool Contains(Point p) => p.X >= MinX && p.X <= MaxX && p.Y >= MinY && p.Y <= MaxY; + internal bool Overlaps(Box other) => MinX <= other.MaxX && MaxX >= other.MinX && MinY <= other.MaxY && MaxY >= other.MinY; + internal static Box Segment(Point a, Point b) => new(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); + internal static Box Bounds(List ring) => new(ring.Min(p => p.X), ring.Min(p => p.Y), ring.Max(p => p.X), ring.Max(p => p.Y)); + } + + private sealed record Ring(List Points, double Area, Box Extent, bool IsConvex) + { + internal int Parent { get; set; } = -1; + } + + private const double Roundoff = 1.7763568394002505e-15; // eight ulps near one + private const int MaxFaceVertices = 32_768; + private sealed class WorkLimitException : Exception; + + internal static List? Triangulate(IReadOnlyList vertices, IReadOnlyList bounds) + { + if (bounds.Count == 0 || vertices.Count > MaxFaceVertices) return null; + try { return TriangulateWithin(vertices, bounds); } + catch (WorkLimitException) { return null; } + } + + private static List? TriangulateWithin(IReadOnlyList vertices, IReadOnlyList bounds) + { + int workLeft = 20_000_000; + void Spend() + { + if (--workLeft < 0) throw new WorkLimitException(); + } + + // Use the declared outer bound to orient the face. Use the largest nondegenerate loop if no outer was marked. + IfcVector3 normal = default; + double normalSize = 0; + bool foundOuter = false; + foreach (var bound in bounds) + { + if (bound.Indices.Count < 3) return null; + var origin = vertices[bound.Indices[0]]; + IfcVector3 sum = default; + for (int i = 1; i + 1 < bound.Indices.Count; i++) + sum += IfcVector3.Cross(vertices[bound.Indices[i]] - origin, vertices[bound.Indices[i + 1]] - origin); + double size = Math.Max(Math.Abs(sum.X), Math.Max(Math.Abs(sum.Y), Math.Abs(sum.Z))); + if (double.IsFinite(size) && size > 0 && (bound.IsOuter && !foundOuter || bound.IsOuter == foundOuter && size > normalSize)) + { + normal = sum; + normalSize = size; + foundOuter = bound.IsOuter; + } + } + if (normalSize == 0) return null; + + if (bounds is [{ Indices.Count: 3 } triangle]) + return [triangle.Indices[0], triangle.Indices[1], triangle.Indices[2]]; + + int axis = Math.Abs(normal.Z) == normalSize ? 2 : Math.Abs(normal.Y) == normalSize ? 1 : 0; + double orientation = Math.Sign(axis == 2 ? normal.Z : axis == 1 ? normal.Y : normal.X); + var anchor = vertices[bounds[0].Indices[0]]; + Point Project(int index) + { + var point = vertices[index] - anchor; + return axis switch + { + 0 => new Point(index, point.Y, orientation * point.Z), + 1 => new Point(index, point.Z, orientation * point.X), + _ => new Point(index, point.X, orientation * point.Y), + }; + } + + double scale = 0; + for (int i = 0; i < vertices.Count; i++) + { + var point = Project(i); + scale = Math.Max(scale, Math.Max(Math.Abs(point.X), Math.Abs(point.Y))); + } + if (!double.IsFinite(scale) || scale <= 0) return null; + + var rings = new List(bounds.Count); + foreach (var bound in bounds) + { + var points = new List(bound.Indices.Count); + foreach (int index in bound.Indices) + { + var p = Project(index); + var scaled = new Point(index, p.X / scale, p.Y / scale); + if (points.Count == 0 || !Same(points[^1], scaled)) points.Add(scaled); + } + if (points.Count > 1 && Same(points[0], points[^1])) points.RemoveAt(points.Count - 1); + double area = SignedArea(points); + if (points.Count < 3 || area == 0) return null; + bool convex = IsConvexInOrder(points, Math.Sign(area)); + if (!convex && !IsSimple(points)) return null; + rings.Add(new Ring(points, area, Box.Bounds(points), convex)); + } + + // IFC data in the wild may put separate islands in IfcFaceBound entries. The smallest + // containing ring is the parent; even levels are filled and odd levels are holes. + for (int i = 0; i < rings.Count; i++) + { + double bestArea = double.PositiveInfinity; + var inner = rings[i]; + for (int j = 0; j < rings.Count; j++) + { + if (i == j) continue; + Spend(); + var other = rings[j]; + if (!inner.Extent.Overlaps(other.Extent)) continue; + if (j > i && RingsIntersect(inner.Points, other.Points)) return null; + double area = Math.Abs(other.Area); + if (area <= Math.Abs(inner.Area) || area >= bestArea || !Inside(inner.Points[0], other)) continue; + inner.Parent = j; + bestArea = area; + } + } + + var output = new List(); + for (int i = 0; i < rings.Count; i++) + { + int depth = 0; + for (int ancestor = rings[i].Parent; ancestor >= 0; ancestor = rings[ancestor].Parent) depth++; + if ((depth & 1) != 0) continue; + var outerRing = rings[i]; + var outer = Oriented(outerRing, positive: true); + var holes = rings.Where(ring => ring.Parent == i).OrderByDescending(ring => ring.Extent.MaxX).ToList(); + if (holes.Count == 0 && outerRing.IsConvex) + { + for (int k = 1; k + 1 < outer.Count; k++) Add(outer[0], outer[k], outer[k + 1]); + continue; + } + + var polygon = new List(outer); + foreach (var holeRing in holes) + { + var hole = Oriented(holeRing, positive: false); + int holeIndex = 0; + for (int j = 1; j < hole.Count; j++) + if (hole[j].X > hole[holeIndex].X) holeIndex = j; + + var tip = hole[holeIndex]; + int target = -1; + var candidates = Enumerable.Range(0, polygon.Count).OrderBy(j => DistanceSquared(polygon[j], tip)); + foreach (int j in candidates) + { + Spend(); + var p = polygon[j]; + var extent = Box.Segment(tip, p); + if (!InWedge(polygon, j, tip) + || CrossesBoundary(tip, p, polygon, allowCoincidentEdge: false) + || holes.Any(ring => extent.Overlaps(ring.Extent) && CrossesBoundary(tip, p, ring.Points, allowCoincidentEdge: false)) + || !InsideRegion(new Point(-1, (p.X + tip.X) / 2, (p.Y + tip.Y) / 2), outerRing, holes)) + continue; + target = j; + break; + } + if (target < 0) return null; + var bridge = new List(hole.Count + 2); + for (int j = 0; j <= hole.Count; j++) bridge.Add(hole[(holeIndex + j) % hole.Count]); + bridge.Add(polygon[target]); + polygon.InsertRange(target + 1, bridge); + } + + double areaCovered = 0; + int cursor = 0; + while (polygon.Count > 3) + { + int ear = -1; + for (int offset = 0; offset < polygon.Count; offset++) + { + Spend(); + int j = (cursor + offset) % polygon.Count; + var a = polygon[(j + polygon.Count - 1) % polygon.Count]; + var b = polygon[j]; + var c = polygon[(j + 1) % polygon.Count]; + double twiceArea = Cross(a, b, c); + if (Turn(a, b, c) <= 0 || TriangleHasOtherPoint(a, b, c, polygon) + || CrossesBoundary(a, c, polygon, allowCoincidentEdge: true) + || !InsideRegion(Centroid(a, b, c), outerRing, holes)) continue; + ear = j; + areaCovered += twiceArea / 2; + Add(a, b, c); + break; + } + if (ear < 0) return null; + polygon.RemoveAt(ear); + cursor = ear % polygon.Count; + } + double lastArea = Cross(polygon[0], polygon[1], polygon[2]) / 2; + double expectedArea = Math.Abs(outerRing.Area) - holes.Sum(ring => Math.Abs(ring.Area)); + if (Turn(polygon[0], polygon[1], polygon[2]) <= 0 || expectedArea <= 0 + || Math.Abs(areaCovered + lastArea - expectedArea) > Math.Abs(outerRing.Area) * 1e-9) + return null; + Add(polygon[0], polygon[1], polygon[2]); + } + return output.Count == 0 ? null : output; + + void Add(Point a, Point b, Point c) + { + output.Add(a.Index); + output.Add(b.Index); + output.Add(c.Index); + } + + bool IsSimple(List ring) + { + for (int i = 0; i < ring.Count; i++) + for (int j = i + 2; j < ring.Count; j++) + { + if (i == 0 && j == ring.Count - 1) continue; + Spend(); + if (Intersects(ring[i], ring[i + 1], ring[j], ring[(j + 1) % ring.Count])) return false; + } + return true; + } + + bool RingsIntersect(List a, List b) + { + for (int i = 0; i < a.Count; i++) + for (int j = 0; j < b.Count; j++) + { + Spend(); + if (Intersects(a[i], a[(i + 1) % a.Count], b[j], b[(j + 1) % b.Count])) return true; + } + return false; + } + + bool Inside(Point point, Ring bound) + { + if (!bound.Extent.Contains(point)) return false; + var ring = bound.Points; + bool inside = false; + for (int i = 0; i < ring.Count; i++) + { + Spend(); + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + if ((a.Y > point.Y) != (b.Y > point.Y) && + point.X < a.X + (point.Y - a.Y) * (b.X - a.X) / (b.Y - a.Y)) + inside = !inside; + } + return inside; + } + + bool InsideRegion(Point point, Ring outer, List holes) => + Inside(point, outer) && !holes.Any(hole => Inside(point, hole)); + + bool CrossesBoundary(Point a, Point b, List ring, bool allowCoincidentEdge) + { + var extent = Box.Segment(a, b); + for (int i = 0; i < ring.Count; i++) + { + Spend(); + var c = ring[i]; + var d = ring[(i + 1) % ring.Count]; + if (!extent.Overlaps(Box.Segment(c, d))) continue; + bool sharedStart = Same(a, c) || Same(a, d), sharedEnd = Same(b, c) || Same(b, d); + if (sharedStart && sharedEnd) + { + if (!allowCoincidentEdge) return true; + continue; + } + if (!sharedStart && !sharedEnd) + { + if (Intersects(a, b, c, d)) return true; + continue; + } + // A common endpoint is allowed, but overlapping an edge leaving it is not. + var other = Same(a, c) || Same(b, c) ? d : c; + var unshared = sharedStart ? b : a; + if (OnSegment(a, b, other) || OnSegment(c, d, unshared)) return true; + } + return false; + } + + bool TriangleHasOtherPoint(Point a, Point b, Point c, List ring) + { + var extent = new Box(Math.Min(a.X, Math.Min(b.X, c.X)), Math.Min(a.Y, Math.Min(b.Y, c.Y)), + Math.Max(a.X, Math.Max(b.X, c.X)), Math.Max(a.Y, Math.Max(b.Y, c.Y))); + foreach (var p in ring) + { + Spend(); + if (!extent.Contains(p) || Same(p, a) || Same(p, b) || Same(p, c)) continue; + if (Turn(a, b, p) >= 0 && Turn(b, c, p) >= 0 && Turn(c, a, p) >= 0) + return true; + } + return false; + } + } + + private static List Oriented(Ring ring, bool positive) + { + var points = new List(ring.Points); + if ((ring.Area > 0) != positive) points.Reverse(); + return points; + } + + private static bool IsConvexInOrder(List ring, int winding) + { + // Strictly consistent turns alone would accept a star. Its edge directions wind more + // than once; a strictly convex boundary crosses the positive X ray exactly once. + int crossings = 0; + for (int i = 0; i < ring.Count; i++) + { + var a = ring[i]; + var b = ring[(i + 1) % ring.Count]; + var c = ring[(i + 2) % ring.Count]; + if (Turn(a, b, c) != winding) return false; + bool incoming = UpperHalf(a, b); + bool outgoing = UpperHalf(b, c); + if (winding > 0 ? !incoming && outgoing : incoming && !outgoing) crossings++; + } + return crossings == 1; + + static bool UpperHalf(Point a, Point b) => b.Y > a.Y || b.Y == a.Y && b.X >= a.X; + } + + private static bool InWedge(List ring, int index, Point target) + { + var a = ring[(index + ring.Count - 1) % ring.Count]; + var b = ring[index]; + var c = ring[(index + 1) % ring.Count]; + bool incoming = Turn(a, b, target) > 0; + bool outgoing = Turn(b, c, target) > 0; + return Turn(a, b, c) >= 0 ? incoming && outgoing : incoming || outgoing; + } + + private static bool Same(Point a, Point b) => a.X == b.X && a.Y == b.Y; + private static double DistanceSquared(Point a, Point b) => + (a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y); + + private static double Cross(Point a, Point b, Point c) => (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X); + private static int Turn(Point a, Point b, Point c) + { + // The tolerance follows the determinant terms, not the whole face. A small hole or a + // small region far from another contour does not become degenerate because of its size. + double left = (b.X - a.X) * (c.Y - a.Y); + double right = (b.Y - a.Y) * (c.X - a.X); + double tolerance = (Math.Abs(left) + Math.Abs(right)) * Roundoff; + double determinant = left - right; + return determinant > tolerance ? 1 : determinant < -tolerance ? -1 : 0; + } + private static Point Centroid(Point a, Point b, Point c) => new(-1, (a.X + b.X + c.X) / 3, (a.Y + b.Y + c.Y) / 3); + + private static double SignedArea(List ring) + { + double area = 0; + for (int i = 1; i + 1 < ring.Count; i++) area += Cross(ring[0], ring[i], ring[i + 1]); + return area / 2; + } + + private static bool OnSegment(Point a, Point b, Point p) => Box.Segment(a, b).Contains(p) && Turn(a, b, p) == 0; + + private static bool Intersects(Point a, Point b, Point c, Point d) + { + if (!Box.Segment(a, b).Overlaps(Box.Segment(c, d))) return false; + int abc = Turn(a, b, c), abd = Turn(a, b, d), cda = Turn(c, d, a), cdb = Turn(c, d, b); + return abc * abd < 0 && cda * cdb < 0 + || OnSegment(a, b, c) || OnSegment(a, b, d) || OnSegment(c, d, a) || OnSegment(c, d, b); + } +} diff --git a/src/IfcIO/IfcModel.BrepFaces.cs b/src/IfcIO/IfcModel.BrepFaces.cs new file mode 100644 index 0000000..a2a13be --- /dev/null +++ b/src/IfcIO/IfcModel.BrepFaces.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using IfcIO.Core; +using IfcIO.Geometry; + +namespace IfcIO; + +public sealed partial class IfcModel +{ + private static IfcMesh? ParseFacetedFaces(StepFile step, StepEntity item, IEnumerable faces, string meshName) + { + var vertices = new List(); + var indices = new List(); + var globalIndices = new Dictionary(); + var faceVertices = new List(); + var facePointIds = new List(); + var bounds = new List(); + + foreach (int faceId in faces) + { + var face = step.Find(faceId); + if (face is null || ReadReferenceList(face, 0) is not { Count: > 0 } boundIds) continue; + + // Stage a whole face so bad points do not alter the indices or bounding box of good faces. + faceVertices.Clear(); + facePointIds.Clear(); + bounds.Clear(); + bool valid = true; + foreach (int boundId in boundIds) + { + var bound = step.Find(boundId); + var loop = step.Find(bound?.GetRef(0)); + if (bound is null || bound.GetBool(1) is not bool orientation + || loop is null || !loop.Type.Equals("IFCPOLYLOOP", StringComparison.OrdinalIgnoreCase) + || ReadReferenceList(loop, 0) is not { Count: >= 3 } pointIds) + { + valid = false; + break; + } + + var points = new List(pointIds.Count); + foreach (int pointId in pointIds) + { + IfcVector3 point; + if (globalIndices.TryGetValue(pointId, out int existing)) + point = vertices[existing]; + else if (!TryReadFacetedPoint(step.Find(pointId), out point)) + { + valid = false; + break; + } + + points.Add(faceVertices.Count); + faceVertices.Add(point); + facePointIds.Add(pointId); + } + if (!valid) break; + if (!orientation) points.Reverse(); + bounds.Add(new IfcFaceTriangulator.Bound(points, bound.Type.Equals("IFCFACEOUTERBOUND", StringComparison.OrdinalIgnoreCase))); + } + if (!valid || IfcFaceTriangulator.Triangulate(faceVertices, bounds) is not { } triangles) continue; + + var faceToGlobal = new int[facePointIds.Count]; + for (int i = 0; i < facePointIds.Count; i++) + { + int pointId = facePointIds[i]; + if (!globalIndices.TryGetValue(pointId, out int index)) + { + index = vertices.Count; + globalIndices.Add(pointId, index); + vertices.Add(faceVertices[i]); + } + faceToGlobal[i] = index; + } + foreach (int i in triangles) indices.Add(faceToGlobal[i]); + } + + return indices.Count == 0 ? null : IfcMesh.Create(item.Id, meshName, vertices, indices); + } + + private static List? ReadReferenceList(StepEntity entity, int argument) + { + string? value = entity.GetRaw(argument); + if (value is not { Length: >= 2 } || value[0] != '(' || value[^1] != ')' + || value.AsSpan(1, value.Length - 2).TrimEnd().EndsWith(",")) return null; + var items = StepEntity.ParseArguments(value[1..^1]); + var ids = new List(items.Count); + foreach (var reference in items) + { + if (!reference.StartsWith('#') || !int.TryParse(reference.AsSpan(1), NumberStyles.None, + CultureInfo.InvariantCulture, out int id) || id <= 0) return null; + ids.Add(id); + } + return ids; + } + + private static bool TryReadFacetedPoint(StepEntity? point, out IfcVector3 value) + { + value = default; + if (point is null || !point.Type.Equals("IFCCARTESIANPOINT", StringComparison.OrdinalIgnoreCase) + || point.GetRaw(0) is not { Length: >= 2 } raw || raw[0] != '(' || raw[^1] != ')' + || raw.AsSpan(1, raw.Length - 2).TrimEnd().EndsWith(",")) return false; + var xyz = StepEntity.ParseArguments(raw[1..^1]); + if (xyz.Count != 3 || !Finite(xyz[0], out double x) || !Finite(xyz[1], out double y) || !Finite(xyz[2], out double z)) + return false; + value = new IfcVector3(x, y, z); + return true; + + static bool Finite(string token, out double number) => + double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out number) && double.IsFinite(number); + } +} diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index d05a2de..421195c 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -3282,65 +3282,8 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) itemEnt.Type.Equals("IFCSHELLBASEDSURFACEMODEL", StringComparison.OrdinalIgnoreCase)) { var shellIds = isBrep && itemEnt.GetRef(0) is int shellId ? [shellId] : itemEnt.GetRefList(0); - - var vertices = new List(); - var indices = new List(); - var pointIndexMap = new Dictionary(); - var faceIds = shellIds.SelectMany(id => step.Find(id)?.GetRefList(0) ?? []); - foreach (int faceId in faceIds) - { - var faceEnt = step.Find(faceId); - if (faceEnt is null) continue; - - var boundIds = faceEnt.GetRefList(0); - foreach (int boundId in boundIds) - { - var boundEnt = step.Find(boundId); - if (boundEnt is null) continue; - - int? loopId = boundEnt.GetRef(0); - var loopEnt = step.Find(loopId); - if (loopEnt is null || !loopEnt.Type.Equals("IFCPOLYLOOP", StringComparison.OrdinalIgnoreCase)) - continue; - - var ptIds = loopEnt.GetRefList(0); - var faceIndices = new List(ptIds.Count); - - foreach (int ptId in ptIds) - { - if (!pointIndexMap.TryGetValue(ptId, out int idx)) - { - var ptEnt = step.Find(ptId); - if (ptEnt is not null) - { - string coordStr = ptEnt.GetRaw(0) ?? string.Empty; - var coords = StepEntity.ParseArguments(coordStr.Trim('(', ')')); - double x = coords.Count > 0 && double.TryParse(coords[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double cx) ? cx : 0.0; - double y = coords.Count > 1 && double.TryParse(coords[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double cy) ? cy : 0.0; - double z = coords.Count > 2 && double.TryParse(coords[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double cz) ? cz : 0.0; - - idx = vertices.Count; - vertices.Add(new IfcVector3(x, y, z)); - pointIndexMap[ptId] = idx; - } - } - faceIndices.Add(idx); - } - - for (int i = 1; i + 1 < faceIndices.Count; i++) - { - indices.Add(faceIndices[0]); - indices.Add(faceIndices[i]); - indices.Add(faceIndices[i + 1]); - } - } - } - - if (vertices.Count >= 3 && indices.Count >= 3) - { - return IfcMesh.Create(itemEnt.Id, meshName, vertices, indices); - } + return ParseFacetedFaces(step, itemEnt, faceIds, meshName); } // IFCTRIANGULATEDFACESET (IFC4) diff --git a/tests/IfcIO.Tests/BrepFaceTests.cs b/tests/IfcIO.Tests/BrepFaceTests.cs new file mode 100644 index 0000000..caa7002 --- /dev/null +++ b/tests/IfcIO.Tests/BrepFaceTests.cs @@ -0,0 +1,199 @@ +using System.Globalization; +using System.Text; +using IfcIO.Geometry; +using Xunit; + +namespace IfcIO.Tests; + +public sealed class BrepFaceTests +{ + [Fact] + public void Open_TriangulatesAConcaveFaceWithoutSpillingPastTheBoundary() + { + var mesh = ReadFace( + [[(2, 1), (1, 1), (1, 2), (0, 2), (0, 0), (2, 0)]]); + + Assert.NotNull(mesh); + Assert.Equal(4, mesh.TriangleCount); + Assert.Equal(3.0, Area(mesh), 9); + Assert.All(Triangles(mesh), triangle => Assert.True(triangle.Z > 0)); + } + + [Fact] + public void Open_SubtractsContainedBoundsButKeepsADisjointRegion() + { + var mesh = ReadFace( + [[(0, 0), (4, 0), (4, 4), (0, 4)], + [(1, 1), (3, 1), (3, 3), (1, 3)], + [(5, 0), (6, 0), (6, 1), (5, 1)]]); + + Assert.NotNull(mesh); + Assert.Equal(13.0, Area(mesh), 9); + Assert.All(Triangles(mesh), triangle => Assert.True(triangle.Z > 0)); + Assert.DoesNotContain(TriangleCentroids(mesh), p => p.X > 1 && p.X < 3 && p.Y > 1 && p.Y < 3); + Assert.Contains(TriangleCentroids(mesh), p => p.X > 5); + } + + [Fact] + public void Open_ContainsANestedIslandAndSupportsMultipleHoles() + { + var mesh = ReadFace( + [[(0, 0), (10, 0), (10, 10), (0, 10)], + [(1, 1), (4, 1), (4, 4), (1, 4)], + [(2, 2), (3, 2), (3, 3), (2, 3)], + [(6, 6), (9, 6), (9, 9), (6, 9)]]); + + Assert.NotNull(mesh); + Assert.Equal(83.0, Area(mesh), 9); + Assert.Contains(TriangleCentroids(mesh), p => p.X > 2 && p.X < 3 && p.Y > 2 && p.Y < 3); + } + + [Fact] + public void Open_RespectsOuterBoundOrientation() + { + var mesh = ReadFace([[(0, 0), (3, 0), (3, 3), (0, 3)]], reverseOuter: true); + + Assert.NotNull(mesh); + Assert.Equal(9.0, Area(mesh), 9); + Assert.All(Triangles(mesh), triangle => Assert.True(triangle.Z < 0)); + } + + [Fact] + public void Open_OmitsTheFaceWhenAHoleHasAnInvalidCoordinate() + { + var mesh = ReadFace( + [[(0, 0), (4, 0), (4, 4), (0, 4)], [(1, 1), (3, 1), (3, 3), (1, 3)]], + invalidCoordinate: true); + + Assert.Null(mesh); + } + + [Fact] + public void Open_PreservesAreaAndWindingOfAnOffsetVerticalFaceWithAHole() + { + var mesh = ReadFace( + [[(0, 0), (4, 0), (4, 4), (0, 4)], [(1, 1), (3, 1), (3, 3), (1, 3)]], + vertical: true); + + Assert.NotNull(mesh); + Assert.Equal(12.0, Area(mesh), 9); + Assert.All(Triangles(mesh), triangle => Assert.True(triangle.Y < 0)); + Assert.All(mesh.Vertices, vertex => Assert.Equal(2_000_000.0, vertex.Y)); + } + + [Fact] + public void Open_RejectsCrossingBoundsRatherThanFillingAnAmbiguousHole() + { + var mesh = ReadFace( + [[(0, 0), (4, 0), (4, 4), (0, 4)], [(3, 1), (5, 1), (5, 3), (3, 3)]]); + + Assert.Null(mesh); + } + + [Fact] + public void Open_KeepsSmallContoursIndependentlyOfTheFaceExtent() + { + var separate = ReadFace([[(0, 0), (4, 0), (4, 4), (0, 4)], + [(2_000_000, 0), (2_000_001, 0), (2_000_001, 1), (2_000_000, 1)]]); + Assert.NotNull(separate); + Assert.Equal(17.0, Area(separate), 9); + + var hole = ReadFace([[(0, 0), (100, 0), (100, 100), (0, 100)], + [(50, 50), (50.00005, 50), (50.00005, 50.00005), (50, 50.00005)]]); + Assert.NotNull(hole); + Assert.Equal(8, hole.TriangleCount); + Assert.Equal(10_000.0 - 50e-6 * 50e-6, Area(hole), 10); + } + + [Fact] + public void Open_LargeConvexFaceDoesNotRequireQuadraticValidation() + { + const int size = 7_000; + var circle = Enumerable.Range(0, size).Select(index => + { + double angle = index * (2.0 * Math.PI / size); + return (Math.Cos(angle), Math.Sin(angle)); + }).ToArray(); + + var mesh = ReadFace([circle]); + + Assert.NotNull(mesh); + Assert.Equal(size - 2, mesh.TriangleCount); + Assert.Equal(size / 2.0 * Math.Sin(2.0 * Math.PI / size), Area(mesh), 8); + } + + [Fact] + public void Open_TriangulatesARegularGridOfHolesWithinTheWorkLimit() + { + List<(double X, double Y)[]> rings = [[(0, 0), (49, 0), (49, 49), (0, 49)]]; + for (int y = 1; y < 48; y += 3) + for (int x = 1; x < 48; x += 3) + rings.Add([(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)]); + + var mesh = ReadFace(rings); + + Assert.NotNull(mesh); + Assert.Equal(2_145.0, Area(mesh), 8); + } + + private static IfcMesh? ReadFace(List<(double X, double Y)[]> rings, + bool reverseOuter = false, bool invalidCoordinate = false, bool vertical = false) + { + var text = new StringBuilder(""" + ISO-10303-21; + HEADER; FILE_SCHEMA(('IFC2X3')); ENDSEC; + DATA; + #1=IFCWALL('01vctVUKr0kugbFTf53O9L',$,'Face test',$,$,$,#2,$); + #2=IFCPRODUCTDEFINITIONSHAPE($,$,(#3)); + #3=IFCSHAPEREPRESENTATION($,'Body','Brep',(#4)); + #4=IFCFACETEDBREP(#5); + #5=IFCCLOSEDSHELL((#6)); + """); + text.AppendLine(); + int next = 20; + var bounds = new List(); + for (int ring = 0; ring < rings.Count; ring++) + { + var pointIds = new List(); + for (int index = 0; index < rings[ring].Length; index++) + { + var (x, y) = rings[ring][index]; + int pointId = next++; + string coordinate = invalidCoordinate && ring == 1 && index == 0 ? "$" + : (vertical ? 1_000_000 + x : x).ToString(CultureInfo.InvariantCulture); + double worldY = vertical ? 2_000_000 : y; + double worldZ = vertical ? 3_000_000 + y : 0; + pointIds.Add($"#{pointId}"); + text.AppendLine(CultureInfo.InvariantCulture, $"#{pointId}=IFCCARTESIANPOINT(({coordinate},{worldY},{worldZ}));"); + } + int poly = next++; + text.AppendLine(CultureInfo.InvariantCulture, $"#{poly}=IFCPOLYLOOP(({string.Join(",", pointIds)}));"); + int bound = next++; + text.AppendLine(CultureInfo.InvariantCulture, $"#{bound}=IFCFACE{(ring == 0 ? "OUTER" : "")}BOUND(#{poly},.{(ring == 0 && reverseOuter ? "F" : "T")}.);"); + bounds.Add($"#{bound}"); + } + text.AppendLine(CultureInfo.InvariantCulture, $"#6=IFCFACE(({string.Join(",", bounds)}));"); + text.AppendLine("ENDSEC; END-ISO-10303-21;"); + var model = IfcModel.Open(new StringReader(text.ToString())); + return Assert.Single(model.AllElements).Mesh; + } + + private static IEnumerable Triangles(IfcMesh mesh) + { + for (int i = 0; i < mesh.Indices.Count; i += 3) + { + var a = mesh.Vertices[mesh.Indices[i]]; + var b = mesh.Vertices[mesh.Indices[i + 1]]; + var c = mesh.Vertices[mesh.Indices[i + 2]]; + yield return IfcVector3.Cross(b - a, c - a); + } + } + + private static IEnumerable TriangleCentroids(IfcMesh mesh) + { + for (int i = 0; i < mesh.Indices.Count; i += 3) + yield return (mesh.Vertices[mesh.Indices[i]] + mesh.Vertices[mesh.Indices[i + 1]] + mesh.Vertices[mesh.Indices[i + 2]]) * (1.0 / 3.0); + } + + private static double Area(IfcMesh mesh) => Triangles(mesh).Sum(n => n.Length) / 2.0; +}