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 reports missing or unreadable shape representation items, including items in partially readable
and mapped bodies, through the model, validation, CLI and scene adapter.
- Import meshes swept disks along open 3D polylines and linear indexed curves, including optional trimming,
mitered joints and hollow sections.
- Import reads IFC4 and IFC4.3 `IfcPolygonalFaceSet` geometry, including concave polygons, holes and `PnIndex`
Expand Down
7 changes: 7 additions & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ arcs and other curved directrices are not read by this path. Input curves must n
the mesher checks adjacent miters, not intersections between distant parts of the sweep.
A readable `Body-FallBack` takes precedence when the primary body has unreadable items.

`IfcModel.RepresentationImportWarnings` identifies missing representations or unreadable items by their original
STEP IDs and item type when known. It includes failed items in a body that used `Body-FallBack`, but not
unselected alternatives or individual faces within a usable mesh. Extraction and merge retain the warnings as
source diagnostics rather than revalidating the selected geometry. `SourceName` is a label, not a unique file ID;
pass distinct model names when identical filenames need to be distinguished. CLI geometry commands report the
warnings on standard error, and `Validate()` includes them as `IFC_GEOMETRY_IMPORT`.

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
misplaced solid. Boolean operands also use placed meshes where necessary. Applying arbitrary solid-to-solid
Expand Down
2 changes: 2 additions & 0 deletions docs/scene-adapter.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ rebases them, for example on `ComputeBounds().Center`, before narrowing them to

- Mapped items (`IfcMappedItem`) are baked into each element's world mesh, so shared geometry is not shared in the
scene.
- `skipped-representation-item` warnings identify unreadable IFC items by source STEP IDs, including when the
remaining items or a fallback still produce geometry. `missing-representation` reports unresolved representation references.
- IfcIO uses `IfcRelContainedInSpatialStructure` and passes known storey assignments to aggregated parts
(`IfcRelAggregates`). Products with no storey assignment are in the first storey. A file without storeys
gets IfcIO's default storey `Level 1`, which has no GlobalId. Site, building and project are not tree nodes.
Expand Down
5 changes: 5 additions & 0 deletions src/IfcIO.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ private static int ExecutePack(string[] args)
Console.WriteLine($"Packaging '{inputPath}' into '{outputPath}'...");
var sw = Stopwatch.StartNew();
var model = IfcModel.Open(inputPath);
WarnOnPartialImport(model);
model.SaveZip(outputPath);
sw.Stop();

Expand Down Expand Up @@ -427,6 +428,7 @@ private static int ExecuteUnpack(string[] args)
Console.WriteLine($"Extracting '{inputPath}' to '{outputPath}'...");
var sw = Stopwatch.StartNew();
var model = IfcModel.Open(inputPath);
WarnOnPartialImport(model);
model.Save(outputPath);
sw.Stop();

Expand Down Expand Up @@ -662,6 +664,8 @@ private static void WarnOnPartialImport(IfcModel model)
{
foreach (string warning in model.BooleanImportWarnings)
Console.Error.WriteLine($"Warning: {warning}");
foreach (var item in model.RepresentationImportWarnings)
Console.Error.WriteLine($"Warning: {item}");
if (model.Schema != IfcSchema.Ifc4x3) return;
Console.Error.WriteLine($"Warning: {model.SourceSchemaIdentifier} is read as a subset. Uninterpreted content is omitted.");
if (model.UnsupportedPlacementCount > 0)
Expand Down Expand Up @@ -976,6 +980,7 @@ private static int ExecuteImportCsv(string[] args)

var sw = Stopwatch.StartNew();
var model = IfcModel.Open(inputPath);
WarnOnPartialImport(model);
var (elems, props) = model.ImportCsv(csvPath, delimiter);
model.Save(outPath);
sw.Stop();
Expand Down
3 changes: 3 additions & 0 deletions src/IfcIO.Scene/IfcSceneReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ private static IfcSceneResult Convert(IfcModel model, string key, string? path,
});

