Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 18 additions & 4 deletions src/IfcIO/Geometry/IfcFaceTriangulator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,19 @@ private sealed record Ring(List<Point> 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<int>? Triangulate(IReadOnlyList<IfcVector3> vertices, IReadOnlyList<Bound> bounds)
internal static List<int>? Triangulate(
IReadOnlyList<IfcVector3> vertices, IReadOnlyList<Bound> 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<int>? TriangulateWithin(IReadOnlyList<IfcVector3> vertices, IReadOnlyList<Bound> bounds)
private static List<int>? TriangulateWithin(
IReadOnlyList<IfcVector3> vertices, IReadOnlyList<Bound> bounds, bool strictPolygon)
{
int workLeft = 20_000_000;
void Spend()
Expand Down Expand Up @@ -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<Ring>(bounds.Count);
foreach (var bound in bounds)
Expand Down Expand Up @@ -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<int>();
for (int i = 0; i < rings.Count; i++)
{
Expand Down
157 changes: 157 additions & 0 deletions src/IfcIO/IfcModel.IndexedFaces.cs
Original file line number Diff line number Diff line change
@@ -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<int>();
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<int>();
var faceVertices = new List<IfcVector3>();
var faceToGlobal = new List<int>();
var bounds = new List<IfcFaceTriangulator.Bound>();
var seenFaces = new HashSet<int>();

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<int>(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<string> 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<int> indices)
{
if (indices.Count == 0) return null;
var vertices = new List<IfcVector3>(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<int>(indices);
var sparseRemap = new Dictionary<int, int>(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);
}
}
84 changes: 12 additions & 72 deletions src/IfcIO/IfcModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2806,6 +2806,7 @@ private sealed class GeometryReadContext(
public Dictionary<int, (IfcMesh? Mesh, IfcMaterial? Material)> MappedRepresentations { get; } = [];
public HashSet<int> MapsInProgress { get; } = [];
public HashSet<string> BooleanWarnings { get; } = [];
public Dictionary<int, IfcVector3?[]> TessellatedPointLists { get; } = [];

/// <summary>
/// Cap on vertices materialised while reading nested mapped items and Boolean bodies.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 ||
Expand All @@ -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<IfcVector3>();
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<int>();
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<string> 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;

Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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);
}
}
Expand Down
Loading