diff --git a/CHANGELOG.md b/CHANGELOG.md index 48b16c0..264baa2 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 +- Import reads IFC4 and IFC4.3 `IfcPolygonalFaceSet` geometry, including concave polygons, holes and `PnIndex` + point reindexing. Invalid faces are omitted without altering the other faces. - Import reads additional concrete IFC products with a `Body` representation, including curtain walls, piles, ramps, furniture, distribution equipment, and IFC4.3 infrastructure elements. - Boolean import preserves nested operands and evaluates chains of plane clips. It reports skipped bounded diff --git a/docs/public-api.md b/docs/public-api.md index f4e99ed..7fa8b27 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -54,6 +54,9 @@ among generated product GlobalIds and does not rewrite explicit GlobalIds. 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. +IFC4 and IFC4.3 `IfcPolygonalFaceSet` import also triangulates indexed polygons and interior holes, +honours optional `PnIndex` remapping, and omits malformed faces. It keeps the resulting triangle mesh, +not the original indexed polygon groups. Imported meshes use world coordinates. If a swept body cannot be represented by one equivalent parametric solid, the reader keeps its placed mesh instead; IFC export writes that mesh rather than a partial or diff --git a/src/IfcIO/Geometry/IfcFaceTriangulator.cs b/src/IfcIO/Geometry/IfcFaceTriangulator.cs index 68ce892..fecfe60 100644 --- a/src/IfcIO/Geometry/IfcFaceTriangulator.cs +++ b/src/IfcIO/Geometry/IfcFaceTriangulator.cs @@ -19,17 +19,19 @@ private sealed record Ring(List Points, double Area, Box Extent, bool IsC } private const double Roundoff = 1.7763568394002505e-15; // eight ulps near one - private const int MaxFaceVertices = 32_768; + internal const int MaxFaceVertices = 32_768; private sealed class WorkLimitException : Exception; - internal static List? Triangulate(IReadOnlyList vertices, IReadOnlyList bounds) + internal static List? Triangulate( + IReadOnlyList vertices, IReadOnlyList bounds, bool strictPolygon = false) { if (bounds.Count == 0 || vertices.Count > MaxFaceVertices) return null; - try { return TriangulateWithin(vertices, bounds); } + try { return TriangulateWithin(vertices, bounds, strictPolygon); } catch (WorkLimitException) { return null; } } - private static List? TriangulateWithin(IReadOnlyList vertices, IReadOnlyList bounds) + private static List? TriangulateWithin( + IReadOnlyList vertices, IReadOnlyList bounds, bool strictPolygon) { int workLeft = 20_000_000; void Spend() @@ -82,6 +84,16 @@ Point Project(int index) scale = Math.Max(scale, Math.Max(Math.Abs(point.X), Math.Abs(point.Y))); } if (!double.IsFinite(scale) || scale <= 0) return null; + if (strictPolygon) + { + var scaledNormal = new IfcVector3(normal.X / normalSize, normal.Y / normalSize, normal.Z / normalSize); + // Measure distance relative to the face size, not the distance from the model origin. + foreach (var vertex in vertices) + { + double distance = IfcVector3.Dot(vertex - anchor, scaledNormal); + if (!double.IsFinite(distance) || Math.Abs(distance) > 1e-9 * scale) return null; + } + } var rings = new List(bounds.Count); foreach (var bound in bounds) @@ -121,6 +133,8 @@ Point Project(int index) } } + if (strictPolygon && (rings[0].Parent != -1 || rings.Skip(1).Any(ring => ring.Parent != 0))) return null; + var output = new List(); for (int i = 0; i < rings.Count; i++) { diff --git a/src/IfcIO/IfcModel.IndexedFaces.cs b/src/IfcIO/IfcModel.IndexedFaces.cs new file mode 100644 index 0000000..5823389 --- /dev/null +++ b/src/IfcIO/IfcModel.IndexedFaces.cs @@ -0,0 +1,157 @@ +using System.Globalization; +using IfcIO.Core; +using IfcIO.Geometry; + +namespace IfcIO; + +public sealed partial class IfcModel +{ + private static IfcMesh? ParseTriangulatedFaceSet(GeometryReadContext ctx, StepEntity item, string meshName) + { + var vertices = ReadTessellatedPoints(ctx, item.GetRef(0)); + if (vertices is null) return null; + + string? pointNumberList = item.GetRaw(4); + var pointNumbers = ParseStepList(pointNumberList); + if (pointNumberList is not null && pointNumbers.Count == 0) return null; + // Before IFC4 Addendum 2 this slot held NormalIndex, a list of triplets. + if (pointNumbers.Count > 0 && pointNumbers[0].StartsWith('(')) pointNumbers.Clear(); + + var indices = new List(); + foreach (var tuple in ParseStepList(item.GetRaw(3))) + { + var parts = ParseStepList(tuple); + if (parts.Count != 3 || !TryResolveVertex(parts[0], pointNumbers, vertices, out int a) + || !TryResolveVertex(parts[1], pointNumbers, vertices, out int b) + || !TryResolveVertex(parts[2], pointNumbers, vertices, out int c)) continue; + indices.Add(a); + indices.Add(b); + indices.Add(c); + } + + return CreateIndexedMesh(item.Id, meshName, vertices, indices); + } + + private static IfcMesh? ParsePolygonalFaceSet(GeometryReadContext ctx, StepEntity item, string meshName) + { + var vertices = ReadTessellatedPoints(ctx, item.GetRef(0)); + if (vertices is null) return null; + string? pointNumberList = item.GetRaw(3); + var pointNumbers = ParseStepList(pointNumberList); + if (pointNumberList is not null && pointNumbers.Count == 0) return null; + + var indices = new List(); + var faceVertices = new List(); + var faceToGlobal = new List(); + var bounds = new List(); + var seenFaces = new HashSet(); + + foreach (string reference in ParseStepList(item.GetRaw(2))) + { + if (!reference.StartsWith('#') || !int.TryParse(reference.AsSpan(1), NumberStyles.None, + CultureInfo.InvariantCulture, out int faceId) || faceId <= 0) continue; + // A repeated face is the same surface; do not triangulate it repeatedly. + if (!seenFaces.Add(faceId)) continue; + var face = ctx.Step.Find(faceId); + if (face is null) continue; + bool hasHoles = face.Type.Equals("IFCINDEXEDPOLYGONALFACEWITHVOIDS", StringComparison.OrdinalIgnoreCase); + if (!hasHoles && !face.Type.Equals("IFCINDEXEDPOLYGONALFACE", StringComparison.OrdinalIgnoreCase)) continue; + + faceVertices.Clear(); + faceToGlobal.Clear(); + bounds.Clear(); + if (!ReadRing(face.GetRaw(0), isOuter: true)) continue; + if (hasHoles) + { + var holes = ParseStepList(face.GetRaw(1)); + if (holes.Count == 0 || !holes.All(hole => ReadRing(hole, isOuter: false))) continue; + } + + if (IfcFaceTriangulator.Triangulate(faceVertices, bounds, strictPolygon: true) is not { } triangles) continue; + foreach (int local in triangles) indices.Add(faceToGlobal[local]); + } + + return CreateIndexedMesh(item.Id, meshName, vertices, indices); + + bool ReadRing(string? raw, bool isOuter) + { + var numbers = ParseStepList(raw); + if (numbers.Count < 3 || numbers.Count > IfcFaceTriangulator.MaxFaceVertices - faceVertices.Count) return false; + var ring = new List(numbers.Count); + foreach (string number in numbers) + { + if (!TryResolveVertex(number, pointNumbers, vertices, out int index)) return false; + ring.Add(faceVertices.Count); + faceVertices.Add(vertices[index].GetValueOrDefault()); + faceToGlobal.Add(index); + } + bounds.Add(new IfcFaceTriangulator.Bound(ring, isOuter)); + return true; + } + } + + private static IfcVector3?[]? ReadTessellatedPoints(GeometryReadContext ctx, int? id) + { + if (id is not int pointListId) return null; + if (ctx.TessellatedPointLists.TryGetValue(pointListId, out var cached)) return cached; + var pointList = ctx.Step.Find(pointListId); + if (pointList is null || !pointList.Type.Equals("IFCCARTESIANPOINTLIST3D", StringComparison.OrdinalIgnoreCase)) return null; + var tuples = ParseStepList(pointList.GetRaw(0)); + ctx.ChargeVertices(tuples.Count); + var points = new IfcVector3?[tuples.Count]; + for (int i = 0; i < tuples.Count; i++) + { + var xyz = ParseStepList(tuples[i]); + if (xyz.Count == 3 && TryCoordinate(xyz[0], out double x) + && TryCoordinate(xyz[1], out double y) && TryCoordinate(xyz[2], out double z)) + points[i] = new IfcVector3(x, y, z); + } + ctx.TessellatedPointLists.Add(pointListId, points); + return points; + + static bool TryCoordinate(string value, out double coordinate) => + double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out coordinate) && double.IsFinite(coordinate); + } + + private static bool TryResolveVertex(string token, List pointNumbers, IfcVector3?[] points, out int index) + { + index = 0; + if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out int number) || number <= 0) return false; + if (pointNumbers.Count > 0 && (number > pointNumbers.Count + || !int.TryParse(pointNumbers[number - 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out number))) return false; + if (number <= 0 || number > points.Length || !points[number - 1].HasValue) return false; + index = number - 1; + return true; + } + + private static IfcMesh? CreateIndexedMesh(int id, string name, IfcVector3?[] points, List indices) + { + if (indices.Count == 0) return null; + var vertices = new List(Math.Min(points.Length, indices.Count)); + if (indices.Count < points.Length / 4) + { + // Sparse sets must not scan or retain a large shared coordinate table. + var used = new HashSet(indices); + var sparseRemap = new Dictionary(used.Count); + foreach (int source in used.Order()) + { + sparseRemap.Add(source, vertices.Count); + vertices.Add(points[source].GetValueOrDefault()); + } + for (int i = 0; i < indices.Count; i++) indices[i] = sparseRemap[indices[i]]; + return IfcMesh.Create(id, name, vertices, indices); + } + + var remap = new int[points.Length]; + foreach (int index in indices) remap[index] = 1; + for (int i = 0; i < points.Length; i++) + { + if (remap[i] == 0) continue; + remap[i] = vertices.Count; + vertices.Add(points[i].GetValueOrDefault()); + } + if (vertices.Count != points.Length) + for (int i = 0; i < indices.Count; i++) indices[i] = remap[indices[i]]; + return IfcMesh.Create(id, name, vertices, indices); + } +} diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index c7f6a18..3a441ac 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -2806,6 +2806,7 @@ private sealed class GeometryReadContext( public Dictionary MappedRepresentations { get; } = []; public HashSet MapsInProgress { get; } = []; public HashSet BooleanWarnings { get; } = []; + public Dictionary TessellatedPointLists { get; } = []; /// /// Cap on vertices materialised while reading nested mapped items and Boolean bodies. @@ -2960,7 +2961,7 @@ public void ChargeVertices(int count) var step = ctx.Step; // A/B. Meshes (Brep / TriangulatedFaceSet / surface models) - var mesh = ParseMeshEntity(step, itemEnt, meshName); + var mesh = ParseMeshEntity(ctx, itemEnt, meshName); if (mesh is not null) return mesh; // C/D. IFCEXTRUDEDAREASOLID / IFCREVOLVEDAREASOLID @@ -3324,8 +3325,9 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) return null; } - private static IfcMesh? ParseMeshEntity(StepFile step, StepEntity itemEnt, string meshName = "Mesh") + private static IfcMesh? ParseMeshEntity(GeometryReadContext ctx, StepEntity itemEnt, string meshName = "Mesh") { + var step = ctx.Step; // IFCFACETEDBREP (one closed shell), IFCFACEBASEDSURFACEMODEL (connected face sets), IFCSHELLBASEDSURFACEMODEL (shells) bool isBrep = itemEnt.Type.Equals("IFCFACETEDBREP", StringComparison.OrdinalIgnoreCase); if (isBrep || @@ -3337,80 +3339,18 @@ private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) return ParseFacetedFaces(step, itemEnt, faceIds, meshName); } - // IFCTRIANGULATEDFACESET (IFC4) if (itemEnt.Type.Equals("IFCTRIANGULATEDFACESET", StringComparison.OrdinalIgnoreCase)) - { - int? ptListId = itemEnt.GetRef(0); - var ptListEnt = step.Find(ptListId); - if (ptListEnt is null) return null; - - var vertices = new List(); - foreach (var tuple in ParseStepList(ptListEnt.GetRaw(0))) - { - var parts = ParseStepList(tuple); - if (parts.Count != 3 || !TryCoordinate(parts[0], out double x) - || !TryCoordinate(parts[1], out double y) || !TryCoordinate(parts[2], out double z)) return null; - vertices.Add(new IfcVector3(x, y, z)); - } - - var pointNumbers = ParseStepList(itemEnt.GetRaw(4)); - // Before IFC4 Addendum 2 this attribute was NormalIndex (a list of triplets). - if (pointNumbers.Count > 0 && pointNumbers[0].StartsWith('(')) - pointNumbers.Clear(); - var indices = new List(); - foreach (var triTuple in ParseStepList(itemEnt.GetRaw(3))) - { - var parts = ParseStepList(triTuple); - if (parts.Count == 3 && TryVertexIndex(parts[0], out int i0) - && TryVertexIndex(parts[1], out int i1) && TryVertexIndex(parts[2], out int i2)) - { - indices.Add(i0); - indices.Add(i1); - indices.Add(i2); - } - } - - if (vertices.Count >= 3 && indices.Count >= 3) - { - var remap = new int[vertices.Count]; - foreach (int index in indices) remap[index] = 1; - int count = 0; - for (int i = 0; i < vertices.Count; i++) - { - if (remap[i] == 0) continue; - remap[i] = count; - vertices[count++] = vertices[i]; - } - if (count != vertices.Count) - { - vertices.RemoveRange(count, vertices.Count - count); - for (int i = 0; i < indices.Count; i++) indices[i] = remap[indices[i]]; - } - return IfcMesh.Create(itemEnt.Id, meshName, vertices, indices); - } - - static bool TryCoordinate(string text, out double value) => - double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value); - - bool TryVertexIndex(string text, out int index) - { - index = 0; - if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int number) || number <= 0) - return false; - if (pointNumbers.Count > 0 && (number > pointNumbers.Count - || !int.TryParse(pointNumbers[number - 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out number))) - return false; - if (number <= 0 || number > vertices.Count) return false; - index = number - 1; - return true; - } - } + return ParseTriangulatedFaceSet(ctx, itemEnt, meshName); + if (itemEnt.Type.Equals("IFCPOLYGONALFACESET", StringComparison.OrdinalIgnoreCase)) + return ParsePolygonalFaceSet(ctx, itemEnt, meshName); return null; } private static List ParseStepList(string? raw) => - raw is { Length: >= 2 } && raw[0] == '(' && raw[^1] == ')' ? StepEntity.ParseArguments(raw[1..^1]) : []; + raw is { Length: >= 2 } && raw[0] == '(' && raw[^1] == ')' + && !raw.AsSpan(1, raw.Length - 2).TrimEnd().EndsWith(",", StringComparison.Ordinal) + ? StepEntity.ParseArguments(raw[1..^1]) : []; private const int MaxBooleanDepth = 64; @@ -3454,7 +3394,7 @@ private static IfcBooleanResult ParseBooleanResult(GeometryReadContext ctx, Step boolResult.FirstSolid = extruded; boolResult.FirstRevolved = revolved; if (extruded is null && revolved is null) - boolResult.FirstMesh = sweptMesh ?? ParseMeshEntity(step, firstEnt); + boolResult.FirstMesh = sweptMesh ?? ParseMeshEntity(ctx, firstEnt); ctx.ChargeVertices((sweptMesh ?? boolResult.FirstMesh)?.Vertices.Count ?? 0); } } @@ -3476,7 +3416,7 @@ private static IfcBooleanResult ParseBooleanResult(GeometryReadContext ctx, Step boolResult.SecondSolid = extruded; boolResult.SecondRevolved = revolved; if (extruded is null) - boolResult.SecondMesh = sweptMesh ?? ParseMeshEntity(step, secondEnt); + boolResult.SecondMesh = sweptMesh ?? ParseMeshEntity(ctx, secondEnt); ctx.ChargeVertices((sweptMesh ?? boolResult.SecondMesh)?.Vertices.Count ?? 0); } } diff --git a/tests/IfcIO.Tests/PolygonalFaceSetTests.cs b/tests/IfcIO.Tests/PolygonalFaceSetTests.cs new file mode 100644 index 0000000..40df67c --- /dev/null +++ b/tests/IfcIO.Tests/PolygonalFaceSetTests.cs @@ -0,0 +1,113 @@ +using IfcIO.Geometry; +using Xunit; + +namespace IfcIO.Tests; + +public class PolygonalFaceSetTests +{ + private static IfcMesh? OpenMesh(string schema, string faces, string coordinateList, string faceRefs, string pointNumbers = "$") + { + string ifc = $$""" + ISO-10303-21; + HEADER; + FILE_SCHEMA(('{{schema}}')); + ENDSEC; + DATA; + #1=IFCPROJECT('0YvctVUKr0kugbFTf53O9L',$,'Indexed faces',$,$,$,$,(#7),#2); + #2=IFCUNITASSIGNMENT((#3)); + #3=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.); + #4=IFCCARTESIANPOINT((100.,200.,300.)); + #5=IFCAXIS2PLACEMENT3D(#4,$,$); + #6=IFCLOCALPLACEMENT($,#5); + #7=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#15,$); + #8=IFCCARTESIANPOINTLIST3D({{coordinateList}}{{(schema == "IFC4" ? "" : ",$")}}); + #9=IFCPOLYGONALFACESET(#8,.F.,{{faceRefs}},{{pointNumbers}}); + #10=IFCSHAPEREPRESENTATION(#7,'Body','Tessellation',(#9)); + #11=IFCPRODUCTDEFINITIONSHAPE($,$,(#10)); + #12=IFCWALL('1YvctVUKr0kugbFTf53O9L',$,'Wall',$,$,#6,#11,$,$); + #14=IFCCARTESIANPOINT((0.,0.,0.)); + #15=IFCAXIS2PLACEMENT3D(#14,$,$); + {{faces}} + ENDSEC; + END-ISO-10303-21; + """; + return Assert.Single(IfcModel.Open(new StringReader(ifc)).AllElements).Mesh; + } + + [Theory] + [InlineData("IFC4")] + [InlineData("IFC4X3_ADD2")] + public void Open_IndexedFaceWithHole_UsesPointNumbersAndPreservesPlacement(string schema) + { + var mesh = OpenMesh(schema, + "#20=IFCINDEXEDPOLYGONALFACEWITHVOIDS((1,2,3,4),((5,6,7,8)));", + "((1.,1.,0.),(3.,1.,0.),(3.,3.,0.),(1.,3.,0.),(0.,0.,0.),(4.,0.,0.),(4.,4.,0.),(0.,4.,0.),(1000.,0.,0.))", + "(#20)", "(5,6,7,8,1,4,3,2)"); + + Assert.NotNull(mesh); + Assert.Equal(8, mesh.Vertices.Count); + Assert.Equal(8, mesh.TriangleCount); + Assert.Equal(12, SignedArea(mesh), 9); + Assert.Equal(new IfcBoundingBox(new(100, 200, 300), new(104, 204, 300)), mesh.BoundingBox); + } + + [Fact] + public void Open_OmitsInvalidFacesAndKeepsConcavityAndOrientation() + { + var mesh = OpenMesh("IFC4", """ + #20=IFCINDEXEDPOLYGONALFACE((6,5,4,3,2,1)); + #21=IFCINDEXEDPOLYGONALFACE((1,2,99)); + #22=IFCINDEXEDPOLYGONALFACEWITHVOIDS((1,2,3),((1,0,2))); + """, + "((0.,0.,0.),(2.,0.,0.),(2.,1.,0.),(1.,1.,0.),(1.,2.,0.),(0.,2.,0.))", "(#20,#21,#22,#20)"); + + Assert.NotNull(mesh); + Assert.Equal(4, mesh.TriangleCount); + Assert.Equal(-3, SignedArea(mesh), 9); + } + + [Fact] + public void Open_IndexedFaceWithAnExteriorHole_DoesNotFillItAsAnIsland() + { + var mesh = OpenMesh("IFC4", "#20=IFCINDEXEDPOLYGONALFACEWITHVOIDS((1,2,3,4),((5,6,7)));", + "((0.,0.,0.),(4.,0.,0.),(4.,4.,0.),(0.,4.,0.),(5.,0.,0.),(6.,0.,0.),(6.,1.,0.))", "(#20)"); + Assert.Null(mesh); + } + + [Theory] + [InlineData("#20=IFCINDEXEDPOLYGONALFACE((1,2,3,4));", "((0.,0.,0.),(4.,0.,0.),(4.,4.,1.),(0.,4.,0.))")] + [InlineData("#20=IFCINDEXEDPOLYGONALFACE((1,2,3,));", "((0.,0.,0.),(4.,0.,0.),(4.,4.,0.))")] + [InlineData("#20=IFCINDEXEDPOLYGONALFACEWITHVOIDS((1,2,3,4),((5,6,7)));", + "((0.,0.,0.),(4.,0.,0.),(4.,4.,0.),(0.,4.,0.),(1.,1.,1.),(2.,1.,1.),(2.,2.,1.))")] + public void Open_MalformedFace_IsOmitted(string face, string coordinates) + { + Assert.Null(OpenMesh("IFC4", face, coordinates, "(#20)")); + } + + [Fact] + public void Open_GoodFacesShareVerticesEvenWithInvalidNeighbours() + { + var mesh = OpenMesh("IFC4", """ + #20=IFCINDEXEDPOLYGONALFACE((1,2,3)); + #21=IFCINDEXEDPOLYGONALFACE((1,3,4)); + #22=IFCINDEXEDPOLYGONALFACE((1,3,5)); + """, "((0.,0.,0.),(4.,0.,0.),(4.,4.,0.),(0.,4.,0.),($,0.,0.))", "(#20,$,#21,#22)"); + Assert.NotNull(mesh); + Assert.Equal(4, mesh.Vertices.Count); + Assert.Equal([0, 1, 2, 0, 2, 3], mesh.Indices); + Assert.Equal(16, SignedArea(mesh), 9); + } + + private static double SignedArea(IfcMesh mesh) + { + double sum = 0; + 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]]; + sum += IfcVector3.Cross(b - a, c - a).Z * 0.5; + } + return sum; + } +}