var diagnostics = new List<SceneDiagnostic>();
foreach (var item in model.RepresentationImportWarnings)
diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, item.ItemId is null ? "missing-representation" : "skipped-representation-item",
item.ToString(), null));
var materials = new Dictionary<IfcMaterial, int>(ReferenceEqualityComparer.Instance);
var sets = new Dictionary<object, int>(ReferenceEqualityComparer.Instance);
var converted = new Dictionary<IfcElement, long>(ReferenceEqualityComparer.Instance);
Expand Down
3 changes: 3 additions & 0 deletions src/IfcIO.Scene/IfcSceneResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ internal IfcSceneResult(
/// <see cref="SceneDiagnostic.SourceId"/>: <c>no-geometry</c> (information: IfcIO returned no mesh),
/// <c>empty-mesh</c> or <c>invalid-mesh</c> (warnings: a mesh without triangles, or with a non-finite coordinate,
/// an index out of range or an index count not divisible by 3). These elements stay in the scene without geometry.
/// Source IFC items that could not be read also produce <c>skipped-representation-item</c> warnings,
/// even if their parent representation or an explicit fallback produced a usable mesh.
/// Unresolved representation references produce <c>missing-representation</c> warnings.
/// </summary>
public IReadOnlyList<SceneDiagnostic> Diagnostics { get; }

Expand Down
35 changes: 30 additions & 5 deletions src/IfcIO/IfcModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ public sealed partial class IfcModel

/// <summary>Boolean import warnings for skipped operands or operations not evaluated in the mesh.</summary>
public IReadOnlyList<string> BooleanImportWarnings { get; internal set; } = [];

/// <summary>Missing representations and unreadable items encountered during import.</summary>
public IReadOnlyList<IfcRepresentationImportWarning> RepresentationImportWarnings { get; internal set; } = [];
public IfcLengthUnit LengthUnit { get; set; } = IfcLengthUnit.Millimetre;
public IfcPlaneAngleUnit AngleUnit { get; set; } = IfcPlaneAngleUnit.Degree;

Expand Down Expand Up @@ -2515,6 +2518,10 @@ openElem is IfcOpeningElement opening &&

model._reservedElementIds.UnionWith(allElementsMap.Keys);
model.BooleanImportWarnings = geometry.BooleanWarnings.Order(StringComparer.Ordinal).ToArray();
if (geometry.RepresentationWarnings.Count > 0)
model.RepresentationImportWarnings = Array.AsReadOnly(geometry.RepresentationWarnings
.OrderBy(item => item.RepresentationId).ThenBy(item => item.ItemId)
.Select(item => item with { SourceName = modelName ?? step.FileName }).ToArray());
return model;
}

