From 32b89327a1280155894e8f1be5191cbad0b50d5c Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:33:40 +0300 Subject: [PATCH] Allocate model-wide element IDs and protect generated IFC GUIDs --- CHANGELOG.md | 2 + docs/public-api.md | 5 + src/IfcIO/Api/IfcApi.cs | 46 +----- .../Compatibility/Clash/IfcClashDetector.cs | 14 +- src/IfcIO/IfcModel.cs | 149 +++++++++++++++--- src/IfcIO/Model/IfcModelTypes.cs | 85 ++++++++-- src/IfcIO/Patch/IfcPatch.cs | 6 +- .../IfcIO.Scene.Tests/IfcSceneReaderTests.cs | 6 +- tests/IfcIO.Tests/ClashDetectorTests.cs | 24 +++ tests/IfcIO.Tests/IfcModelTests.cs | 117 ++++++++++++++ 10 files changed, 363 insertions(+), 91 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2cf39b..d16b247 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 +- Element factories allocate IDs across the model rather than per storey; the writer avoids generated GlobalId + collisions, and clash storey filters no longer confuse distinct elements that share a caller-assigned ID. - IFC export declares feet and inches as conversion-based length units and respects the selected plane angle unit. Revolved-solid geometry converts between the file's angle unit and radians in memory. The CLI labels storey elevations in the model's units. - Length quantities follow the model length unit after import, and metre-based cost quantities retain their explicit unit. diff --git a/docs/public-api.md b/docs/public-api.md index 5261621..2b756ee 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -26,6 +26,11 @@ declaration. For a file known to have this legacy error, use `IfcModel.Open(path, new IfcReadOptions { LegacyIfcIoRevolvedAnglesInRadians = true })`, then save the model, or run `ifcio patch old.ifc --legacy-ifcio-radian-sweeps -o repaired.ifc`. +Factory methods allocate element IDs across a model's storeys, including after import. Create storeys with +`IfcModel.AddStorey`, or pass a caller-created storey to a model factory before calling its own factories. +Factory calls reserve IDs already in the registered storeys' element and space lists. Export avoids collisions +among generated product GlobalIds and does not rewrite explicit GlobalIds. + ## Geometry & Representation | Type | Description | diff --git a/src/IfcIO/Api/IfcApi.cs b/src/IfcIO/Api/IfcApi.cs index 997229b..fa7e69a 100644 --- a/src/IfcIO/Api/IfcApi.cs +++ b/src/IfcIO/Api/IfcApi.cs @@ -119,7 +119,7 @@ public static void AssignContainer(IfcBuildingStorey storey, params IfcElement[] { if (!storey.Elements.Contains(el)) { - storey.Elements.Add(el); + storey.AddExistingElement(el); } } } @@ -143,64 +143,28 @@ public static IfcBuildingStorey CreateStorey(IfcModel model, string name, double public static IfcElement CreateWall(IfcBuildingStorey storey, string name, IfcMesh? mesh = null, IfcMaterial? material = null) { ArgumentNullException.ThrowIfNull(storey); - var wall = new IfcElement - { - Id = storey.Elements.Count + 1, - Name = name, - IfcType = "IFCWALL", - Mesh = mesh, - Material = material - }; - storey.Elements.Add(wall); - return wall; + return storey.AddWall(name, mesh, material); } /// Creates and adds an IFCSLAB element to a storey. public static IfcElement CreateSlab(IfcBuildingStorey storey, string name, IfcMesh? mesh = null, IfcMaterial? material = null) { ArgumentNullException.ThrowIfNull(storey); - var slab = new IfcElement - { - Id = storey.Elements.Count + 1, - Name = name, - IfcType = "IFCSLAB", - Mesh = mesh, - Material = material - }; - storey.Elements.Add(slab); - return slab; + return storey.AddSlab(name, mesh, material); } /// Creates and adds an IFCCOLUMN element to a storey. public static IfcElement CreateColumn(IfcBuildingStorey storey, string name, IfcMesh? mesh = null, IfcMaterial? material = null) { ArgumentNullException.ThrowIfNull(storey); - var column = new IfcElement - { - Id = storey.Elements.Count + 1, - Name = name, - IfcType = "IFCCOLUMN", - Mesh = mesh, - Material = material - }; - storey.Elements.Add(column); - return column; + return storey.AddColumn(name, mesh, material); } /// Creates and adds an IFCBEAM element to a storey. public static IfcElement CreateBeam(IfcBuildingStorey storey, string name, IfcMesh? mesh = null, IfcMaterial? material = null) { ArgumentNullException.ThrowIfNull(storey); - var beam = new IfcElement - { - Id = storey.Elements.Count + 1, - Name = name, - IfcType = "IFCBEAM", - Mesh = mesh, - Material = material - }; - storey.Elements.Add(beam); - return beam; + return storey.AddBeam(name, mesh, material); } } } diff --git a/src/IfcIO/Compatibility/Clash/IfcClashDetector.cs b/src/IfcIO/Compatibility/Clash/IfcClashDetector.cs index bd26935..65f83d3 100644 --- a/src/IfcIO/Compatibility/Clash/IfcClashDetector.cs +++ b/src/IfcIO/Compatibility/Clash/IfcClashDetector.cs @@ -46,7 +46,7 @@ public static IfcClashReport DetectClashes(IfcModel modelA, IfcModel modelB, Ifc new IfcVector3(boxA.Max.X + tol, boxA.Max.Y + tol, boxA.Max.Z + tol) ); - storeyMapA.TryGetValue(elemA.Id, out var sA); + storeyMapA.TryGetValue(elemA, out var sA); foreach (var (elemB, meshB) in elemsB) { @@ -55,7 +55,7 @@ public static IfcClashReport DetectClashes(IfcModel modelA, IfcModel modelB, Ifc continue; } - if (options.ExcludeSameStorey && sA is not null && storeyMapB.TryGetValue(elemB.Id, out var sB) && sA.Name.Equals(sB.Name, StringComparison.OrdinalIgnoreCase)) + if (options.ExcludeSameStorey && sA is not null && storeyMapB.TryGetValue(elemB, out var sB) && sA.Name.Equals(sB.Name, StringComparison.OrdinalIgnoreCase)) { continue; } @@ -120,7 +120,7 @@ public static IfcClashReport DetectClashes(IfcModel model, IfcClashOptions? opti new IfcVector3(boxA.Max.X + tol, boxA.Max.Y + tol, boxA.Max.Z + tol) ); - storeyMap.TryGetValue(elemA.Id, out var sA); + storeyMap.TryGetValue(elemA, out var sA); for (int j = i + 1; j < count; j++) { @@ -131,7 +131,7 @@ public static IfcClashReport DetectClashes(IfcModel model, IfcClashOptions? opti continue; } - if (options.ExcludeSameStorey && sA is not null && storeyMap.TryGetValue(elemB.Id, out var sB) && sA.Name.Equals(sB.Name, StringComparison.OrdinalIgnoreCase)) + if (options.ExcludeSameStorey && sA is not null && storeyMap.TryGetValue(elemB, out var sB) && ReferenceEquals(sA, sB)) { continue; } @@ -188,14 +188,14 @@ private static bool BoxesOverlap(IfcBoundingBox a, IfcBoundingBox b) return list; } - private static Dictionary BuildStoreyMap(IfcModel model) + private static Dictionary BuildStoreyMap(IfcModel model) { - var map = new Dictionary(); + var map = new Dictionary(ReferenceEqualityComparer.Instance); foreach (var storey in model.Storeys) { foreach (var elem in storey.Elements) { - map[elem.Id] = storey; + map[elem] = storey; } } return map; diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index 64e6d40..54e2fd2 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -47,11 +47,51 @@ public sealed partial class IfcModel public IEnumerable AllPorts => AllElements.SelectMany(e => e.Ports); private bool _hasCustomStorey; + private readonly HashSet _reservedElementIds = []; + private int _nextElementId = 1; public IfcModel() { // Default storey - Storeys.Add(new IfcBuildingStorey { Name = "Level 1", Elevation = 0.0 }); + RegisterStorey(new IfcBuildingStorey { Name = "Level 1", Elevation = 0.0 }); + } + + internal int AllocateElementId(IfcBuildingStorey? targetStorey = null) + { + foreach (var storey in Storeys) + AttachStorey(storey); + if (targetStorey is not null && targetStorey.Model != this) + AttachStorey(targetStorey); + while (!_reservedElementIds.Add(_nextElementId)) + { + if (_nextElementId == int.MaxValue) + throw new InvalidOperationException("The model has exhausted its positive element IDs."); + _nextElementId++; + } + return _nextElementId; + } + + internal void ReserveElementIds(IfcElement element) + { + _reservedElementIds.Add(element.Id); + foreach (var opening in element.Openings) + { + _reservedElementIds.Add(opening.Id); + if (opening.Filling is { } filling) + _reservedElementIds.Add(filling.Id); + } + } + + private void AttachStorey(IfcBuildingStorey storey) + { + if (storey.Model is null) storey.Model = this; + storey.SynchronizeIds(this); + } + + internal void RegisterStorey(IfcBuildingStorey storey) + { + AttachStorey(storey); + Storeys.Add(storey); } /// Creates a new empty IFC model with the specified project name and schema. @@ -70,6 +110,7 @@ public IfcBuildingStorey AddStorey(string name, double elevation = 0.0) var existing = Storeys.Find(s => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (existing is not null) { + AttachStorey(existing); _hasCustomStorey = true; existing.Elevation = elevation; return existing; @@ -86,7 +127,7 @@ public IfcBuildingStorey AddStorey(string name, double elevation = 0.0) _hasCustomStorey = true; var storey = new IfcBuildingStorey { Name = name, Elevation = elevation }; - Storeys.Add(storey); + RegisterStorey(storey); return storey; } @@ -110,7 +151,9 @@ public void AddElement(IfcElement element, IfcBuildingStorey? storey = null) { ArgumentNullException.ThrowIfNull(element); storey ??= Storeys[0]; - storey.Elements.Add(element); + AttachStorey(storey); + ReserveElementIds(element); + storey.AddExistingElement(element); } /// Creates and adds an element with a 3D mesh geometry to the model. @@ -124,7 +167,7 @@ public IfcElement AddMesh( { storey ??= Storeys[0]; - int nextId = storey.Elements.Count + 1; + int nextId = AllocateElementId(storey); var mesh = IfcMesh.Create(nextId, name, vertices, indices); var element = new IfcElement @@ -141,7 +184,7 @@ public IfcElement AddMesh( Materials.Add(material); } - storey.Elements.Add(element); + storey.AddExistingElement(element); return element; } @@ -158,7 +201,7 @@ public IfcElement AddExtrudedRectangle( string? ifcType = null) { storey ??= Storeys[0]; - int nextId = storey.Elements.Count + 1; + int nextId = AllocateElementId(storey); var profile = new IfcRectangleProfileDef(xDim, yDim, name: $"{name}_Profile"); var solid = new IfcExtrudedAreaSolid(profile, depth, position, direction); @@ -176,7 +219,7 @@ public IfcElement AddExtrudedRectangle( Materials.Add(material); } - storey.Elements.Add(element); + storey.AddExistingElement(element); return element; } @@ -192,7 +235,7 @@ public IfcElement AddExtrudedCircle( string? ifcType = null) { storey ??= Storeys[0]; - int nextId = storey.Elements.Count + 1; + int nextId = AllocateElementId(storey); var profile = new IfcCircleProfileDef(radius, name: $"{name}_Profile"); var solid = new IfcExtrudedAreaSolid(profile, depth, position, direction); @@ -210,7 +253,7 @@ public IfcElement AddExtrudedCircle( Materials.Add(material); } - storey.Elements.Add(element); + storey.AddExistingElement(element); return element; } @@ -226,7 +269,7 @@ public IfcElement AddRevolvedSolid( string? ifcType = null) { storey ??= Storeys[0]; - int nextId = storey.Elements.Count + 1; + int nextId = AllocateElementId(storey); var solid = new IfcRevolvedAreaSolid(profile, angle, position, axis); var element = new IfcElement @@ -243,7 +286,7 @@ public IfcElement AddRevolvedSolid( Materials.Add(material); } - storey.Elements.Add(element); + storey.AddExistingElement(element); return element; } @@ -281,7 +324,9 @@ public IfcOpeningElement AddOpening( { ArgumentNullException.ThrowIfNull(hostElement); - int nextId = (AllOpenings.Count() + 1) * 1000 + hostElement.Id; + ReserveElementIds(hostElement); + if (filling is not null) ReserveElementIds(filling); + int nextId = AllocateElementId(); var opening = new IfcOpeningElement { Id = nextId, @@ -308,7 +353,7 @@ public IfcSpace AddSpace( IfcMesh? mesh = null) { storey ??= Storeys[0]; - int nextId = (storey.Elements.Count + storey.Spaces.Count + 1) * 10; + int nextId = AllocateElementId(storey); var space = new IfcSpace { Id = nextId, @@ -321,7 +366,7 @@ public IfcSpace AddSpace( GrossVolume = grossFloorArea * height, Mesh = mesh, }; - storey.Spaces.Add(space); + storey.AddExistingSpace(space); return space; } @@ -434,7 +479,7 @@ public IfcElement AddClippedSolid( ArgumentNullException.ThrowIfNull(plane); storey ??= Storeys[0]; - int nextId = storey.Elements.Count + 1; + int nextId = AllocateElementId(storey); var halfSpace = new IfcHalfSpaceSolid(plane, agreementFlag); var booleanResult = new IfcBooleanResult(solid, halfSpace, IfcBooleanOperator.Difference); @@ -738,6 +783,20 @@ public void Save(TextWriter writer, string fileName = "model.ifc") var storeyIds = new List(); var typeToElementsMap = new Dictionary>(); var elementEntityMap = new Dictionary(); + var productGuids = new HashSet(StringComparer.Ordinal); + var duplicatedProductIds = ReserveProductIdentities(productGuids); + int nextCollision = 2; + + string ProductGuid(IfcElement element, string domain) + { + if (element.GlobalId is { } assigned) return assigned; + string generated = IfcGuid.FromElementId(element.Id, domain); + if (duplicatedProductIds.Contains((element.Id, domain)) || productGuids.Contains(generated)) + generated = IfcGuid.FromKey(domain + ":" + element.DuplicateIdentity); + while (!productGuids.Add(generated)) + generated = IfcGuid.FromElementId(element.Id, domain + ":" + (nextCollision++).ToString(CultureInfo.InvariantCulture)); + return generated; + } bool useTessellation = (Schema == IfcSchema.Ifc4 && UseTessellationInIfc4); @@ -760,7 +819,7 @@ public void Save(TextWriter writer, string fileName = "model.ifc") int prodShapeId = WriteElementShape(w, element, bodySubContextId, styleCache, useTessellation); - string elemGuid = element.GlobalId ?? IfcGuid.FromElementId(element.Id, "IfcIO"); + string elemGuid = ProductGuid(element, "IfcIO"); string ifcType = !string.IsNullOrEmpty(element.IfcType) ? element.IfcType : ClassifyElement(element.Name, element.Material?.Name); @@ -778,7 +837,7 @@ public void Save(TextWriter writer, string fileName = "model.ifc") $"{StepWriter.Ref(prodPlacementId)},{StepWriter.Ref(worldPlacement3dId)}"); int openShapeId = WriteElementShape(w, opening, bodySubContextId, styleCache, useTessellation); - string openGuid = opening.GlobalId ?? IfcGuid.FromElementId(opening.Id, "IfcIO-Opening"); + string openGuid = ProductGuid(opening, "IfcIO-Opening"); int openElemId = w.Add("IFCOPENINGELEMENT", $"{StepWriter.Str(openGuid)},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(opening.Name)},$,$,{StepWriter.Ref(openPlacementId)},{StepWriter.Ref(openShapeId)},{StepWriter.Str(opening.Tag ?? opening.Id.ToString(CultureInfo.InvariantCulture))},.OPENING."); @@ -792,7 +851,7 @@ public void Save(TextWriter writer, string fileName = "model.ifc") $"{StepWriter.Ref(openPlacementId)},{StepWriter.Ref(worldPlacement3dId)}"); int fillShapeId = WriteElementShape(w, filling, bodySubContextId, styleCache, useTessellation); - string fillGuid = filling.GlobalId ?? IfcGuid.FromElementId(filling.Id, "IfcIO-Filling"); + string fillGuid = ProductGuid(filling, "IfcIO-Filling"); string fillType = !string.IsNullOrEmpty(filling.IfcType) ? filling.IfcType : ClassifyElement(filling.Name, filling.Material?.Name); @@ -836,7 +895,7 @@ public void Save(TextWriter writer, string fileName = "model.ifc") } string spaceShapeRef = spaceShapeId > 0 ? StepWriter.Ref(spaceShapeId) : "$"; - string spaceGuid = space.GlobalId ?? IfcGuid.FromElementId(space.Id, "IfcIO-Space"); + string spaceGuid = ProductGuid(space, "IfcIO-Space"); string intExt = space.InteriorOrExteriorSpace == IfcInternalOrExternal.External ? ".EXTERNAL." : ".INTERNAL."; int spaceId = w.Add("IFCSPACE", @@ -1420,6 +1479,53 @@ private void WritePropertyAndQuantitySets(StepWriter w, IfcElement element, int } } + private HashSet<(int Id, string Domain)> ReserveProductIdentities(HashSet guids) + { + var generatedIds = new HashSet<(int Id, string Domain)>(); + var duplicates = new HashSet<(int Id, string Domain)>(); + void Reserve(string? guid) + { + if (guid is not null) guids.Add(guid); + } + + void Product(IfcElement element, string domain) + { + if (element.GlobalId is { } guid) Reserve(guid); + else if (!generatedIds.Add((element.Id, domain))) duplicates.Add((element.Id, domain)); + } + + foreach (var type in TypeProducts) Reserve(type.GlobalId); + foreach (var group in Groups) Reserve(group.GlobalId); + foreach (var system in Systems) Reserve(system.GlobalId); + foreach (var zone in Zones) Reserve(zone.GlobalId); + foreach (var schedule in WorkSchedules) + { + Reserve(schedule.GlobalId); + foreach (var task in schedule.AllTasks) Reserve(task.GlobalId); + } + foreach (var schedule in CostSchedules) + { + Reserve(schedule.GlobalId); + foreach (var item in schedule.AllCostItems) Reserve(item.GlobalId); + } + foreach (var storey in Storeys) + { + Reserve(storey.GlobalId); + foreach (var element in storey.Elements) + { + Product(element, "IfcIO"); + foreach (var port in element.Ports) Reserve(port.GlobalId); + foreach (var opening in element.Openings) + { + Product(opening, "IfcIO-Opening"); + if (opening.Filling is { } filling) Product(filling, "IfcIO-Filling"); + } + } + foreach (var space in storey.Spaces) Product(space, "IfcIO-Space"); + } + return duplicates; + } + /// Parses an existing IFC STEP file (.ifc or .ifczip) from disk into a structured model. public static IfcModel Open(string path) => Open(path, options: null); @@ -1514,14 +1620,14 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions Elevation = (sEnt.GetReal(9) ?? 0.0) * geometryScale, GlobalId = sEnt.GetString(0), }; - model.Storeys.Add(storey); + model.RegisterStorey(storey); storeyMap[sEnt.Id] = storey; } if (model.Storeys.Count == 0) { var defStorey = new IfcBuildingStorey { Name = "Level 1", Elevation = 0.0 }; - model.Storeys.Add(defStorey); + model.RegisterStorey(defStorey); } // 3. Parse Materials & Styles @@ -2425,6 +2531,7 @@ openElem is IfcOpeningElement opening && } } + model._reservedElementIds.UnionWith(allElementsMap.Keys); return model; } diff --git a/src/IfcIO/Model/IfcModelTypes.cs b/src/IfcIO/Model/IfcModelTypes.cs index c5c27a8..c4fa521 100644 --- a/src/IfcIO/Model/IfcModelTypes.cs +++ b/src/IfcIO/Model/IfcModelTypes.cs @@ -1,3 +1,4 @@ +using IfcIO.Core; using IfcIO.Geometry; namespace IfcIO.Model; @@ -225,33 +226,82 @@ public sealed class IfcBuildingStorey public string? GlobalId { get; set; } public List Elements { get; } = []; public List Spaces { get; } = []; + internal IfcModel? Model { get; set; } + private IfcModel? _snapshotModel; + private List.Enumerator _elementsSnapshot; + private List.Enumerator _spacesSnapshot; - public IfcElement AddWall(string name, IfcMesh? mesh = null, IfcMaterial? material = null) + internal void SynchronizeIds(IfcModel model) { - var wall = new IfcElement { Id = Elements.Count + 1, Name = name, IfcType = "IFCWALL", Mesh = mesh, Material = material }; - Elements.Add(wall); - return wall; + // The public lists are mutable. A copied enumerator detects edits, including replacement at + // the same index, without rescanning every product on normal factory calls. + if (ReferenceEquals(_snapshotModel, model) && Unchanged(_elementsSnapshot) && Unchanged(_spacesSnapshot)) return; + foreach (var element in Elements) model.ReserveElementIds(element); + foreach (var space in Spaces) model.ReserveElementIds(space); + if (ReferenceEquals(Model, model)) RecordSnapshot(model); } - public IfcElement AddSlab(string name, IfcMesh? mesh = null, IfcMaterial? material = null) + internal void AddExistingElement(IfcElement element) { - var slab = new IfcElement { Id = Elements.Count + 1, Name = name, IfcType = "IFCSLAB", Mesh = mesh, Material = material }; - Elements.Add(slab); - return slab; + if (Model is { } model) + { + SynchronizeIds(model); + model.ReserveElementIds(element); + } + Elements.Add(element); + if (Model is not null) RecordSnapshot(Model); } - public IfcElement AddColumn(string name, IfcMesh? mesh = null, IfcMaterial? material = null) + internal void AddExistingSpace(IfcSpace space) { - var col = new IfcElement { Id = Elements.Count + 1, Name = name, IfcType = "IFCCOLUMN", Mesh = mesh, Material = material }; - Elements.Add(col); - return col; + if (Model is { } model) + { + SynchronizeIds(model); + model.ReserveElementIds(space); + } + Spaces.Add(space); + if (Model is not null) RecordSnapshot(Model); } - public IfcElement AddBeam(string name, IfcMesh? mesh = null, IfcMaterial? material = null) + private void RecordSnapshot(IfcModel model) { - var beam = new IfcElement { Id = Elements.Count + 1, Name = name, IfcType = "IFCBEAM", Mesh = mesh, Material = material }; - Elements.Add(beam); - return beam; + _snapshotModel = model; + _elementsSnapshot = Elements.GetEnumerator(); + _spacesSnapshot = Spaces.GetEnumerator(); + } + + private static bool Unchanged(List.Enumerator snapshot) + { + try + { + snapshot.MoveNext(); + return true; + } + catch (InvalidOperationException) + { + return false; + } + } + + public IfcElement AddWall(string name, IfcMesh? mesh = null, IfcMaterial? material = null) => + AddProduct(name, "IFCWALL", mesh, material); + + public IfcElement AddSlab(string name, IfcMesh? mesh = null, IfcMaterial? material = null) => + AddProduct(name, "IFCSLAB", mesh, material); + + public IfcElement AddColumn(string name, IfcMesh? mesh = null, IfcMaterial? material = null) => + AddProduct(name, "IFCCOLUMN", mesh, material); + + public IfcElement AddBeam(string name, IfcMesh? mesh = null, IfcMaterial? material = null) => + AddProduct(name, "IFCBEAM", mesh, material); + + private IfcElement AddProduct(string name, string type, IfcMesh? mesh, IfcMaterial? material) + { + int id = Model?.AllocateElementId(this) ?? + checked(1 + Elements.Concat(Spaces).Select(element => element.Id).Prepend(0).Max()); + var product = new IfcElement { Id = id, Name = name, IfcType = type, Mesh = mesh, Material = material }; + AddExistingElement(product); + return product; } } @@ -283,6 +333,9 @@ public IfcPropertySet GetOrCreatePropertySet(string name) /// public class IfcElement { + private string? _duplicateIdentity; + internal string DuplicateIdentity => _duplicateIdentity ??= IfcGuid.NewGuid(); + public required int Id { get; init; } public required string Name { get; set; } public string IfcType { get; set; } = "IFCBUILDINGELEMENTPROXY"; diff --git a/src/IfcIO/Patch/IfcPatch.cs b/src/IfcIO/Patch/IfcPatch.cs index 5573d9e..267b877 100644 --- a/src/IfcIO/Patch/IfcPatch.cs +++ b/src/IfcIO/Patch/IfcPatch.cs @@ -213,7 +213,7 @@ public static IfcModel Extract(IfcModel source, Func predicate targetStorey.Elements.Add(clone); } - target.Storeys.Add(targetStorey); + target.RegisterStorey(targetStorey); } return target; @@ -270,13 +270,13 @@ public static IfcModel Merge(IEnumerable models, string mergedProjectN Name = storey.Name, Elevation = storey.Elevation, }; - merged.Storeys.Add(targetStorey); + merged.RegisterStorey(targetStorey); } foreach (var elem in storey.Elements) { var clone = CloneElement(elem, nextId++); - targetStorey.Elements.Add(clone); + merged.AddElement(clone, targetStorey); } } } diff --git a/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs b/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs index 6e3c3dc..373467b 100644 --- a/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs +++ b/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs @@ -360,10 +360,10 @@ public void Read_SpacesOnlyWhenIncluded() [Fact] public void Read_DuplicateElementIds_Throws() { - // A model built in memory numbers elements per storey, so two storeys both start at 1. + // The adapter still rejects collisions when callers supply IDs themselves. var model = IfcModel.Create("Duplicates"); - model.AddMesh("A", Mm(Triangle), [0, 1, 2]); - model.AddMesh("B", Mm(Triangle), [0, 1, 2], storey: model.AddStorey("Level 2", 3000)); + var first = model.AddMesh("A", Mm(Triangle), [0, 1, 2]); + model.AddElement(new IfcElement { Id = first.Id, Name = "B", Mesh = first.Mesh }, model.AddStorey("Level 2", 3000)); var ex = Assert.Throws(() => Read(model)); Assert.Contains("used twice", ex.Message, StringComparison.Ordinal); diff --git a/tests/IfcIO.Tests/ClashDetectorTests.cs b/tests/IfcIO.Tests/ClashDetectorTests.cs index a1b05ef..3ca2213 100644 --- a/tests/IfcIO.Tests/ClashDetectorTests.cs +++ b/tests/IfcIO.Tests/ClashDetectorTests.cs @@ -73,6 +73,30 @@ public void DetectClashes_SelfClash_FindsCollisionsWithinSameModel() Assert.Equal("Column 1", report.Clashes[0].ElementB.Name); } + [Fact] + public void DetectClashes_DuplicateUserIdsDoNotHideCrossStoreyClashes() + { + var model = IfcModel.Create("Storey clash"); + var lower = model.AddStorey("Lower"); + var upper = model.AddStorey("Upper", 3); + model.AddElement(new IfcElement + { + Id = 1, Name = "Beam", IfcType = "IFCBEAM", + Solid = new IfcExtrudedAreaSolid(new IfcRectangleProfileDef(6, 0.3), 0.5, new IfcVector3(0, 0, 3)), + }, lower); + model.AddElement(new IfcElement + { + Id = 1, Name = "Column", IfcType = "IFCCOLUMN", + Solid = new IfcExtrudedAreaSolid(new IfcRectangleProfileDef(0.4, 0.4), 4, new IfcVector3(2, 0, 0)), + }, upper); + + var report = model.DetectClashes(new IfcClashOptions { ExcludeSameStorey = true }); + + var clash = Assert.Single(report.Clashes); + Assert.Equal("Beam", clash.ElementA.Name); + Assert.Equal("Column", clash.ElementB.Name); + } + [Fact] public void ClashReport_SaveJson_OutputsValidJson() { diff --git a/tests/IfcIO.Tests/IfcModelTests.cs b/tests/IfcIO.Tests/IfcModelTests.cs index 9a3ce3f..13ec9b1 100644 --- a/tests/IfcIO.Tests/IfcModelTests.cs +++ b/tests/IfcIO.Tests/IfcModelTests.cs @@ -1,6 +1,7 @@ using System.Buffers.Binary; using System.IO.Compression; using System.Text.Json; +using IfcIO.Api; using IfcIO.Core; using IfcIO.Geometry; using IfcIO.Model; @@ -11,6 +12,122 @@ namespace IfcIO.Tests; public class IfcModelTests { + [Fact] + public void Factories_AllocateDistinctIdsAndExportDistinctGlobalIdsAcrossStoreys() + { + var model = IfcModel.Create("Two levels", IfcSchema.Ifc4); + var lower = model.AddStorey("Lower"); + var upper = model.AddStorey("Upper", 3000); + var wall = lower.AddWall("Wall"); + IfcApi.Root.CreateBeam(upper, "Beam"); + model.AddExtrudedRectangle("Column", 250, 250, 3000, storey: upper, ifcType: "IFCCOLUMN"); + model.AddSpace("Room", storey: upper); + model.AddOpening(wall, "Void"); + + var products = model.AllElements.Concat(model.AllSpaces).Concat(model.AllOpenings).ToList(); + Assert.Equal(5, products.Count); + Assert.Equal(products.Count, products.Select(element => element.Id).Distinct().Count()); + + var file = StepReader.Read(new StringReader(model.ToStepString())); + var guids = file.Entities.Values.Where(entity => entity.Type is "IFCWALL" or "IFCBEAM" or "IFCCOLUMN" or "IFCSPACE" or "IFCOPENINGELEMENT") + .Select(entity => entity.GetString(0)).ToList(); + Assert.Equal(products.Count, guids.Count); + Assert.Equal(products.Count, guids.Distinct(StringComparer.Ordinal).Count()); + } + + [Fact] + public void Open_ReservesImportedProductIdsWhenAddingToExistingAndNewStoreys() + { + const string source = """ + HEADER; FILE_SCHEMA(('IFC4')); ENDSEC; + DATA; + #2=IFCWALL('01vctVUKr0kugbFTf53O9L',$,'Imported wall',$,$,$,$,$,.STANDARD.); + ENDSEC; + """; + var reopened = IfcModel.Open(new StringReader(source)); + var original = Assert.Single(reopened.AllElements); + + reopened.Storeys[0].AddSlab("Added slab"); + IfcApi.Root.CreateBeam(reopened.AddStorey("Roof"), "Added beam"); + reopened.AddElement(new IfcElement { Id = 4, Name = "Manually assigned" }); + reopened.Storeys[0].AddColumn("Added column"); + + Assert.Equal(5, reopened.AllElements.Select(element => element.Id).Distinct().Count()); + Assert.Contains(reopened.AllElements, element => ReferenceEquals(original, element)); + } + + [Fact] + public void Save_ReusedUserIdsDoNotGenerateDuplicateGlobalIds() + { + var model = IfcModel.Create("Manual IDs", IfcSchema.Ifc4); + var lower = model.AddStorey("Lower"); + var upper = model.AddStorey("Upper"); + string assigned = IfcGuid.FromElementId(7); + model.AddElement(new IfcElement { Id = 7, Name = "Lower wall", IfcType = "IFCWALL" }, lower); + model.AddElement(new IfcElement { Id = 7, Name = "Upper wall", IfcType = "IFCWALL" }, upper); + model.AddElement(new IfcElement { Id = 8, Name = "Explicit wall", IfcType = "IFCWALL", GlobalId = assigned }, upper); + + Dictionary WallsByName() => StepReader.Read(new StringReader(model.ToStepString())).OfType("IFCWALL") + .ToDictionary(e => e.GetString(2)!, e => e.GetString(0), StringComparer.Ordinal); + var first = WallsByName(); + Assert.Equal(3, first.Values.Distinct(StringComparer.Ordinal).Count()); + Assert.Equal(assigned, first["Explicit wall"]); + + model.Storeys.Reverse(); + var reordered = WallsByName(); + foreach (var (name, guid) in first) Assert.Equal(guid, reordered[name]); + } + + [Fact] + public void Factories_ReserveDirectListEditsAndAttachPassedStoreys() + { + var model = IfcModel.Create("Public collections"); + var upper = new IfcBuildingStorey { Name = "Upper" }; + model.Storeys.Add(upper); + model.Storeys[0].Elements.Add(new IfcElement { Id = 1, Name = "Directly added" }); + + var first = model.AddMesh("First mesh", [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], [0, 1, 2], storey: upper); + var wall = upper.AddWall("Wall"); + upper.Elements[1] = new IfcElement { Id = 4, Name = "Same-position replacement" }; + var beam = upper.AddBeam("After replacement"); + + Assert.Equal(2, first.Id); + Assert.Equal(3, wall.Id); + Assert.Equal(5, beam.Id); + Assert.Equal(4, model.AllElements.Select(element => element.Id).Distinct().Count()); + } + + [Fact] + public void Save_GeneratedOccurrenceGlobalIdDoesNotCollideWithASystem() + { + var model = IfcModel.Create("System"); + var wall = model.Storeys[0].AddWall("Wall"); + var system = model.AddSystem("System"); + system.GlobalId = IfcGuid.FromElementId(wall.Id); + + var step = StepReader.Read(new StringReader(model.ToStepString())); + Assert.Equal(system.GlobalId, Assert.Single(step.OfType("IFCSYSTEM")).GetString(0)); + Assert.NotEqual(system.GlobalId, Assert.Single(step.OfType("IFCWALL")).GetString(0)); + } + + [Fact] + public void ExtractAndMerge_KeepTheNewStoreysAttachedToTheModelAllocator() + { + var first = IfcModel.Create("First"); + first.AddStorey("Lower").AddWall("Wall"); + var second = IfcModel.Create("Second"); + second.AddStorey("Upper", 3000).AddSlab("Slab"); + + var merged = IfcModel.Merge([first, second]); + var extracted = merged.Extract(_ => true); + foreach (var model in new[] { merged, extracted }) + { + IfcApi.Spatial.AssignContainer(model.Storeys[0], new IfcElement { Id = 3, Name = "Custom element" }); + IfcApi.Root.CreateBeam(model.Storeys[1], "Later beam"); + Assert.Equal(4, model.AllElements.Select(element => element.Id).Distinct().Count()); + } + } + [Fact] public void IfcGuid_RoundTrip_ParsesCorrectly() {