From dfb5d852966649d7a55e64d48417049dbc91bd86 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:02:18 +0300 Subject: [PATCH] Import IFC product occurrences by schema and body representation Derive occurrence classes from official EXPRESS schemas. Include site terrain, inherit the container storey for aggregated parts, and retain hosts of imported openings. --- CHANGELOG.md | 2 + docs/public-api.md | 6 + docs/scene-adapter.md | 4 +- src/IfcIO/Core/StepReader.cs | 1 + src/IfcIO/IfcModel.cs | 116 ++++++++-- src/IfcIO/Schema/IfcProductOccurrences.g.cs | 225 ++++++++++++++++++++ tests/IfcIO.Tests/ProductOccurrenceTests.cs | 212 ++++++++++++++++++ tools/README-product-occurrences.md | 18 ++ tools/generate_product_occurrences.py | 97 +++++++++ 9 files changed, 660 insertions(+), 21 deletions(-) create mode 100644 src/IfcIO/Schema/IfcProductOccurrences.g.cs create mode 100644 tests/IfcIO.Tests/ProductOccurrenceTests.cs create mode 100644 tools/README-product-occurrences.md create mode 100644 tools/generate_product_occurrences.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0388366..48b16c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes to the `IfcIO` library are documented in this file. ## [Unreleased] ### Fixed +- Import reads 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 half-spaces and Boolean operations not evaluated in the mesh, and rejects cyclic or excessive trees. - Swept-solid import applies the profile, solid and object placements to inclined extrusions, revolutions and diff --git a/docs/public-api.md b/docs/public-api.md index b449c10..f4e99ed 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -21,6 +21,12 @@ Representations and ports with unsupported placements are omitted and counted in IFC output and schema migration are not supported for these models, including after extraction. Unknown, missing or multiple schema identifiers fail model import. +Import includes concrete `IfcProduct` occurrences with a `Body` shape in the declared schema, including +`IfcSite` terrain. Other spatial objects and ports still use their dedicated import paths; type definitions +are not occurrences. Aggregated parts inherit their container's storey unless directly assigned elsewhere. +The original element classes and hosts of imported openings can still be read without a body. Additional +classes retain their IFC type in memory; IFC export can fall back to `IfcBuildingElementProxy`. + `IfcModel.LengthUnit` controls the declared unit of geometry and storey elevations. IFC import keeps recognised millimetres, metres, feet and inches in the model; other supported length scales are converted to metres. `IfcModel.AngleUnit` controls the IFC plane angle unit, but `IfcRevolvedAreaSolid.Angle` is always in radians in memory. diff --git a/docs/scene-adapter.md b/docs/scene-adapter.md index ef6731f..4ea7c4d 100644 --- a/docs/scene-adapter.md +++ b/docs/scene-adapter.md @@ -81,8 +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. -- IfcIO places an element in a storey only through `IfcRelContainedInSpatialStructure`. Elements contained in the site - or building, and spaces aggregated to a storey (`IfcRelAggregates`), are in the first storey. A file without storeys +- 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. - IfcIO excludes type objects (`IfcWallType`, `IfcDoorStyle`) and door and window lining and panel properties from the occurrence list. Type property sets are not read yet; when they are, they will use the same diff --git a/src/IfcIO/Core/StepReader.cs b/src/IfcIO/Core/StepReader.cs index 39a05b1..b38ec1f 100644 --- a/src/IfcIO/Core/StepReader.cs +++ b/src/IfcIO/Core/StepReader.cs @@ -217,6 +217,7 @@ 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 : []; + internal IEnumerable IndexedTypeNames => _typeIndex is { } index ? index.Keys : []; /// 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; diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index b6b4c75..c7f6a18 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -847,8 +847,8 @@ string ProductGuid(IfcElement element, string domain) int openShapeId = WriteElementShape(w, opening, bodySubContextId, styleCache, useTessellation); 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."); + int openElemId = AddIfcProduct(w, "IFCOPENINGELEMENT", openGuid, ownerHistoryId, opening.Name, + openPlacementId, openShapeId, opening.Tag ?? opening.Id.ToString(CultureInfo.InvariantCulture)); w.Add("IFCRELVOIDSELEMENT", $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,{StepWriter.Ref(elemId)},{StepWriter.Ref(openElemId)}"); @@ -1660,6 +1660,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions } } } + InheritAggregateStoreys(step, storeyMap, elementToStoreyMap); // 5. Parse Property Sets and Quantity Sets var psetMap = new Dictionary(); @@ -1775,19 +1776,23 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions keepParametric: geometryScale == 1.0); var defaultStorey = model.Storeys[0]; var allElementsMap = new Dictionary(); + var productTypes = GetProductImportTypes(step, schema); + var voidHosts = FindVoidHosts(step, productTypes); foreach (var entity in step.EntityValues) { - if (!IsBimProductType(entity.Type)) continue; + if (!productTypes.TryGetValue(entity.Type, out var occurrence)) continue; + int? shapeDefId = entity.GetRef(6); + if (occurrence.NeedsBody && !voidHosts.Contains(entity.Id) && !HasBodyRepresentation(step, shapeDefId)) continue; string globalId = entity.GetString(0) ?? IfcGuid.NewGuid(); string name = entity.GetString(2) ?? entity.Type; - string? tag = entity.GetString(7); + string? tag = occurrence.TagIndex >= 0 ? entity.GetString(occurrence.TagIndex) : null; var targetStorey = elementToStoreyMap.TryGetValue(entity.Id, out var s) ? s : defaultStorey; - bool isOpening = entity.Type.Equals("IFCOPENINGELEMENT", StringComparison.OrdinalIgnoreCase); bool isSpace = entity.Type.Equals("IFCSPACE", StringComparison.OrdinalIgnoreCase); + bool isOpening = occurrence.IsOpening; IfcElement element; if (isOpening) @@ -1858,11 +1863,10 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions } // Parse Mesh / Solid Geometry - int? shapeDefId = entity.GetRef(6); if (shapeDefId.HasValue && ResolveObjectPlacement(geometry, entity.GetRef(5)) is { } placement) { var mesh = ParseGeometry(geometry, shapeDefId.Value, name, placement, out var mat, out var solid, out var revSolid, - out var boolResult, out bool unwritableBooleanBody); + out var boolResult, out bool unwritableBooleanBody, bodyOnly: occurrence.NeedsBody); element.HasUnwritableBooleanBody = unwritableBooleanBody; if (mesh is not null) { @@ -2612,7 +2616,7 @@ private int WriteElementShape(StepWriter w, IfcElement element, int bodySubConte $"$,$,({StepWriter.Ref(shapeRepId)})"); } - return StepWriter.Null == "$" ? w.Add("IFCPRODUCTDEFINITIONSHAPE", "$,$,()") : 0; + return 0; } private int WriteProfileDef(StepWriter w, IfcProfileDef profile) @@ -2848,7 +2852,8 @@ public void ChargeVertices(int count) out IfcExtrudedAreaSolid? solid, out IfcRevolvedAreaSolid? revolvedSolid, out IfcBooleanResult? booleanResult, - out bool unwritableBooleanBody) + out bool unwritableBooleanBody, + bool bodyOnly) { material = null; solid = null; @@ -2864,9 +2869,10 @@ public void ChargeVertices(int count) .Where(r => r.Type.Equals("IFCSHAPEREPRESENTATION", StringComparison.OrdinalIgnoreCase)) .ToList(); - // 'Body' first; other representations (Axis, Box, FootPrint...) only when no body geometry is readable. + // Legacy products can fall back to another representation; newly discovered products require Body. static bool IsBody(StepEntity rep) => string.Equals(rep.GetString(1), "Body", StringComparison.OrdinalIgnoreCase); - foreach (var rep in reps.Where(IsBody).Concat(reps.Where(r => !IsBody(r)))) + var bodies = reps.Where(IsBody); + foreach (var rep in bodyOnly ? bodies : bodies.Concat(reps.Where(r => !IsBody(r)))) { IfcMaterial? repMaterial = null; var mesh = ParseRepresentationItems(ctx, rep, meshName, ref repMaterial, out var parametric, out bool hasBoolean); @@ -3677,9 +3683,8 @@ private static string ExtractNominalValue(string? rawVal) return StepWriter.Unescape(rawVal) ?? rawVal; } - // Supported IFC2x3 and IFC4 occurrence classes. Explicit names keep type objects, - // styles, and property definitions out without excluding legitimate occurrence variants. - private static readonly HashSet BimProductTypes = new(StringComparer.OrdinalIgnoreCase) + // Preserve metadata-only imports for the original set of supported occurrences. + private static readonly HashSet ProductsImportedWithoutBody = new(StringComparer.OrdinalIgnoreCase) { "IFCWALL", "IFCWALLSTANDARDCASE", "IFCWALLELEMENTEDCASE", "IFCSLAB", "IFCSLABSTANDARDCASE", "IFCSLABELEMENTEDCASE", @@ -3695,7 +3700,77 @@ private static string ExtractNominalValue(string? rawVal) "IFCPIPESEGMENT", "IFCDUCTSEGMENT", "IFCPIPEFITTING", "IFCDUCTFITTING", }; - private static bool IsBimProductType(string type) => BimProductTypes.Contains(type); + private readonly record struct ProductImportInfo(int TagIndex, bool IsOpening, bool NeedsBody); + + private static void InheritAggregateStoreys( + StepFile step, Dictionary storeys, Dictionary assignments) + { + var children = new Dictionary>(); + foreach (var rel in step.IndexedOfType("IFCRELAGGREGATES")) + { + if (rel.GetRef(4) is not int parent) continue; + if (!children.TryGetValue(parent, out var group)) children[parent] = group = []; + group.AddRange(rel.GetRefList(5)); + } + if (children.Count == 0) return; + + var pending = new Queue(); + foreach (int id in assignments.Keys) + if (children.ContainsKey(id)) pending.Enqueue(id); + foreach (var (id, storey) in storeys) + if (children.ContainsKey(id) && assignments.TryAdd(id, storey)) pending.Enqueue(id); + + while (pending.TryDequeue(out int parent)) + { + var storey = assignments[parent]; + foreach (int child in children[parent]) + if (assignments.TryAdd(child, storey) && children.ContainsKey(child)) pending.Enqueue(child); + } + } + + private static HashSet FindVoidHosts(StepFile step, Dictionary productTypes) + { + var hosts = new HashSet(); + foreach (var relation in step.IndexedOfType("IFCRELVOIDSELEMENT")) + { + if (step.Find(relation.GetRef(4)) is { } host + && productTypes.TryGetValue(host.Type, out var hostType) && hostType.TagIndex == 7 + && step.Find(relation.GetRef(5)) is { } opening + && productTypes.TryGetValue(opening.Type, out var occurrence) && occurrence.IsOpening + && (!occurrence.NeedsBody || HasBodyRepresentation(step, opening.GetRef(6)))) + hosts.Add(host.Id); + } + return hosts; + } + + private static Dictionary GetProductImportTypes(StepFile step, IfcSchema schema) + { + var productTypes = new Dictionary(StringComparer.OrdinalIgnoreCase); + // Classify each STEP type once, then visit the entities in their original order. + foreach (string type in step.IndexedTypeNames) + { + if (ProductsImportedWithoutBody.Contains(type)) + productTypes.Add(type, new(7, type.Equals("IFCOPENINGELEMENT", StringComparison.OrdinalIgnoreCase), NeedsBody: false)); + else if (IfcProductOccurrences.TryGetInfo(schema, type, out int tagIndex, out bool subtracts)) + productTypes.Add(type, new(tagIndex, subtracts, NeedsBody: true)); + } + return productTypes; + } + + private static bool HasBodyRepresentation(StepFile step, int? shapeId) + { + if (step.Find(shapeId) is not { } shape + || !shape.Type.Equals("IFCPRODUCTDEFINITIONSHAPE", StringComparison.OrdinalIgnoreCase)) return false; + + foreach (int repId in shape.GetRefList(2)) + { + if (step.Find(repId) is { } rep + && rep.Type.Equals("IFCSHAPEREPRESENTATION", StringComparison.OrdinalIgnoreCase) + && string.Equals(rep.GetString(1), "Body", StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } private static int WriteMeshTriangulatedFaceSet(StepWriter w, IReadOnlyList vertices, int[] indices, bool closed) { @@ -3778,7 +3853,7 @@ private int GetOrCreateSurfaceStyle(StepWriter w, IfcMaterial mat, Dictionary 0 ? StepWriter.Ref(shapeId) : StepWriter.Null; + string commonArgs = $"{StepWriter.Str(guid)},{StepWriter.Ref(ownerHistoryId)},{StepWriter.Str(name)},$,$,{StepWriter.Ref(placementId)},{shapeRef},{StepWriter.Str(tag)}"; return ifcType switch { @@ -3805,8 +3881,10 @@ private static int AddIfcProduct( "IFCROOF" => w.Add("IFCROOF", $"{commonArgs},.FLAT_ROOF."), "IFCPIPESEGMENT" => w.Add("IFCPIPESEGMENT", commonArgs), "IFCDUCTSEGMENT" => w.Add("IFCDUCTSEGMENT", commonArgs), - "IFCOPENINGELEMENT" => w.Add("IFCOPENINGELEMENT", $"{commonArgs},.OPENING."), - _ => w.Add("IFCBUILDINGELEMENTPROXY", $"{commonArgs},.ELEMENT."), + "IFCOPENINGELEMENT" => w.Add("IFCOPENINGELEMENT", Schema == IfcSchema.Ifc4 ? $"{commonArgs},.OPENING." : commonArgs), + _ => w.Add("IFCBUILDINGELEMENTPROXY", Schema == IfcSchema.Ifc4 + ? $"{commonArgs},.NOTDEFINED." + : $"{commonArgs},.ELEMENT."), }; } diff --git a/src/IfcIO/Schema/IfcProductOccurrences.g.cs b/src/IfcIO/Schema/IfcProductOccurrences.g.cs new file mode 100644 index 0000000..88b9bcf --- /dev/null +++ b/src/IfcIO/Schema/IfcProductOccurrences.g.cs @@ -0,0 +1,225 @@ +// Generated by tools/generate_product_occurrences.py from buildingSMART IFC2x3 TC1, IFC4 ADD2 TC1 and IFC4.3 ADD2. +using System.Collections.Frozen; + +namespace IfcIO.Schema; + +internal static class IfcProductOccurrences +{ + private const int V2x3 = 1, V4 = 2, V4x3 = 4; + + public static bool TryGetInfo(IfcSchema schema, string type, out int tagIndex, out bool subtracts) + { + tagIndex = -1; + subtracts = false; + int version = schema switch + { + IfcSchema.Ifc2x3 => V2x3, + IfcSchema.Ifc4 => V4, + IfcSchema.Ifc4x3 => V4x3, + _ => 0, + }; + if (!Types.TryGetValue(type, out var occurrence) || (occurrence.Versions & version) == 0) return false; + tagIndex = occurrence.TagIndex; + subtracts = occurrence.Subtracts; + return true; + } + + private static readonly FrozenDictionary Types = + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["IFCACTUATOR"] = (V4 | V4x3, 7, false), + ["IFCAIRTERMINAL"] = (V4 | V4x3, 7, false), + ["IFCAIRTERMINALBOX"] = (V4 | V4x3, 7, false), + ["IFCAIRTOAIRHEATRECOVERY"] = (V4 | V4x3, 7, false), + ["IFCALARM"] = (V4 | V4x3, 7, false), + ["IFCALIGNMENT"] = (V4x3, -1, false), + ["IFCALIGNMENTCANT"] = (V4x3, -1, false), + ["IFCALIGNMENTHORIZONTAL"] = (V4x3, -1, false), + ["IFCALIGNMENTSEGMENT"] = (V4x3, -1, false), + ["IFCALIGNMENTVERTICAL"] = (V4x3, -1, false), + ["IFCANNOTATION"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCAUDIOVISUALAPPLIANCE"] = (V4 | V4x3, 7, false), + ["IFCBEAM"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCBEAMSTANDARDCASE"] = (V4, 7, false), + ["IFCBEARING"] = (V4x3, 7, false), + ["IFCBOILER"] = (V4 | V4x3, 7, false), + ["IFCBOREHOLE"] = (V4x3, 7, false), + ["IFCBUILDINGELEMENTPART"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCBUILDINGELEMENTPROXY"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCBUILTELEMENT"] = (V4x3, 7, false), + ["IFCBURNER"] = (V4 | V4x3, 7, false), + ["IFCCABLECARRIERFITTING"] = (V4 | V4x3, 7, false), + ["IFCCABLECARRIERSEGMENT"] = (V4 | V4x3, 7, false), + ["IFCCABLEFITTING"] = (V4 | V4x3, 7, false), + ["IFCCABLESEGMENT"] = (V4 | V4x3, 7, false), + ["IFCCAISSONFOUNDATION"] = (V4x3, 7, false), + ["IFCCHAMFEREDGEFEATURE"] = (V2x3, 7, true), + ["IFCCHILLER"] = (V4 | V4x3, 7, false), + ["IFCCHIMNEY"] = (V4 | V4x3, 7, false), + ["IFCCIVILELEMENT"] = (V4 | V4x3, 7, false), + ["IFCCOIL"] = (V4 | V4x3, 7, false), + ["IFCCOLUMN"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCCOLUMNSTANDARDCASE"] = (V4, 7, false), + ["IFCCOMMUNICATIONSAPPLIANCE"] = (V4 | V4x3, 7, false), + ["IFCCOMPRESSOR"] = (V4 | V4x3, 7, false), + ["IFCCONDENSER"] = (V4 | V4x3, 7, false), + ["IFCCONTROLLER"] = (V4 | V4x3, 7, false), + ["IFCCONVEYORSEGMENT"] = (V4x3, 7, false), + ["IFCCOOLEDBEAM"] = (V4 | V4x3, 7, false), + ["IFCCOOLINGTOWER"] = (V4 | V4x3, 7, false), + ["IFCCOURSE"] = (V4x3, 7, false), + ["IFCCOVERING"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCCURTAINWALL"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCDAMPER"] = (V4 | V4x3, 7, false), + ["IFCDEEPFOUNDATION"] = (V4x3, 7, false), + ["IFCDISCRETEACCESSORY"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCDISTRIBUTIONBOARD"] = (V4x3, 7, false), + ["IFCDISTRIBUTIONCHAMBERELEMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCDISTRIBUTIONCONTROLELEMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCDISTRIBUTIONELEMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCDISTRIBUTIONFLOWELEMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCDOOR"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCDOORSTANDARDCASE"] = (V4, 7, false), + ["IFCDUCTFITTING"] = (V4 | V4x3, 7, false), + ["IFCDUCTSEGMENT"] = (V4 | V4x3, 7, false), + ["IFCDUCTSILENCER"] = (V4 | V4x3, 7, false), + ["IFCEARTHWORKSCUT"] = (V4x3, 7, true), + ["IFCEARTHWORKSELEMENT"] = (V4x3, 7, false), + ["IFCEARTHWORKSFILL"] = (V4x3, 7, false), + ["IFCELECTRICALELEMENT"] = (V2x3, 7, false), + ["IFCELECTRICAPPLIANCE"] = (V4 | V4x3, 7, false), + ["IFCELECTRICDISTRIBUTIONBOARD"] = (V4 | V4x3, 7, false), + ["IFCELECTRICDISTRIBUTIONPOINT"] = (V2x3, 7, false), + ["IFCELECTRICFLOWSTORAGEDEVICE"] = (V4 | V4x3, 7, false), + ["IFCELECTRICFLOWTREATMENTDEVICE"] = (V4x3, 7, false), + ["IFCELECTRICGENERATOR"] = (V4 | V4x3, 7, false), + ["IFCELECTRICMOTOR"] = (V4 | V4x3, 7, false), + ["IFCELECTRICTIMECONTROL"] = (V4 | V4x3, 7, false), + ["IFCELEMENTASSEMBLY"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCENERGYCONVERSIONDEVICE"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCENGINE"] = (V4 | V4x3, 7, false), + ["IFCEQUIPMENTELEMENT"] = (V2x3, 7, false), + ["IFCEVAPORATIVECOOLER"] = (V4 | V4x3, 7, false), + ["IFCEVAPORATOR"] = (V4 | V4x3, 7, false), + ["IFCFAN"] = (V4 | V4x3, 7, false), + ["IFCFASTENER"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFILTER"] = (V4 | V4x3, 7, false), + ["IFCFIRESUPPRESSIONTERMINAL"] = (V4 | V4x3, 7, false), + ["IFCFLOWCONTROLLER"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFLOWFITTING"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFLOWINSTRUMENT"] = (V4 | V4x3, 7, false), + ["IFCFLOWMETER"] = (V4 | V4x3, 7, false), + ["IFCFLOWMOVINGDEVICE"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFLOWSEGMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFLOWSTORAGEDEVICE"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFLOWTERMINAL"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFLOWTREATMENTDEVICE"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFOOTING"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFURNISHINGELEMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCFURNITURE"] = (V4 | V4x3, 7, false), + ["IFCGEOGRAPHICELEMENT"] = (V4 | V4x3, 7, false), + ["IFCGEOMODEL"] = (V4x3, 7, false), + ["IFCGEOSLICE"] = (V4x3, 7, false), + ["IFCGEOTECHNICALSTRATUM"] = (V4x3, 7, false), + ["IFCGRID"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCHEATEXCHANGER"] = (V4 | V4x3, 7, false), + ["IFCHUMIDIFIER"] = (V4 | V4x3, 7, false), + ["IFCIMPACTPROTECTIONDEVICE"] = (V4x3, 7, false), + ["IFCINTERCEPTOR"] = (V4 | V4x3, 7, false), + ["IFCJUNCTIONBOX"] = (V4 | V4x3, 7, false), + ["IFCKERB"] = (V4x3, 7, false), + ["IFCLAMP"] = (V4 | V4x3, 7, false), + ["IFCLIGHTFIXTURE"] = (V4 | V4x3, 7, false), + ["IFCLINEARELEMENT"] = (V4x3, -1, false), + ["IFCLINEARPOSITIONINGELEMENT"] = (V4x3, -1, false), + ["IFCLIQUIDTERMINAL"] = (V4x3, 7, false), + ["IFCMECHANICALFASTENER"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCMEDICALDEVICE"] = (V4 | V4x3, 7, false), + ["IFCMEMBER"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCMEMBERSTANDARDCASE"] = (V4, 7, false), + ["IFCMOBILETELECOMMUNICATIONSAPPLIANCE"] = (V4x3, 7, false), + ["IFCMOORINGDEVICE"] = (V4x3, 7, false), + ["IFCMOTORCONNECTION"] = (V4 | V4x3, 7, false), + ["IFCNAVIGATIONELEMENT"] = (V4x3, 7, false), + ["IFCOPENINGELEMENT"] = (V2x3 | V4 | V4x3, 7, true), + ["IFCOPENINGSTANDARDCASE"] = (V4, 7, true), + ["IFCOUTLET"] = (V4 | V4x3, 7, false), + ["IFCPAVEMENT"] = (V4x3, 7, false), + ["IFCPILE"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCPIPEFITTING"] = (V4 | V4x3, 7, false), + ["IFCPIPESEGMENT"] = (V4 | V4x3, 7, false), + ["IFCPLATE"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCPLATESTANDARDCASE"] = (V4, 7, false), + ["IFCPROJECTIONELEMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCPROTECTIVEDEVICE"] = (V4 | V4x3, 7, false), + ["IFCPROTECTIVEDEVICETRIPPINGUNIT"] = (V4 | V4x3, 7, false), + ["IFCPROXY"] = (V2x3 | V4, 8, false), + ["IFCPUMP"] = (V4 | V4x3, 7, false), + ["IFCRAIL"] = (V4x3, 7, false), + ["IFCRAILING"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCRAMP"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCRAMPFLIGHT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCREFERENT"] = (V4x3, -1, false), + ["IFCREINFORCEDSOIL"] = (V4x3, 7, false), + ["IFCREINFORCINGBAR"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCREINFORCINGMESH"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCROOF"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCROUNDEDEDGEFEATURE"] = (V2x3, 7, true), + ["IFCSANITARYTERMINAL"] = (V4 | V4x3, 7, false), + ["IFCSENSOR"] = (V4 | V4x3, 7, false), + ["IFCSHADINGDEVICE"] = (V4 | V4x3, 7, false), + ["IFCSIGN"] = (V4x3, 7, false), + ["IFCSIGNAL"] = (V4x3, 7, false), + ["IFCSITE"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSLAB"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCSLABELEMENTEDCASE"] = (V4, 7, false), + ["IFCSLABSTANDARDCASE"] = (V4, 7, false), + ["IFCSOLARDEVICE"] = (V4 | V4x3, 7, false), + ["IFCSPACEHEATER"] = (V4 | V4x3, 7, false), + ["IFCSTACKTERMINAL"] = (V4 | V4x3, 7, false), + ["IFCSTAIR"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCSTAIRFLIGHT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCSTRUCTURALCURVEACTION"] = (V4 | V4x3, -1, false), + ["IFCSTRUCTURALCURVECONNECTION"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALCURVEMEMBER"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALCURVEMEMBERVARYING"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALCURVEREACTION"] = (V4 | V4x3, -1, false), + ["IFCSTRUCTURALLINEARACTION"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALLINEARACTIONVARYING"] = (V2x3, -1, false), + ["IFCSTRUCTURALPLANARACTION"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALPLANARACTIONVARYING"] = (V2x3, -1, false), + ["IFCSTRUCTURALPOINTACTION"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALPOINTCONNECTION"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALPOINTREACTION"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALSURFACEACTION"] = (V4 | V4x3, -1, false), + ["IFCSTRUCTURALSURFACECONNECTION"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALSURFACEMEMBER"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALSURFACEMEMBERVARYING"] = (V2x3 | V4 | V4x3, -1, false), + ["IFCSTRUCTURALSURFACEREACTION"] = (V4 | V4x3, -1, false), + ["IFCSURFACEFEATURE"] = (V4 | V4x3, 7, false), + ["IFCSWITCHINGDEVICE"] = (V4 | V4x3, 7, false), + ["IFCSYSTEMFURNITUREELEMENT"] = (V4 | V4x3, 7, false), + ["IFCTANK"] = (V4 | V4x3, 7, false), + ["IFCTENDON"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCTENDONANCHOR"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCTENDONCONDUIT"] = (V4x3, 7, false), + ["IFCTRACKELEMENT"] = (V4x3, 7, false), + ["IFCTRANSFORMER"] = (V4 | V4x3, 7, false), + ["IFCTRANSPORTELEMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCTUBEBUNDLE"] = (V4 | V4x3, 7, false), + ["IFCUNITARYCONTROLELEMENT"] = (V4 | V4x3, 7, false), + ["IFCUNITARYEQUIPMENT"] = (V4 | V4x3, 7, false), + ["IFCVALVE"] = (V4 | V4x3, 7, false), + ["IFCVEHICLE"] = (V4x3, 7, false), + ["IFCVIBRATIONDAMPER"] = (V4x3, 7, false), + ["IFCVIBRATIONISOLATOR"] = (V4 | V4x3, 7, false), + ["IFCVIRTUALELEMENT"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCVOIDINGFEATURE"] = (V4 | V4x3, 7, true), + ["IFCWALL"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCWALLELEMENTEDCASE"] = (V4, 7, false), + ["IFCWALLSTANDARDCASE"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCWASTETERMINAL"] = (V4 | V4x3, 7, false), + ["IFCWINDOW"] = (V2x3 | V4 | V4x3, 7, false), + ["IFCWINDOWSTANDARDCASE"] = (V4, 7, false), + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); +} diff --git a/tests/IfcIO.Tests/ProductOccurrenceTests.cs b/tests/IfcIO.Tests/ProductOccurrenceTests.cs new file mode 100644 index 0000000..1e6832c --- /dev/null +++ b/tests/IfcIO.Tests/ProductOccurrenceTests.cs @@ -0,0 +1,212 @@ +using IfcIO.Core; +using IfcIO.Geometry; +using Xunit; + +namespace IfcIO.Tests; + +public class ProductOccurrenceTests +{ + private static string BuildIfc(string schema, string products, string representation = "Body") => $$""" + ISO-10303-21; + HEADER; + FILE_SCHEMA(('{{schema}}')); + ENDSEC; + DATA; + #1=IFCPROJECT('0YvctVUKr0kugbFTf53O9L',$,'Occurrences',$,$,$,$,(#7),#2); + #2=IFCUNITASSIGNMENT((#3)); + #3=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.); + #4=IFCCARTESIANPOINT((0.,0.,0.)); + #5=IFCAXIS2PLACEMENT3D(#4,$,$); + #6=IFCLOCALPLACEMENT($,#5); + #7=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#5,$); + #8=IFCCARTESIANPOINT((0.,0.)); + #9=IFCAXIS2PLACEMENT2D(#8,$); + #10=IFCRECTANGLEPROFILEDEF(.AREA.,$,#9,20.,10.); + #11=IFCDIRECTION((0.,0.,1.)); + #12=IFCEXTRUDEDAREASOLID(#10,#5,#11,100.); + #13=IFCSHAPEREPRESENTATION(#7,'{{representation}}','SweptSolid',(#12)); + #14=IFCPRODUCTDEFINITIONSHAPE($,$,(#13)); + {{products}} + ENDSEC; + END-ISO-10303-21; + """; + + [Theory] + [InlineData("IFC2X3", "IFCCURTAINWALL", "")] + [InlineData("IFC2X3", "IFCPILE", ",.NOTDEFINED.,$")] + [InlineData("IFC4", "IFCFURNITURE", ",$")] + [InlineData("IFC4", "IFCACTUATOR", ",$")] + [InlineData("IFC4", "IFCRAMP", ",$")] + [InlineData("IFC4X3_ADD2", "IFCCOURSE", ",$")] + public void Open_ConcreteProductWithBody_KeepsTypeTagAndMesh(string schema, string type, string tail) + { + string ifc = BuildIfc(schema, $"#20={type}('1YvctVUKr0kugbFTf53O9L',$,'Product',$,$,#6,#14,'P-01'{tail});"); + var model = IfcModel.Open(new StringReader(ifc)); + var product = Assert.Single(model.AllElements); + Assert.Equal(type, product.IfcType); + Assert.Equal("P-01", product.Tag); + Assert.Equal(new IfcBoundingBox(new(-10, -5, 0), new(10, 5, 100)), product.Mesh!.BoundingBox); + } + + [Fact] + public void Open_OtherProductsRequireBody_AndLegacyMetadataOnlyElementsRemain() + { + string ifc = BuildIfc("IFC4", """ + #20=IFCACTUATOR('1YvctVUKr0kugbFTf53O9L',$,'Axis only',$,$,#6,#14,$,$); + #21=IFCWALL('2YvctVUKr0kugbFTf53O9L',$,'Wall metadata',$,$,#6,$,$,$); + """, representation: "Axis"); + var model = IfcModel.Open(new StringReader(ifc)); + var wall = Assert.Single(model.AllElements); + Assert.Equal("IFCWALL", wall.IfcType); + Assert.Null(wall.Mesh); + } + + [Fact] + public void Open_ExcludeSpatialStructuresTypesAndWrongSchemaOccurrences() + { + string ifc = BuildIfc("IFC2X3", """ + #20=IFCBUILDING('1YvctVUKr0kugbFTf53O9L',$,'Building',$,$,#6,#14,$,.ELEMENT.,$,$,$); + #21=IFCACTUATOR('2YvctVUKr0kugbFTf53O9L',$,'IFC4 only',$,$,#6,#14,$,$); + #22=IFCCURTAINWALLTYPE('3YvctVUKr0kugbFTf53O9L',$,'Type',$,$,$,(#24),$,$,.NOTDEFINED.); + #24=IFCREPRESENTATIONMAP(#5,#13); + #25=IFCDISTRIBUTIONPORT('4YvctVUKr0kugbFTf53O9L',$,'Port',$,$,#6,#14,.SOURCE.); + #26=IFCVENDORPROXY('5YvctVUKr0kugbFTf53O9L',$,'Unknown',$,$,#6,#14,$); + """); + Assert.Empty(IfcModel.Open(new StringReader(ifc)).AllElements); + } + + [Fact] + public void Open_SiteWithBody_ImportsTerrainButNotMetadataOnlySite() + { + string ifc = BuildIfc("IFC2X3", """ + #20=IFCSITE('1YvctVUKr0kugbFTf53O9L',$,'Terrain',$,$,#6,#14,$,.ELEMENT.,$,$,$,$,$); + #21=IFCSITE('2YvctVUKr0kugbFTf53O9L',$,'No terrain',$,$,#6,$,$,.ELEMENT.,$,$,$,$,$); + """); + var terrain = Assert.Single(IfcModel.Open(new StringReader(ifc)).AllElements); + Assert.Equal("IFCSITE", terrain.IfcType); + Assert.Null(terrain.Tag); + Assert.Equal(12, terrain.Mesh!.TriangleCount); + } + + [Fact] + public void Open_NestedRamp_InheritsTheStoreyOfItsContainer() + { + string ifc = BuildIfc("IFC4", """ + #20=IFCBUILDINGSTOREY('1YvctVUKr0kugbFTf53O9L',$,'Ground',$,$,#6,$,$,.ELEMENT.,0.); + #21=IFCBUILDINGSTOREY('2YvctVUKr0kugbFTf53O9L',$,'Upper',$,$,#6,$,$,.ELEMENT.,3000.); + #22=IFCRAMP('3YvctVUKr0kugbFTf53O9L',$,'Parent ramp',$,$,#6,$,$,$); + #23=IFCRAMP('4YvctVUKr0kugbFTf53O9L',$,'Ramp body',$,$,#6,#14,'Ramp-01',$); + #24=IFCRELCONTAINEDINSPATIALSTRUCTURE('5YvctVUKr0kugbFTf53O9L',$,$,$,(#22),#21); + #25=IFCRELAGGREGATES('6YvctVUKr0kugbFTf53O9L',$,$,$,#22,(#23)); + """); + var model = IfcModel.Open(new StringReader(ifc)); + Assert.Empty(model.Storeys[0].Elements); + var ramp = Assert.Single(model.Storeys[1].Elements); + Assert.Equal("Ramp-01", ramp.Tag); + Assert.NotNull(ramp.Mesh); + } + + [Fact] + public void Open_UnreadableBody_DoesNotUseClearanceAsTheProductMesh() + { + string ifc = BuildIfc("IFC4", """ + #20=IFCACTUATOR('1YvctVUKr0kugbFTf53O9L',$,'Actuator',$,$,#6,#14,$,$); + #21=IFCSWEPTDISKSOLID(#22,1.,$,$,$); + #22=IFCPOLYLINE((#4,#23)); + #23=IFCCARTESIANPOINT((0.,0.,100.)); + #24=IFCSHAPEREPRESENTATION(#7,'Clearance','SweptSolid',(#12)); + """) + .Replace("'Body','SweptSolid',(#12)", "'Body','AdvancedSweptSolid',(#21)", StringComparison.Ordinal) + .Replace("$,$,(#13)", "$,$,(#13,#24)", StringComparison.Ordinal); + + var product = Assert.Single(IfcModel.Open(new StringReader(ifc)).AllElements); + Assert.Equal("IFCACTUATOR", product.IfcType); + Assert.Null(product.Mesh); + var step = StepReader.Read(new StringReader(IfcModel.Open(new StringReader(ifc)).ToStepString())); + Assert.Null(Assert.Single(step.OfType("IFCBUILDINGELEMENTPROXY")).GetRef(6)); + Assert.Empty(step.OfType("IFCPRODUCTDEFINITIONSHAPE")); + } + + [Fact] + public void Open_SubtractionFeature_KeepsItsMetadataOnlyHost() + { + string ifc = BuildIfc("IFC4", """ + #20=IFCELEMENTASSEMBLY('1YvctVUKr0kugbFTf53O9L',$,'Assembly',$,$,#6,$,$,$,$); + #21=IFCVOIDINGFEATURE('2YvctVUKr0kugbFTf53O9L',$,'Opening',$,$,#6,#14,$,$); + #22=IFCRELVOIDSELEMENT('3YvctVUKr0kugbFTf53O9L',$,$,$,#20,#21); + """); + var model = IfcModel.Open(new StringReader(ifc)); + var assembly = Assert.Single(model.AllElements); + Assert.Equal("IFCELEMENTASSEMBLY", assembly.IfcType); + Assert.Null(assembly.Mesh); + Assert.NotNull(Assert.Single(assembly.Openings).Mesh); + } + + [Fact] + public void Open_NonElementProductWithBody_DoesNotTreatExtraAttributeAsTag() + { + var model = IfcModel.Open(new StringReader(BuildIfc("IFC4", """ + #20=IFCANNOTATION('1YvctVUKr0kugbFTf53O9L',$,'Annotation',$,$,#6,#14); + """))); + var annotation = Assert.Single(model.AllElements); + Assert.Equal("IFCANNOTATION", annotation.IfcType); + Assert.Null(annotation.Tag); + Assert.Equal(12, annotation.Mesh!.TriangleCount); + } + + [Fact] + public void Open_Proxy_ReadsItsOwnTagAttribute() + { + var model = IfcModel.Open(new StringReader(BuildIfc("IFC4", """ + #20=IFCPROXY('1YvctVUKr0kugbFTf53O9L',$,'Proxy',$,$,#6,#14,.PRODUCT.,'Proxy tag'); + """))); + Assert.Equal("Proxy tag", Assert.Single(model.AllElements).Tag); + } + + [Theory] + [InlineData("IFCOPENINGSTANDARDCASE", ".OPENING.")] + [InlineData("IFCVOIDINGFEATURE", "$")] + public void Open_SubtractionFeature_IsAttachedToHostAndNotDuplicated(string type, string predefinedType) + { + var model = IfcModel.Open(new StringReader(BuildIfc("IFC4", $""" + #20=IFCWALL('1YvctVUKr0kugbFTf53O9L',$,'Wall',$,$,#6,#14,$,$); + #21={type}('2YvctVUKr0kugbFTf53O9L',$,'Opening',$,$,#6,#14,$,{predefinedType}); + #22=IFCRELVOIDSELEMENT('3YvctVUKr0kugbFTf53O9L',$,$,$,#20,#21); + """))); + var wall = Assert.Single(model.AllElements); + var opening = Assert.Single(wall.Openings); + Assert.Equal(type, opening.IfcType); + Assert.NotNull(opening.Mesh); + } + + [Theory] + [InlineData("IFC2X3", "IFCCURTAINWALL", "", ".ELEMENT.")] + [InlineData("IFC4", "IFCFURNITURE", ",$", ".NOTDEFINED.")] + public void SaveAndOpen_ProductsWithoutDedicatedWriter_UseTheSchemaProxyKind( + string schema, string type, string tail, string expectedProxyKind) + { + string ifc = BuildIfc(schema, $"#20={type}('1YvctVUKr0kugbFTf53O9L',$,'Product',$,$,#6,#14,'P-01'{tail});"); + var model = IfcModel.Open(new StringReader(ifc)); + var original = Assert.Single(model.AllElements); + string saved = model.ToStepString(); + var step = StepReader.Read(new StringReader(saved)); + Assert.Equal(expectedProxyKind, Assert.Single(step.OfType("IFCBUILDINGELEMENTPROXY")).GetRaw(8)); + var proxy = Assert.Single(IfcModel.Open(new StringReader(saved)).AllElements); + Assert.Equal(original.GlobalId, proxy.GlobalId); + Assert.Equal(original.Tag, proxy.Tag); + Assert.Equal(original.Mesh!.BoundingBox, proxy.Mesh!.BoundingBox); + } + + [Fact] + public void Save_Ifc2x3OpeningHasNoPredefinedTypeArgument() + { + string ifc = BuildIfc("IFC2X3", """ + #20=IFCWALL('1YvctVUKr0kugbFTf53O9L',$,'Wall',$,$,#6,#14,$); + #21=IFCOPENINGELEMENT('2YvctVUKr0kugbFTf53O9L',$,'Opening',$,$,#6,#14,$); + #22=IFCRELVOIDSELEMENT('3YvctVUKr0kugbFTf53O9L',$,$,$,#20,#21); + """); + string saved = IfcModel.Open(new StringReader(ifc)).ToStepString(); + var opening = Assert.Single(StepReader.Read(new StringReader(saved)).OfType("IFCOPENINGELEMENT")); + Assert.Equal(8, opening.Arguments.Count); + } +} diff --git a/tools/README-product-occurrences.md b/tools/README-product-occurrences.md new file mode 100644 index 0000000..ead3551 --- /dev/null +++ b/tools/README-product-occurrences.md @@ -0,0 +1,18 @@ +# IFC product occurrence index + +`generate_product_occurrences.py` reads buildingSMART EXPRESS entity declarations and generates +`src/IfcIO/Schema/IfcProductOccurrences.g.cs`. Only derived entity names, schema membership, STEP +tag slots and subtraction-feature classification are checked in. No schema file or generator dependency is needed at runtime. + +Regenerate using these buildingSMART sources: + +- [IFC2x3 TC1](https://github.com/buildingSMART/IFC4.x-development/blob/0f1c7acb287740d7d40e2d0021c216a9cdf638ab/reference_schemas/IFC2X3_TC1.exp) +- [IFC4 ADD2 TC1](https://github.com/buildingSMART/IFC4.x-development/blob/0f1c7acb287740d7d40e2d0021c216a9cdf638ab/reference_schemas/IFC4_ADD2_TC1.exp) +- [IFC4.3 ADD2](https://github.com/buildingSMART/IFC4.x-output/blob/610ee3f95db9d0380b1eb8de4dc6e17833531518/IFC/RELEASE/IFC4_3/HTML/IFC4X3_ADD2.exp) + +```sh +python tools/generate_product_occurrences.py IFC2X3_TC1.exp IFC4_ADD2_TC1.exp IFC4X3_ADD2.exp +``` + +The classifier includes concrete descendants of `IfcProduct`, excluding ports and spatial products except `IfcSite` terrain. +The reader separately preserves its legacy metadata-only imports. diff --git a/tools/generate_product_occurrences.py b/tools/generate_product_occurrences.py new file mode 100644 index 0000000..da187b1 --- /dev/null +++ b/tools/generate_product_occurrences.py @@ -0,0 +1,97 @@ +"""Generate the product occurrence index from official buildingSMART EXPRESS files. + +Usage: python tools/generate_product_occurrences.py IFC2X3_TC1.exp IFC4_ADD2_TC1.exp IFC4X3_ADD2.exp +The schema files are inputs only and are not distributed in the repository. +""" + +import argparse +import re +from pathlib import Path + + +def product_occurrences(path, expected_schema): + schema = re.sub(r"\(\*.*?\*\)|--[^\n]*", "", path.read_text(encoding="utf-8-sig"), flags=re.S) + if not re.search(rf"(?im)^SCHEMA\s+{expected_schema}\s*;", schema): + raise ValueError(f"{path}: expected SCHEMA {expected_schema}") + + entities = {} + for entity, header in re.findall(r"(?im)^ENTITY\s+(\w+)\b([^;]*);", schema): + parents = re.search(r"\bSUBTYPE\s+OF\s*\(([^)]*)\)", header, re.I) + parent = parents[1].strip().upper() if parents else None + if parent and not parent.isidentifier(): + raise ValueError(f"{path}: unsupported supertype declaration for {entity}") + entities[entity.upper()] = (parent, bool(re.search(r"\bABSTRACT\b", header, re.I))) + + def ancestry(name): + while name: + yield name + name, _ = entities[name] + + excluded = {"IFCSPATIALELEMENT", "IFCSPATIALSTRUCTUREELEMENT", "IFCPORT"} + for name, (_, abstract) in entities.items(): + lineage = set(ancestry(name)) + if abstract or "IFCPRODUCT" not in lineage or (lineage & excluded and name != "IFCSITE"): + continue + tag_index = 7 if "IFCELEMENT" in lineage else 8 if name == "IFCPROXY" else -1 + yield name, tag_index, "IFCFEATUREELEMENTSUBTRACTION" in lineage + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("ifc2x3", type=Path) + parser.add_argument("ifc4", type=Path) + parser.add_argument("ifc4x3", type=Path) + args = parser.parse_args() + + by_name = {} + for path, schema, mask in ( + (args.ifc2x3, "IFC2X3", "V2x3"), + (args.ifc4, "IFC4", "V4"), + (args.ifc4x3, "IFC4X3_ADD2", "V4x3"), + ): + for name, tag_index, subtracts in product_occurrences(path, schema): + entry = by_name.setdefault(name, ([], tag_index, subtracts)) + if entry[1:] != (tag_index, subtracts): + raise ValueError(f"{name}: occurrence metadata changes between schemas") + entry[0].append(mask) + + output = [ + "// Generated by tools/generate_product_occurrences.py from buildingSMART IFC2x3 TC1, IFC4 ADD2 TC1 and IFC4.3 ADD2.", + "using System.Collections.Frozen;", + "", + "namespace IfcIO.Schema;", + "", + "internal static class IfcProductOccurrences", + "{", + " private const int V2x3 = 1, V4 = 2, V4x3 = 4;", + "", + " public static bool TryGetInfo(IfcSchema schema, string type, out int tagIndex, out bool subtracts)", + " {", + " tagIndex = -1;", + " subtracts = false;", + " int version = schema switch", + " {", + " IfcSchema.Ifc2x3 => V2x3,", + " IfcSchema.Ifc4 => V4,", + " IfcSchema.Ifc4x3 => V4x3,", + " _ => 0,", + " };", + " if (!Types.TryGetValue(type, out var occurrence) || (occurrence.Versions & version) == 0) return false;", + " tagIndex = occurrence.TagIndex;", + " subtracts = occurrence.Subtracts;", + " return true;", + " }", + "", + " private static readonly FrozenDictionary Types =", + " new Dictionary(StringComparer.OrdinalIgnoreCase)", + " {", + ] + for name, (versions, tag_index, subtracts) in sorted(by_name.items()): + output.append(f' ["{name}"] = ({" | ".join(versions)}, {tag_index}, {str(subtracts).lower()}),') + output += [" }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);", "}", ""] + destination = Path(__file__).resolve().parents[1] / "src" / "IfcIO" / "Schema" / "IfcProductOccurrences.g.cs" + destination.write_text("\n".join(output), encoding="utf-8", newline="\n") + + +if __name__ == "__main__": + main()