Expand Down Expand Up @@ -2808,6 +2815,7 @@ private sealed class GeometryReadContext(
public Dictionary<int, (IfcMesh? Mesh, IfcMaterial? Material, bool HasSkippedItems)> MappedRepresentations { get; } = [];
public HashSet<int> MapsInProgress { get; } = [];
public HashSet<string> BooleanWarnings { get; } = [];
public HashSet<IfcRepresentationImportWarning> RepresentationWarnings { get; } = [];
public Dictionary<int, IfcVector3?[]> TessellatedPointLists { get; } = [];

/// <summary>
Expand Down Expand Up @@ -2871,11 +2879,14 @@ public void CheckVertexBudget(long count)
var shapeDef = ctx.Step.Find(shapeDefId);
if (shapeDef is null) return null;

var reps = shapeDef.GetRefList(2)
.Select(id => ctx.Step.Find(id))
.OfType<StepEntity>()
.Where(r => r.Type.Equals("IFCSHAPEREPRESENTATION", StringComparison.OrdinalIgnoreCase))
.ToList();
var reps = new List<StepEntity>();
foreach (int id in shapeDef.GetRefList(2))
{
var representation = ctx.Step.Find(id);
if (representation is null) ctx.RepresentationWarnings.Add(new(id, null, null));
else if (representation.Type.Equals("IFCSHAPEREPRESENTATION", StringComparison.OrdinalIgnoreCase))
reps.Add(representation);
}

// A complete Body-FallBack can replace an incomplete Body, but not vice versa.
// Never substitute e.g. Clearance for Body on newly discovered products.
Expand Down Expand Up @@ -2947,6 +2958,7 @@ public void CheckVertexBudget(long count)
if (itemEnt is null)
{
hasSkippedItems = true;
ctx.RepresentationWarnings.Add(new(repEnt.Id, itemId, null));
continue;
}

Expand All @@ -2955,8 +2967,15 @@ public void CheckVertexBudget(long count)
if (mesh is null)
{
hasSkippedItems = true;
ctx.RepresentationWarnings.Add(new(repEnt.Id, itemId, itemEnt.Type));
continue;
}
if (mesh.TriangleCount == 0 && (itemParametric?.Boolean is not { } boolean || !HasBooleanBase(boolean)))
{
// Preserve incomplete Boolean metadata, but report that it contributed no geometry.
ctx.RepresentationWarnings.Add(new(repEnt.Id, itemId, itemEnt.Type));
hasSkippedItems = true;
}
hasSkippedItems |= skippedNestedItems;
material ??= itemMaterial;
// The Boolean reader already charges leaf meshes and triangles emitted by each clip.
Expand All @@ -2978,6 +2997,12 @@ public void CheckVertexBudget(long count)
foreach (int index in part.Indices) indices.Add(index + offset);
}
return IfcMesh.Create(parts[0].Id, meshName, vertices, indices);

static bool HasBooleanBase(IfcBooleanResult result)
{
while (result.FirstBoolean is { } child) result = child;
return result.FirstMesh is { TriangleCount: > 0 } || result.FirstSolid is not null || result.FirstRevolved is not null;
}
}

/// <summary>Reads one representation item into a mesh in the coordinates of its representation.</summary>
Expand Down
27 changes: 27 additions & 0 deletions src/IfcIO/IfcRepresentationImportWarning.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System.Globalization;

namespace IfcIO;

/// <summary>A missing representation or an item that could not be read.</summary>
/// <param name="RepresentationId">STEP entity ID of the shape representation.</param>
/// <param name="ItemId">STEP entity ID of the item, or null if the representation itself is missing.</param>
/// <param name="ItemType">STEP entity type, or null if the referenced entity is missing.</param>
public readonly record struct IfcRepresentationImportWarning(int RepresentationId, int? ItemId, string? ItemType)
{
/// <summary>Source model label or STEP header filename, when available.</summary>
public string? SourceName { get; init; }

public override string ToString()
{
string message = ItemId is null
? string.Create(CultureInfo.InvariantCulture, $"Missing representation #{RepresentationId}.")
: ItemType is null
? string.Create(CultureInfo.InvariantCulture, $"Representation #{RepresentationId}: missing item #{ItemId}.")
: string.Create(CultureInfo.InvariantCulture, $"Representation #{RepresentationId}: skipped item #{ItemId} ({ItemType}).");
if (string.IsNullOrWhiteSpace(SourceName)) return message;
string label = SourceName.Any(char.IsControl)
? new string(SourceName.Select(c => char.IsControl(c) ? ' ' : c).ToArray())
: SourceName;
return $"{message} Source: {label}";
}
}
2 changes: 2 additions & 0 deletions src/IfcIO/Patch/IfcPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ public static IfcModel Extract(IfcModel source, Func<IfcElement, bool> predicate
SourceSchemaIdentifier = source.SourceSchemaIdentifier,
UnsupportedPlacementCount = source.UnsupportedPlacementCount,
BooleanImportWarnings = source.BooleanImportWarnings,
RepresentationImportWarnings = source.RepresentationImportWarnings,
};
target.Storeys.Clear();

