From 64eae97744498b90af06c1d8e51d184a86985325 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:11:51 +0300 Subject: [PATCH] Index STEP import entities and read typed arguments without copies --- CHANGELOG.md | 1 + docs/public-api.md | 5 + src/IfcIO/Core/StepReader.cs | 234 +++++++++++------- src/IfcIO/IfcModel.SurfaceStyles.cs | 8 +- src/IfcIO/IfcModel.cs | 78 +++--- tests/IfcIO.Tests/StepReaderTests.cs | 74 ++++++ tools/StepImportBenchmark/Program.cs | 96 +++++++ tools/StepImportBenchmark/README.md | 17 ++ .../StepImportBenchmark.csproj | 10 + 9 files changed, 395 insertions(+), 128 deletions(-) create mode 100644 tools/StepImportBenchmark/Program.cs create mode 100644 tools/StepImportBenchmark/README.md create mode 100644 tools/StepImportBenchmark/StepImportBenchmark.csproj diff --git a/CHANGELOG.md b/CHANGELOG.md index ee929f3..99f3b5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to the `IfcIO` library are documented in this file. ## [Unreleased] ### Fixed +- STEP import indexes entities by type once, reuses repeated type names, and reads typed arguments from lazy slices. - 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. diff --git a/docs/public-api.md b/docs/public-api.md index fe58c4f..0352841 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -58,6 +58,11 @@ bounds remain separate regions. Invalid contours or faces that exceed the triang | `IfcGlbExporter` | Binary glTF 2.0 exporter generating specification-compliant `.glb` files with PBR materials. | | `IfcObjExporter` | Wavefront OBJ geometry exporter with MTL material library generation. | +Model import builds a case-insensitive index for its type queries. Public `StepFile.OfType` follows the mutable +`StepFile.Entities` dictionary, including edits during enumeration. Typed `StepEntity` accessors parse slices +lazily; `Arguments` materializes the full string list on demand. Model import does not retain the temporary +`StepFile` or stream model objects incrementally. + ## Coordination & Validation | Type | Description | diff --git a/src/IfcIO/Core/StepReader.cs b/src/IfcIO/Core/StepReader.cs index 4b12f7d..39a05b1 100644 --- a/src/IfcIO/Core/StepReader.cs +++ b/src/IfcIO/Core/StepReader.cs @@ -13,83 +13,79 @@ public sealed class StepEntity public required string RawArgs { get; init; } private List? _arguments; + private List? _argumentRanges; /// Parsed top-level arguments of the entity, respecting nested parentheses and quoted strings. - public IReadOnlyList Arguments => _arguments ??= ParseArguments(RawArgs); - - public string? GetString(int index) + public IReadOnlyList Arguments { - if (index < 0 || index >= Arguments.Count) return null; - return DecodeString(Arguments[index]); + get + { + _arguments ??= ParseArguments(RawArgs); + _argumentRanges = null; + return _arguments; + } } - internal static string? DecodeString(string arg) + private bool TryGetArgument(int index, out ReadOnlySpan arg) { - if (arg == "$" || arg == "*") return null; - if (arg.StartsWith('\'') && arg.EndsWith('\'') && arg.Length >= 2) + arg = default; + if (index < 0) return false; + if (_arguments is { } materialized) { - return StepWriter.Unescape(arg[1..^1]); + if (index >= materialized.Count) return false; + arg = materialized[index]; + return true; } - return StepWriter.Unescape(arg); - } - public int? GetRef(int index) - { - if (index < 0 || index >= Arguments.Count) return null; - string arg = Arguments[index]; - if (arg.StartsWith('#') && int.TryParse(arg.AsSpan(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int refId)) + var ranges = _argumentRanges; + if (ranges is null) { - return refId; + // Numeric and reference accessors can use slices of RawArgs without retaining a string per field. + ranges = new List(); + var scanner = new ArgumentScanner(RawArgs); + while (scanner.Next(out var range)) ranges.Add(range); + _argumentRanges = ranges; } - return null; + if (index >= ranges.Count) return false; + arg = RawArgs.AsSpan(ranges[index]); + return true; + } + + public string? GetString(int index) => TryGetArgument(index, out var arg) ? DecodeString(arg) : null; + + internal static string? DecodeString(ReadOnlySpan arg) + { + if (Omitted(arg)) return null; + if (arg.Length >= 2 && arg[0] == '\'' && arg[^1] == '\'') arg = arg[1..^1]; + return arg.IndexOfAny('\'', '\\') < 0 ? arg.ToString() : StepWriter.Unescape(arg.ToString()); } + public int? GetRef(int index) => TryGetArgument(index, out var arg) && ParseRef(arg) is int reference ? reference : null; + + private static int? ParseRef(ReadOnlySpan arg) => !arg.IsEmpty && arg[0] == '#' + && int.TryParse(arg[1..], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) ? id : null; + public List GetRefList(int index) { var result = new List(); - if (index < 0 || index >= Arguments.Count) return result; - string arg = Arguments[index]; - if (!arg.StartsWith('(') || !arg.EndsWith(')')) return result; + if (!TryGetArgument(index, out var arg) || arg.Length < 2 || arg[0] != '(' || arg[^1] != ')') return result; - string inner = arg[1..^1]; - foreach (var item in ParseArguments(inner)) - { - if (item.StartsWith('#') && int.TryParse(item.AsSpan(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int refId)) - { - result.Add(refId); - } - } + var inner = arg[1..^1]; + var scanner = new ArgumentScanner(inner); + while (scanner.Next(out var range)) + if (ParseRef(inner[range]) is int reference) result.Add(reference); return result; } - public double? GetReal(int index) - { - if (index < 0 || index >= Arguments.Count) return null; - string arg = Arguments[index]; - if (arg == "$" || arg == "*") return null; - if (double.TryParse(arg, NumberStyles.Float, CultureInfo.InvariantCulture, out double val)) - { - return val; - } - return null; - } + public double? GetReal(int index) => TryGetArgument(index, out var arg) + && double.TryParse(arg, NumberStyles.Float, CultureInfo.InvariantCulture, out double value) ? value : null; - public int? GetInt(int index) - { - if (index < 0 || index >= Arguments.Count) return null; - string arg = Arguments[index]; - if (arg == "$" || arg == "*") return null; - if (int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out int val)) - { - return val; - } - return null; - } + public int? GetInt(int index) => TryGetArgument(index, out var arg) + && int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) ? value : null; public bool? GetBool(int index) { - if (index < 0 || index >= Arguments.Count) return null; - string arg = Arguments[index]; + if (!TryGetArgument(index, out var arg)) return null; if (arg.Equals(".T.", StringComparison.OrdinalIgnoreCase)) return true; if (arg.Equals(".F.", StringComparison.OrdinalIgnoreCase)) return false; return null; @@ -97,43 +93,68 @@ public List GetRefList(int index) public string? GetRaw(int index) { - if (index < 0 || index >= Arguments.Count) return null; - string arg = Arguments[index]; - return (arg == "$" || arg == "*") ? null : arg; + if (_arguments is { } materialized) + { + if (index < 0 || index >= materialized.Count) return null; + string value = materialized[index]; + return Omitted(value) ? null : value; + } + if (!TryGetArgument(index, out var arg) || Omitted(arg)) return null; + return arg.Length == RawArgs.Length ? RawArgs : arg.ToString(); } + private static bool Omitted(ReadOnlySpan arg) => arg.Length == 1 && arg[0] is '$' or '*'; + public static List ParseArguments(string args) { var result = new List(); - if (string.IsNullOrWhiteSpace(args)) return result; + var scanner = new ArgumentScanner(args); + while (scanner.Next(out var range)) result.Add(args[range]); + return result; + } - int depth = 0; - var text = new StepStringState(); - int start = 0; + private ref struct ArgumentScanner + { + private readonly ReadOnlySpan _text; + private int _next; + + internal ArgumentScanner(ReadOnlySpan text) + { + _text = text; + _next = text.IsWhiteSpace() ? text.Length : 0; + } - for (int i = 0; i < args.Length; i++) + internal bool Next(out Range range) { - char c = args[i]; - if (text.InString || c == '\'') - text.Read(c); - else + if (_next >= _text.Length) { - if (c == '(') depth++; - else if (c == ')') depth--; - else if (c == ',' && depth == 0) + range = default; + return false; + } + + int depth = 0; + var state = new StepStringState(); + int end = _next; + for (; end < _text.Length; end++) + { + char c = _text[end]; + if (state.InString || c == '\'') + state.Read(c); + else { - result.Add(args[start..i].Trim()); - start = i + 1; + if (c == '(') depth++; + else if (c == ')') depth--; + else if (c == ',' && depth == 0) break; } } - } - if (start < args.Length) - { - result.Add(args[start..].Trim()); + int start = _next; + _next = end < _text.Length ? end + 1 : end; + while (start < end && char.IsWhiteSpace(_text[start])) start++; + while (end > start && char.IsWhiteSpace(_text[end - 1])) end--; + range = start..end; + return true; } - - return result; } } @@ -158,12 +179,33 @@ public sealed class StepFile public IReadOnlyList SchemaIdentifiers { get; internal set; } = []; internal bool HasSchemaDeclaration { get; set; } - public Dictionary Entities { get; } = new(4096); + private readonly Dictionary _entities = new(4096); + private Dictionary>? _typeIndex; + + /// The editable entity dictionary. + public Dictionary Entities => _entities; + + internal Dictionary.ValueCollection EntityValues => _entities.Values; + internal int EntityCount => _entities.Count; + + internal void SetEntity(StepEntity entity) => _entities[entity.Id] = entity; + + internal void IndexTypes() + { + var index = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (var entity in _entities.Values) + { + if (!index.TryGetValue(entity.Type, out var bucket)) + index.Add(entity.Type, bucket = []); + bucket.Add(entity); + } + _typeIndex = index; + } /// Returns all entities matching a given IFC entity type name. public IEnumerable OfType(string entityType) { - foreach (var entity in Entities.Values) + foreach (var entity in _entities.Values) { if (entity.Type.Equals(entityType, StringComparison.OrdinalIgnoreCase)) { @@ -172,8 +214,12 @@ public IEnumerable OfType(string entityType) } } + // Only used by the model importer, which neither exposes nor edits the parsed dictionary. + internal IEnumerable IndexedOfType(string entityType) => + _typeIndex is not null && _typeIndex.TryGetValue(entityType, out var bucket) ? bucket : []; + /// Finds an entity by its #ID, or null if not found. - public StepEntity? Find(int? id) => id.HasValue && Entities.TryGetValue(id.Value, out var e) ? e : null; + public StepEntity? Find(int? id) => id.HasValue && _entities.TryGetValue(id.Value, out var e) ? e : null; } /// @@ -188,7 +234,9 @@ public static StepFile Read(string path) return Read(reader); } - public static StepFile Read(TextReader reader) + public static StepFile Read(TextReader reader) => Read(reader, indexTypes: false); + + internal static StepFile Read(TextReader reader, bool indexTypes) { var file = new StepFile(); bool inHeader = false; @@ -198,6 +246,7 @@ public static StepFile Read(TextReader reader) bool commentStar = false; bool possibleComment = false; var statement = new StringBuilder(256); + var names = new Dictionary(StringComparer.Ordinal); // Physical line breaks are not characters in STEP. Do not trim a line: // spaces can be significant when a string continues on the next line. while (reader.ReadLine() is { } line) @@ -245,7 +294,7 @@ public static StepFile Read(TextReader reader) else if (inHeader) ParseHeaderStatement(text, file); else if (inData) - ParseDataStatement(text, file); + ParseDataStatement(text, file, names); continue; } if (statement.Length == 0 && char.IsWhiteSpace(c)) continue; @@ -261,6 +310,7 @@ public static StepFile Read(TextReader reader) if (statement.Length != 0 || possibleComment || inHeader || inData) throw new InvalidDataException("Incomplete STEP statement or section."); + if (indexTypes) file.IndexTypes(); return file; } @@ -324,7 +374,7 @@ IEnumerable Strings(int index) } } - private static void ParseDataStatement(string statement, StepFile file) + private static void ParseDataStatement(string statement, StepFile file, Dictionary names) { if (!statement.StartsWith('#')) return; @@ -342,15 +392,29 @@ private static void ParseDataStatement(string statement, StepFile file) int closeParen = statement.LastIndexOf(')'); if (closeParen <= openParen) return; - string type = statement[(eqIdx + 1)..openParen].Trim(); + string type = InternTypeName(statement.AsSpan(eqIdx + 1, openParen - eqIdx - 1).Trim(), names); string rawArgs = statement[(openParen + 1)..closeParen]; - file.Entities[id] = new StepEntity + file.SetEntity(new StepEntity { Id = id, Type = type, RawArgs = rawArgs, - }; + }); + } + + private static string InternTypeName(ReadOnlySpan name, Dictionary names) + { +#if NET9_0_OR_GREATER + if (names.GetAlternateLookup>().TryGetValue(name, out string? existing)) + return existing; + string value = name.ToString(); +#else + string value = name.ToString(); + if (names.TryGetValue(value, out string? existing)) return existing; +#endif + names.Add(value, value); + return value; } } diff --git a/src/IfcIO/IfcModel.SurfaceStyles.cs b/src/IfcIO/IfcModel.SurfaceStyles.cs index ed5e08b..93169ca 100644 --- a/src/IfcIO/IfcModel.SurfaceStyles.cs +++ b/src/IfcIO/IfcModel.SurfaceStyles.cs @@ -9,7 +9,7 @@ private static (Dictionary Geometry, Dictionary(); - foreach (var style in step.OfType("IFCSURFACESTYLE")) + foreach (var style in step.IndexedOfType("IFCSURFACESTYLE")) { foreach (int appearanceId in style.GetRefList(2)) { @@ -36,7 +36,7 @@ private static (Dictionary Geometry, Dictionary(); - foreach (var assignment in step.OfType("IFCPRESENTATIONSTYLEASSIGNMENT")) + foreach (var assignment in step.IndexedOfType("IFCPRESENTATIONSTYLEASSIGNMENT")) { foreach (int styleId in assignment.GetRefList(0)) { @@ -48,7 +48,7 @@ private static (Dictionary Geometry, Dictionary(); var byGeometry = new Dictionary(); - foreach (var item in step.OfType("IFCSTYLEDITEM")) + foreach (var item in step.IndexedOfType("IFCSTYLEDITEM")) { foreach (int styleId in item.GetRefList(1)) { @@ -62,7 +62,7 @@ private static (Dictionary Geometry, Dictionary(); - foreach (var definition in step.OfType("IFCMATERIALDEFINITIONREPRESENTATION")) + foreach (var definition in step.IndexedOfType("IFCMATERIALDEFINITIONREPRESENTATION")) { if (definition.GetRef(3) is not int materialId || byMaterial.ContainsKey(materialId)) continue; foreach (int representationId in definition.GetRefList(2)) diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index 421195c..6bbc02f 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -1579,7 +1579,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions { ArgumentNullException.ThrowIfNull(reader); - var step = StepReader.Read(reader); + var step = StepReader.Read(reader, indexTypes: true); var schema = ReadSchema(step); var model = new IfcModel @@ -1591,12 +1591,12 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions model.Storeys.Clear(); // Clear default storey // 1. Parse Project, Building - var projectEntity = step.OfType("IFCPROJECT").FirstOrDefault(); + var projectEntity = step.IndexedOfType("IFCPROJECT").FirstOrDefault(); if (projectEntity is not null) { model.ProjectName = projectEntity.GetString(2) ?? model.ProjectName; } - var buildingEntity = step.OfType("IFCBUILDING").FirstOrDefault(); + var buildingEntity = step.IndexedOfType("IFCBUILDING").FirstOrDefault(); if (buildingEntity is not null) { model.BuildingName = buildingEntity.GetString(2) ?? model.BuildingName; @@ -1604,7 +1604,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions // 1b. Units: geometry is kept in model length units. A unit without an IfcLengthUnit // counterpart (e.g. centimetres) is converted to metres while reading. - var assignment = step.Find(projectEntity?.GetRef(8)) ?? step.OfType("IFCUNITASSIGNMENT").FirstOrDefault(); + var assignment = step.Find(projectEntity?.GetRef(8)) ?? step.IndexedOfType("IFCUNITASSIGNMENT").FirstOrDefault(); double? fileMetresPerUnit = ParseProjectUnitFactor(step, assignment, ".LENGTHUNIT."); double geometryScale = 1.0; if (fileMetresPerUnit.HasValue) @@ -1622,7 +1622,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions // 2. Parse Storeys var storeyMap = new Dictionary(); - foreach (var sEnt in step.OfType("IFCBUILDINGSTOREY")) + foreach (var sEnt in step.IndexedOfType("IFCBUILDINGSTOREY")) { var storey = new IfcBuildingStorey { @@ -1645,7 +1645,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions // 4. Map Elements to Storeys var elementToStoreyMap = new Dictionary(); - foreach (var relSpatial in step.OfType("IFCRELCONTAINEDINSPATIALSTRUCTURE")) + foreach (var relSpatial in step.IndexedOfType("IFCRELCONTAINEDINSPATIALSTRUCTURE")) { int? structId = relSpatial.GetRef(5); if (structId.HasValue && storeyMap.TryGetValue(structId.Value, out var targetStorey)) @@ -1660,7 +1660,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions // 5. Parse Property Sets and Quantity Sets var psetMap = new Dictionary(); - foreach (var psetEnt in step.OfType("IFCPROPERTYSET")) + foreach (var psetEnt in step.IndexedOfType("IFCPROPERTYSET")) { string psetName = psetEnt.GetString(2) ?? "PropertySet"; var pset = new IfcPropertySet(psetName); @@ -1681,7 +1681,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions } var qsetMap = new Dictionary(); - foreach (var qsetEnt in step.OfType("IFCELEMENTQUANTITY")) + foreach (var qsetEnt in step.IndexedOfType("IFCELEMENTQUANTITY")) { string qsetName = qsetEnt.GetString(2) ?? "BaseQuantities"; string? desc = qsetEnt.GetString(3); @@ -1729,7 +1729,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions var elementPropertySets = new Dictionary>(); var elementQuantitySets = new Dictionary>(); - foreach (var relProps in step.OfType("IFCRELDEFINESBYPROPERTIES")) + foreach (var relProps in step.IndexedOfType("IFCRELDEFINESBYPROPERTIES")) { int? propDefId = relProps.GetRef(5); if (!propDefId.HasValue) continue; @@ -1773,7 +1773,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions var defaultStorey = model.Storeys[0]; var allElementsMap = new Dictionary(); - foreach (var entity in step.Entities.Values) + foreach (var entity in step.EntityValues) { if (!IsBimProductType(entity.Type)) continue; @@ -1897,7 +1897,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions } // 7. Parse Voids (IFCRELVOIDSELEMENT) and Fillings (IFCRELFILLSELEMENT) - foreach (var relVoids in step.OfType("IFCRELVOIDSELEMENT")) + foreach (var relVoids in step.IndexedOfType("IFCRELVOIDSELEMENT")) { int? hostId = relVoids.GetRef(4); int? openId = relVoids.GetRef(5); @@ -1913,7 +1913,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions } } - foreach (var relFills in step.OfType("IFCRELFILLSELEMENT")) + foreach (var relFills in step.IndexedOfType("IFCRELFILLSELEMENT")) { int? openId = relFills.GetRef(4); int? fillId = relFills.GetRef(5); @@ -1927,7 +1927,7 @@ openElem is IfcOpeningElement opening && } // 8. Parse Space Boundaries (IFCRELSPACEBOUNDARY) - foreach (var relBound in step.OfType("IFCRELSPACEBOUNDARY")) + foreach (var relBound in step.IndexedOfType("IFCRELSPACEBOUNDARY")) { int? spaceId = relBound.GetRef(4); int? relElemId = relBound.GetRef(5); @@ -1959,7 +1959,7 @@ openElem is IfcOpeningElement opening && // 9. Parse Systems & Groups (IFCSYSTEM, IFCDISTRIBUTIONSYSTEM, IFCGROUP, IFCRELASSIGNSTOGROUP) var groupMap = new Dictionary(); - foreach (var sysEnt in step.OfType("IFCSYSTEM").Concat(step.OfType("IFCDISTRIBUTIONSYSTEM"))) + foreach (var sysEnt in step.IndexedOfType("IFCSYSTEM").Concat(step.IndexedOfType("IFCDISTRIBUTIONSYSTEM"))) { string sysGuid = sysEnt.GetString(0) ?? IfcGuid.NewGuid(); string sysName = sysEnt.GetString(2) ?? "System"; @@ -1977,7 +1977,7 @@ openElem is IfcOpeningElement opening && groupMap[sysEnt.Id] = sys; } - foreach (var grpEnt in step.OfType("IFCGROUP")) + foreach (var grpEnt in step.IndexedOfType("IFCGROUP")) { if (groupMap.ContainsKey(grpEnt.Id)) continue; @@ -1995,7 +1995,7 @@ openElem is IfcOpeningElement opening && groupMap[grpEnt.Id] = grp; } - foreach (var zoneEnt in step.OfType("IFCZONE")) + foreach (var zoneEnt in step.IndexedOfType("IFCZONE")) { string zoneGuid = zoneEnt.GetString(0) ?? IfcGuid.NewGuid(); string zName = zoneEnt.GetString(2) ?? "Zone"; @@ -2011,7 +2011,7 @@ openElem is IfcOpeningElement opening && groupMap[zoneEnt.Id] = zone; } - foreach (var relGroup in step.OfType("IFCRELASSIGNSTOGROUP")) + foreach (var relGroup in step.IndexedOfType("IFCRELASSIGNSTOGROUP")) { int? groupId = relGroup.GetRef(6); if (groupId.HasValue && groupMap.TryGetValue(groupId.Value, out var targetGroup)) @@ -2036,7 +2036,7 @@ openElem is IfcOpeningElement opening && // 9b. Parse 4D Construction Work Schedules (IFCWORKSCHEDULE, IFCTASK, IFCTASKTIME, IFCSCHEDULETIMECONTROL, IFCRELASSIGNSTOPROCESS, IFCRELSEQUENCE) var taskMap = new Dictionary(); - foreach (var tEnt in step.OfType("IFCTASK")) + foreach (var tEnt in step.IndexedOfType("IFCTASK")) { string tGuid = tEnt.GetString(0) ?? IfcGuid.NewGuid(); string tName = tEnt.GetString(2) ?? "Task"; @@ -2075,7 +2075,7 @@ openElem is IfcOpeningElement opening && taskMap[tEnt.Id] = task; } - foreach (var wsEnt in step.OfType("IFCWORKSCHEDULE")) + foreach (var wsEnt in step.IndexedOfType("IFCWORKSCHEDULE")) { string wsGuid = wsEnt.GetString(0) ?? IfcGuid.NewGuid(); string wsName = wsEnt.GetString(2) ?? "Schedule"; @@ -2093,7 +2093,7 @@ openElem is IfcOpeningElement opening && } // Connect tasks to elements via IFCRELASSIGNSTOPROCESS - foreach (var relProc in step.OfType("IFCRELASSIGNSTOPROCESS")) + foreach (var relProc in step.IndexedOfType("IFCRELASSIGNSTOPROCESS")) { var procRef = relProc.GetRef(6); if (procRef.HasValue && taskMap.TryGetValue(procRef.Value, out var task)) @@ -2109,7 +2109,7 @@ openElem is IfcOpeningElement opening && } // Connect sequence dependencies via IFCRELSEQUENCE - foreach (var relSeq in step.OfType("IFCRELSEQUENCE")) + foreach (var relSeq in step.IndexedOfType("IFCRELSEQUENCE")) { var relProcRef = relSeq.GetRef(4); var relSuccRef = relSeq.GetRef(5); @@ -2128,7 +2128,7 @@ openElem is IfcOpeningElement opening && // 9c. Parse 5D Cost Schedules & Cost Items (IFCCOSTSCHEDULE, IFCCOSTITEM, IFCAPPLIEDVALUE, IFCRELASSIGNSTOCONTROL, IFCRELNESTING) var costItemMap = new Dictionary(); - foreach (var ciEnt in step.OfType("IFCCOSTITEM")) + foreach (var ciEnt in step.IndexedOfType("IFCCOSTITEM")) { string ciGuid = ciEnt.GetString(0) ?? IfcGuid.NewGuid(); string ciName = ciEnt.GetString(2) ?? "Cost Item"; @@ -2187,7 +2187,7 @@ openElem is IfcOpeningElement opening && costItemMap[ciEnt.Id] = ci; } - foreach (var csEnt in step.OfType("IFCCOSTSCHEDULE")) + foreach (var csEnt in step.IndexedOfType("IFCCOSTSCHEDULE")) { string csGuid = csEnt.GetString(0) ?? IfcGuid.NewGuid(); string csName = csEnt.GetString(2) ?? "Cost Schedule"; @@ -2213,7 +2213,7 @@ openElem is IfcOpeningElement opening && } // Connect sub-items via IFCRELNESTING - foreach (var relNest in step.OfType("IFCRELNESTING")) + foreach (var relNest in step.IndexedOfType("IFCRELNESTING")) { int? parentRef = relNest.GetRef(4); if (parentRef.HasValue && costItemMap.TryGetValue(parentRef.Value, out var parentItem)) @@ -2229,7 +2229,7 @@ openElem is IfcOpeningElement opening && } // Connect control assignments via IFCRELASSIGNSTOCONTROL - foreach (var relCtrl in step.OfType("IFCRELASSIGNSTOCONTROL")) + foreach (var relCtrl in step.IndexedOfType("IFCRELASSIGNSTOCONTROL")) { var ctrlRef = relCtrl.GetRef(6); if (!ctrlRef.HasValue) continue; @@ -2316,7 +2316,7 @@ openElem is IfcOpeningElement opening && // 10. Parse Materials & Composite Systems (IFCMATERIAL, IFCMATERIALLAYER, IFCMATERIALLAYERSET, IFCMATERIALLAYERSETUSAGE) var materialMap = new Dictionary(); - foreach (var matEnt in step.OfType("IFCMATERIAL")) + foreach (var matEnt in step.IndexedOfType("IFCMATERIAL")) { string name = matEnt.GetString(0) ?? "Material"; var material = materialAppearances.TryGetValue(matEnt.Id, out var appearance) @@ -2327,7 +2327,7 @@ openElem is IfcOpeningElement opening && } var layerMap = new Dictionary(); - foreach (var layEnt in step.OfType("IFCMATERIALLAYER")) + foreach (var layEnt in step.IndexedOfType("IFCMATERIALLAYER")) { int? matId = layEnt.GetRef(0); IfcMaterial mat = (matId.HasValue && materialMap.TryGetValue(matId.Value, out var m)) @@ -2342,7 +2342,7 @@ openElem is IfcOpeningElement opening && } var layerSetMap = new Dictionary(); - foreach (var lsEnt in step.OfType("IFCMATERIALLAYERSET")) + foreach (var lsEnt in step.IndexedOfType("IFCMATERIALLAYERSET")) { var layIds = lsEnt.GetRefList(0); string lsName = lsEnt.GetString(1) ?? "Material Layer Set"; @@ -2354,7 +2354,7 @@ openElem is IfcOpeningElement opening && } var layerSetUsageMap = new Dictionary(); - foreach (var usageEnt in step.OfType("IFCMATERIALLAYERSETUSAGE")) + foreach (var usageEnt in step.IndexedOfType("IFCMATERIALLAYERSETUSAGE")) { int? lsId = usageEnt.GetRef(0); if (lsId.HasValue && layerSetMap.TryGetValue(lsId.Value, out var ls)) @@ -2368,7 +2368,7 @@ openElem is IfcOpeningElement opening && // 11. Parse Material Profile Sets (IFCMATERIALPROFILE, IFCMATERIALPROFILESET, IFCMATERIALPROFILESETUSAGE) var materialProfileMap = new Dictionary(); - foreach (var mpEnt in step.OfType("IFCMATERIALPROFILE")) + foreach (var mpEnt in step.IndexedOfType("IFCMATERIALPROFILE")) { string? mpName = mpEnt.GetString(0); int? matId = mpEnt.GetRef(2); @@ -2382,7 +2382,7 @@ openElem is IfcOpeningElement opening && } var profileSetMap = new Dictionary(); - foreach (var psEnt in step.OfType("IFCMATERIALPROFILESET")) + foreach (var psEnt in step.IndexedOfType("IFCMATERIALPROFILESET")) { string psName = psEnt.GetString(0) ?? "Material Profile Set"; string? psDesc = psEnt.GetString(1); @@ -2394,7 +2394,7 @@ openElem is IfcOpeningElement opening && } var profileSetUsageMap = new Dictionary(); - foreach (var usageEnt in step.OfType("IFCMATERIALPROFILESETUSAGE")) + foreach (var usageEnt in step.IndexedOfType("IFCMATERIALPROFILESETUSAGE")) { int? psId = usageEnt.GetRef(0); if (psId.HasValue && profileSetMap.TryGetValue(psId.Value, out var ps)) @@ -2405,7 +2405,7 @@ openElem is IfcOpeningElement opening && } // 12. Parse Material Associations (IFCRELASSOCIATESMATERIAL) - foreach (var relMat in step.OfType("IFCRELASSOCIATESMATERIAL")) + foreach (var relMat in step.IndexedOfType("IFCRELASSOCIATESMATERIAL")) { var elemIds = relMat.GetRefList(4); int? matRelId = relMat.GetRef(5); @@ -2441,7 +2441,7 @@ openElem is IfcOpeningElement opening && // 13. Parse MEP Distribution Ports & Network Connectivity var portMap = new Dictionary(); - foreach (var portEnt in step.OfType("IFCDISTRIBUTIONPORT")) + foreach (var portEnt in step.IndexedOfType("IFCDISTRIBUTIONPORT")) { string portGuid = portEnt.GetString(0) ?? IfcGuid.NewGuid(); string portName = portEnt.GetString(2) ?? "Port"; @@ -2474,7 +2474,7 @@ openElem is IfcOpeningElement opening && portMap[portEnt.Id] = port; } - foreach (var relPortElem in step.OfType("IFCRELCONNECTSPORTTOELEMENT")) + foreach (var relPortElem in step.IndexedOfType("IFCRELCONNECTSPORTTOELEMENT")) { int? portId = relPortElem.GetRef(4); int? elemId = relPortElem.GetRef(5); @@ -2490,7 +2490,7 @@ openElem is IfcOpeningElement opening && } } - foreach (var relPorts in step.OfType("IFCRELCONNECTSPORTS")) + foreach (var relPorts in step.IndexedOfType("IFCRELCONNECTSPORTS")) { int? portId1 = relPorts.GetRef(4); int? portId2 = relPorts.GetRef(5); @@ -2777,7 +2777,7 @@ private sealed class GeometryReadContext( /// Cap on vertices materialised while reading, linear in the file size: nested IfcMappedItems can /// otherwise multiply a small file into exponentially many vertices. /// - public long VertexBudget { get; } = MinVertexBudget + (VerticesPerEntity * (long)step.Entities.Count); + public long VertexBudget { get; } = MinVertexBudget + (VerticesPerEntity * (long)step.EntityCount); private long _materialisedVertices; @@ -2787,7 +2787,7 @@ public void ChargeVertices(int count) if (_materialisedVertices > VertexBudget) { throw new InvalidDataException( - $"IFC geometry expands to more than {VertexBudget} vertices (limit for {Step.Entities.Count} entities); check for nested IfcMappedItem amplification."); + $"IFC geometry expands to more than {VertexBudget} vertices (limit for {Step.EntityCount} entities); check for nested IfcMappedItem amplification."); } } } @@ -3072,7 +3072,7 @@ private static (IfcMesh? Mesh, IfcMaterial? Material) ParseMappedRepresentation( /// WorldCoordinateSystem of the 3D 'Model' context: absolute placements are relative to it. private static IfcTransform ParseWorldCoordinateSystem(StepFile step) { - var contexts = step.OfType("IFCGEOMETRICREPRESENTATIONCONTEXT").ToList(); + var contexts = step.IndexedOfType("IFCGEOMETRICREPRESENTATIONCONTEXT"); var model = contexts.FirstOrDefault(c => string.Equals(c.GetString(1), "Model", StringComparison.OrdinalIgnoreCase)) ?? contexts.FirstOrDefault(c => c.GetInt(2) == 3); return model is null ? IfcTransform.Identity : ParseAxis2Placement(step, model.GetRef(4)); diff --git a/tests/IfcIO.Tests/StepReaderTests.cs b/tests/IfcIO.Tests/StepReaderTests.cs index 0f5de08..693246a 100644 --- a/tests/IfcIO.Tests/StepReaderTests.cs +++ b/tests/IfcIO.Tests/StepReaderTests.cs @@ -5,6 +5,80 @@ namespace IfcIO.Tests; public class StepReaderTests { + [Fact] + public void OfType_PreservesCasingAndTheLastEntityWithADuplicateId() + { + using var text = new StringReader("DATA;#1=IFCWALL();#2=ifcwall();#3=IfcWall();#1=IFCSLAB();ENDSEC;"); + var step = StepReader.Read(text); + + Assert.Collection(step.OfType("IFCWALL"), + first => Assert.Equal("ifcwall", first.Type), + second => Assert.Equal("IfcWall", second.Type)); + Assert.Equal(1, Assert.Single(step.OfType("ifcslab")).Id); + } + + [Fact] + public void OfType_SeesReplacementAndDeletionThroughThePublicDictionary() + { + using var text = new StringReader("DATA;#1=IFCWALL();#2=IFCSLAB();ENDSEC;"); + var step = StepReader.Read(text); + Assert.Single(step.OfType("ifcwall")); + + var entities = step.Entities; + var deferredQuery = step.OfType("IFCWALL"); + entities[1] = new StepEntity { Id = 1, Type = "IFCSLAB", RawArgs = "" }; + Assert.Empty(deferredQuery); + Assert.Equal(2, step.OfType("ifcslab").Count()); + entities.Remove(1); + Assert.Equal(2, Assert.Single(step.OfType("IFCSLAB")).Id); + } + + [Fact] + public void OfType_DoesNotReturnAnEntityRemovedDuringEnumeration() + { + var step = StepReader.Read(new StringReader("DATA;#1=IFCWALL();#2=IFCWALL();ENDSEC;")); + using var enumerator = step.OfType("IFCWALL").GetEnumerator(); + Assert.True(enumerator.MoveNext()); + Assert.Equal(1, enumerator.Current.Id); + + Assert.True(step.Entities.Remove(2)); + + Assert.False(enumerator.MoveNext()); + } + + [Fact] + public void GetRaw_ReusesAFullArgumentOrAnAlreadyMaterializedString() + { + string payload = "(" + new string('0', 10_000) + ")"; + var single = new StepEntity { Id = 1, Type = "IFCA", RawArgs = payload }; + Assert.Same(payload, single.GetRaw(0)); + var multiple = new StepEntity { Id = 2, Type = "IFCA", RawArgs = payload + ",1" }; + string materialized = multiple.Arguments[0]; + Assert.Same(materialized, multiple.GetRaw(0)); + } + + [Fact] + public void TypedAccessorsAndMaterializedArgumentsAgreeOnQuotedAndNestedValues() + { + var step = StepReader.Read(new StringReader(@"DATA;#10=IFCA('a''b,(c)',(#2,(#3,#4),#5),1.25E2,.t.,$, -9);ENDSEC;")); + var entity = step.Find(10)!; + + void Check() + { + Assert.Equal("a'b,(c)", entity.GetString(0)); + Assert.Collection(entity.GetRefList(1), first => Assert.Equal(2, first), second => Assert.Equal(5, second)); + Assert.Equal(125.0, entity.GetReal(2)); + Assert.True(entity.GetBool(3)); + Assert.Null(entity.GetRaw(4)); + Assert.Equal(-9, entity.GetInt(5)); + Assert.Null(entity.GetString(6)); + } + + Check(); + Assert.Equal(6, entity.Arguments.Count); + Check(); + } + [Theory] [InlineData(@"\S\D", "\u00C4")] [InlineData(@"\PA\\S\D", "\u00C4")] diff --git a/tools/StepImportBenchmark/Program.cs b/tools/StepImportBenchmark/Program.cs new file mode 100644 index 0000000..5928506 --- /dev/null +++ b/tools/StepImportBenchmark/Program.cs @@ -0,0 +1,96 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text; +using System.Text.Json; +using IfcIO; + +if (args is not [("generate" or "open"), var path]) +{ + Console.Error.WriteLine("Usage: StepImportBenchmark "); + return 1; +} + +const int MiB = 1024 * 1024; +if (args[0] == "generate") +{ + // Generate the large fixture separately: fixture generation should not affect the import process's peak memory. + using var stream = new FileStream(path, FileMode.CreateNew); + using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\n" }; + writer.WriteLine("ISO-10303-21;"); + writer.WriteLine("HEADER;"); + writer.WriteLine("FILE_DESCRIPTION(('Synthetic import benchmark'),'2;1');"); + writer.WriteLine("FILE_NAME('benchmark.ifc','2026-01-01T00:00:00',(''),(''),'','','');"); + writer.WriteLine("FILE_SCHEMA(('IFC4'));"); + writer.WriteLine("ENDSEC;"); + writer.WriteLine("DATA;"); + writer.WriteLine("#1=IFCPROJECT('01vctVUKr0kugbFTf53O9L',$,'Benchmark',$,$,$,$,(#5),$);"); + writer.WriteLine("#2=IFCWALL('02vctVUKr0kugbFTf53O9L',$,'Wall',$,$,$,#6,$,.STANDARD.);"); + writer.WriteLine("#3=IFCCARTESIANPOINT((0.,0.,0.));"); + writer.WriteLine("#4=IFCAXIS2PLACEMENT3D(#3,$,$);"); + writer.WriteLine("#5=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#4,$);"); + writer.WriteLine("#6=IFCPRODUCTDEFINITIONSHAPE($,$,(#7));"); + writer.WriteLine("#7=IFCSHAPEREPRESENTATION(#5,'Body','SurfaceModel',(#8));"); + writer.WriteLine("#8=IFCSHELLBASEDSURFACEMODEL((#9));"); + const int grid = 100; + const int stride = grid + 1; + const int triangles = grid * grid * 2; + const int firstFace = 10; + const int firstPoint = firstFace + 3 * triangles; + writer.Write("#9=IFCOPENSHELL(("); + for (int i = 0; i < triangles; i++) + { + if (i > 0) writer.Write(','); + writer.Write(FormattableString.Invariant($"#{firstFace + 3 * i}")); + } + writer.WriteLine("));"); + for (int y = 0; y <= grid; y++) + for (int x = 0; x <= grid; x++) + writer.WriteLine(FormattableString.Invariant($"#{firstPoint + stride * y + x}=IFCCARTESIANPOINT(({x}.,{y}.,0.));")); + for (int y = 0; y < grid; y++) + { + for (int x = 0; x < grid; x++) + { + int face = firstFace + 6 * (y * grid + x); + int point = firstPoint + stride * y + x; + WriteFace(face, point, point + 1, point + stride + 1); + WriteFace(face + 3, point, point + stride + 1, point + stride); + } + } + void WriteFace(int id, int a, int b, int c) + { + writer.WriteLine(FormattableString.Invariant($"#{id}=IFCFACE((#{id + 1}));")); + writer.WriteLine(FormattableString.Invariant($"#{id + 1}=IFCFACEOUTERBOUND(#{id + 2},.T.);")); + writer.WriteLine(FormattableString.Invariant($"#{id + 2}=IFCPOLYLOOP((#{a},#{b},#{c}));")); + } + const string payload = "=IFCPROPERTYSINGLEVALUE('Synthetic attribute',$,IFCTEXT('abcdefghijklmnopqrstuvwxyz0123456789'),$);"; + long written = 0; + for (int id = firstPoint + stride * stride; written < 110L * MiB; id++) + { + string number = id.ToString(CultureInfo.InvariantCulture); + writer.Write('#'); + writer.Write(number); + writer.WriteLine(payload); + written += number.Length + payload.Length + 2; + } + writer.WriteLine("ENDSEC;"); + writer.WriteLine("END-ISO-10303-21;"); + return 0; +} + +long allocatedBefore = GC.GetTotalAllocatedBytes(precise: true); +var timer = Stopwatch.StartNew(); +var model = IfcModel.Open(path); +timer.Stop(); +long allocated = GC.GetTotalAllocatedBytes(precise: true) - allocatedBefore; +using var process = Process.GetCurrentProcess(); +Console.WriteLine(JsonSerializer.Serialize(new +{ + Runtime = Environment.Version.ToString(), + InputMiB = new FileInfo(path).Length / (double)MiB, + Elements = model.AllElements.Count(), + Triangles = model.AllElements.Sum(element => element.Mesh?.TriangleCount ?? 0), + ElapsedMs = timer.Elapsed.TotalMilliseconds, + AllocatedMiB = allocated / (double)MiB, + PeakWorkingSetMiB = process.PeakWorkingSet64 / (double)MiB, +})); +return 0; diff --git a/tools/StepImportBenchmark/README.md b/tools/StepImportBenchmark/README.md new file mode 100644 index 0000000..86dff6b --- /dev/null +++ b/tools/StepImportBenchmark/README.md @@ -0,0 +1,17 @@ +# STEP import benchmark + +Build with the repository's .NET SDK, generate the fixture outside the checkout, then run the import in a new process: + +```sh +dotnet build tools/StepImportBenchmark/StepImportBenchmark.csproj -c Release +dotnet tools/StepImportBenchmark/bin/Release/net10.0/StepImportBenchmark.dll generate /synthetic.ifc +dotnet tools/StepImportBenchmark/bin/Release/net10.0/StepImportBenchmark.dll open /synthetic.ifc +``` + +The generator writes over 110 MiB of STEP text with one wall, a reachable 20,000-triangle mesh, and many unreferenced +property records. It is a controlled exercise of STEP parsing and type scans, not a representative project. +Pass a real IFC path to `open` for measurements on your workload. + +`open` reports elapsed wall time, process-wide managed allocation and peak working set. Peak working set includes +runtime overhead. Use fresh processes and several alternating runs for before/after comparisons; file-system +cache and process state can affect both time and memory. diff --git a/tools/StepImportBenchmark/StepImportBenchmark.csproj b/tools/StepImportBenchmark/StepImportBenchmark.csproj new file mode 100644 index 0000000..b7183b8 --- /dev/null +++ b/tools/StepImportBenchmark/StepImportBenchmark.csproj @@ -0,0 +1,10 @@ + + + Exe + net10.0 + false + + + + +