Expand Down Expand Up @@ -256,6 +257,7 @@ public static IfcModel Merge(IEnumerable<IfcModel> models, string mergedProjectN
AngleUnit = baseModel.AngleUnit,
Schema = modelList.Any(m => m.Schema == Schema.IfcSchema.Ifc4) ? Schema.IfcSchema.Ifc4 : Schema.IfcSchema.Ifc2x3,
BooleanImportWarnings = modelList.SelectMany(m => m.BooleanImportWarnings).ToArray(),
RepresentationImportWarnings = Array.AsReadOnly(modelList.SelectMany(m => m.RepresentationImportWarnings).ToArray()),
};
merged.Storeys.Clear();

Expand Down
10 changes: 10 additions & 0 deletions src/IfcIO/Validation/IfcValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,16 @@ public static IfcValidationResult Validate(IfcModel model)
});
}

foreach (var item in model.RepresentationImportWarnings)
{
issues.Add(new IfcValidationIssue
{
RuleId = "IFC_GEOMETRY_IMPORT",
Severity = IfcIssueSeverity.Warning,
Message = item.ToString(),
});
}

// 2. GlobalId uniqueness and format
var seenGuids = new Dictionary<string, string>(StringComparer.Ordinal);

Expand Down
14 changes: 14 additions & 0 deletions tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,20 @@ public void Read_Ifc4TriangulatedFaceSet_ConvertsGeometry()
Assert.Empty(result.Diagnostics);
}

[Fact]
public void Read_PartialBody_ReportsSkippedItemWithoutDroppingGeometry()
{
string ifc = PlacedIfc(Millimetre, "#119=IFCBOUNDINGBOX(#22,100.,100.,100.);")
.Replace("'Brep',(#106)", "'Brep',(#106,#119)", StringComparison.Ordinal);
var result = Valid(Read(OpenText(ifc)));

Assert.Equal(3, result.ElementsWithGeometry);
var warning = Assert.Single(result.Diagnostics);
Assert.Equal(SceneSeverity.Warning, warning.Severity);
Assert.Equal("skipped-representation-item", warning.Code);
Assert.Contains("Representation #105: skipped item #119 (IFCBOUNDINGBOX)", warning.Message, StringComparison.Ordinal);
}

[IfcFileFact]
public void Read_ConfiguredIfcFile_ConvertsEveryElement()
{
Expand Down
119 changes: 119 additions & 0 deletions tests/IfcIO.Tests/RepresentationImportTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
using IfcIO.Validation;
using Xunit;

namespace IfcIO.Tests;

public class RepresentationImportTests
{
private static IfcModel Read(string bodyItems, string additional = "", string representations = "#10", string? sourceName = null) =>
IfcModel.Open(new StringReader($$"""
ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('Synthetic geometry diagnostics'),'2;1');
FILE_NAME('body.ifc','2026-11-25T00:00:00',(''),(''),'','','');
FILE_SCHEMA(('IFC4'));
ENDSEC;
DATA;
#1=IFCPROJECT('0YvctVUKr0kugbFTf53O9L',$,'Geometry diagnostics',$,$,$,$,(#7),#2);
#2=IFCUNITASSIGNMENT((#3));
#3=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);
#4=IFCCARTESIANPOINT((0.,0.,0.));
#5=IFCAXIS2PLACEMENT3D(#4,$,$);
#7=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#5,$);
#9=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(10.,0.,0.),(0.,10.,0.)));
#10=IFCSHAPEREPRESENTATION(#7,'Body',$,({{bodyItems}}));
#11=IFCPRODUCTDEFINITIONSHAPE($,$,({{representations}}));
#12=IFCWALL('1YvctVUKr0kugbFTf53O9L',$,'Wall',$,$,$,#11,$,$);
#13=IFCTRIANGULATEDFACESET(#9,$,.F.,((1,2,3)),$);
#14=IFCBOUNDINGBOX(#4,10.,10.,10.);
{{additional}}
ENDSEC;
END-ISO-10303-21;
"""), sourceName);

[Fact]
public void Open_PartiallyReadBody_IdentifiesMissingAndUnsupportedItems()
{
var model = Read("#13,#14,#999");
Assert.Equal(1, Assert.Single(model.AllElements).Mesh!.TriangleCount);
Assert.Collection(model.RepresentationImportWarnings,
first =>
{
Assert.Equal(10, first.RepresentationId);
Assert.Equal(14, first.ItemId);
Assert.Equal("IFCBOUNDINGBOX", first.ItemType);
Assert.Equal("body.ifc", first.SourceName);
},
second =>
{
Assert.Equal(10, second.RepresentationId);
Assert.Equal(999, second.ItemId);
Assert.Null(second.ItemType);
});
var issues = model.Validate().Issues.Where(issue => issue.RuleId == "IFC_GEOMETRY_IMPORT");
Assert.Equal(2, issues.Count());
Assert.All(issues, issue => Assert.Equal(IfcIssueSeverity.Warning, issue.Severity));
}

[Fact]
public void Open_InstancedPartialBody_ReportsSourceItemOnce()
{
var model = Read("#23,#24", """
#20=IFCSHAPEREPRESENTATION(#7,'Body',$,(#13,#14));
#21=IFCREPRESENTATIONMAP(#5,#20);
#22=IFCCARTESIANTRANSFORMATIONOPERATOR3D($,$,#4,$,$);
#23=IFCMAPPEDITEM(#21,#22);
#24=IFCMAPPEDITEM(#21,#22);
""");
Assert.Equal(2, Assert.Single(model.AllElements).Mesh!.TriangleCount);
var skipped = Assert.Single(model.RepresentationImportWarnings);
Assert.Equal(20, skipped.RepresentationId);
Assert.Equal(14, skipped.ItemId);
}

[Fact]
public void Open_AlternativeRepresentationNotAttempted_IsNotReported()
{
var model = Read("#13", "#20=IFCSHAPEREPRESENTATION(#7,'Box','BoundingBox',(#14));", "#10,#20");
Assert.Empty(model.RepresentationImportWarnings);
}

[Fact]
public void Open_ExplicitFallbackPreservesGeometryAndWarningAboutPrimaryItem()
{
var model = Read("#14", "#20=IFCSHAPEREPRESENTATION(#7,'Body-FallBack','Tessellation',(#13));", "#10,#20");
Assert.Equal(1, Assert.Single(model.AllElements).Mesh!.TriangleCount);
Assert.Equal(new IfcRepresentationImportWarning(10, 14, "IFCBOUNDINGBOX") { SourceName = "body.ifc" },
Assert.Single(model.RepresentationImportWarnings));
}

[Fact]
public void Open_MissingRepresentation_IsReportedWithItsStepId()
{
var model = Read("#13", representations: "#999,#10");
Assert.NotNull(Assert.Single(model.AllElements).Mesh);
Assert.Equal(new IfcRepresentationImportWarning(999, null, null) { SourceName = "body.ifc" },
Assert.Single(model.RepresentationImportWarnings));
}

[Fact]
public void Open_BooleanWithoutReadableBase_ReportsTheItemInAPartialBody()
{
var model = Read("#13,#20", """
#20=IFCBOOLEANRESULT(.DIFFERENCE.,#21,#13);
#21=IFCBLOCK(#5,1.,1.,1.);
""");
Assert.Equal(1, Assert.Single(model.AllElements).Mesh!.TriangleCount);
Assert.Equal(new IfcRepresentationImportWarning(10, 20, "IFCBOOLEANRESULT") { SourceName = "body.ifc" },
Assert.Single(model.RepresentationImportWarnings));
}

[Fact]
public void Merge_RetainsSourceLabelsWhenStepIdsAreReused()
{
var a = Read("#14", sourceName: "A.ifc");
var b = Read("#14", sourceName: "B.ifc");
var merged = IfcIO.Patch.IfcPatch.Merge([a, b]);
Assert.Equal(["A.ifc", "B.ifc"], merged.RepresentationImportWarnings.Select(warning => warning.SourceName));
}
}