From 50ac236e1c01c13b718867b650a60ecc7d4e8ce0 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:38:09 +0300 Subject: [PATCH] Detect IFC4X3 and prevent silent schema rewrites --- CHANGELOG.md | 2 + README.md | 2 + docs/public-api.md | 6 + src/IfcIO.Cli/Program.cs | 47 ++++-- src/IfcIO/Core/StepReader.cs | 23 ++- src/IfcIO/IfcModel.cs | 81 ++++++++-- src/IfcIO/Patch/IfcPatch.cs | 8 + src/IfcIO/Schema/IfcEnums.cs | 3 + src/IfcIO/Validation/IfcValidator.cs | 20 ++- tests/IfcIO.Tests/SchemaDetectionTests.cs | 178 ++++++++++++++++++++++ 10 files changed, 347 insertions(+), 23 deletions(-) create mode 100644 tests/IfcIO.Tests/SchemaDetectionTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index d16b247..3cdd353 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 +- IFC import recognizes IFC4.3 separately and reports unknown, missing and multiple schema identifiers. IFC4.3 + is read as a subset and is not silently rewritten as IFC4. - 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. diff --git a/README.md b/README.md index 2292825..2ec1d73 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,8 @@ The documentation site with API references and guides is at IfcSchema.Ifc2x3, + "IFC4" => IfcSchema.Ifc4, + _ => throw new ArgumentException($"{option} requires ifc2x3 or ifc4. Other IFC output schemas are not supported."), + }; + } + + private static void WarnOnPartialIfc4x3Import(IfcModel model) + { + if (model.Schema != IfcSchema.Ifc4x3) return; + Console.Error.WriteLine($"Warning: {model.SourceSchemaIdentifier} is read as a subset. Uninterpreted content is omitted."); + if (model.UnsupportedPlacementCount > 0) + Console.Error.WriteLine($"Warning: omitted {model.UnsupportedPlacementCount} representations or ports with unsupported placements."); + } + private static int ExecuteQuery(string[] args) { if (args.Length < 2) @@ -715,7 +737,10 @@ private static int ExecutePatch(string[] args) string? extractQuery = GetOptionValue(args, "--extract"); string? offsetStr = GetOptionValue(args, "--offset"); string? scaleStr = GetOptionValue(args, "--scale"); - string? schemaStr = GetOptionValue(args, "--migrate") ?? (string.Equals(recipe, "migrate", StringComparison.OrdinalIgnoreCase) ? GetOptionValue(args, "--schema") : null); + IfcSchema? targetSchema = GetWritableSchemaOption(args, "--migrate"); + if (targetSchema is null && string.Equals(recipe, "migrate", StringComparison.OrdinalIgnoreCase)) + targetSchema = GetWritableSchemaOption(args, "--schema") + ?? throw new ArgumentException("--recipe migrate requires --schema ifc2x3 or ifc4."); Geometry.IfcVector3? manualOffset = null; if (args.Contains("--offset", StringComparer.OrdinalIgnoreCase)) @@ -774,11 +799,10 @@ private static int ExecutePatch(string[] args) Console.WriteLine($" * Scaled model vertices by factor: {scaleFactor:G}"); } - if (!string.IsNullOrEmpty(schemaStr)) + if (targetSchema is { } requestedSchema) { - var targetSchema = schemaStr.Contains('4') ? IfcSchema.Ifc4 : IfcSchema.Ifc2x3; - Patch.IfcPatch.MigrateSchema(model, targetSchema); - Console.WriteLine($" * Migrated model schema to: {targetSchema}"); + Patch.IfcPatch.MigrateSchema(model, requestedSchema); + Console.WriteLine($" * Migrated model schema to: {requestedSchema}"); } model.Save(outputPath); @@ -1182,6 +1206,7 @@ private static int ExecuteView(string[] args) var sw = Stopwatch.StartNew(); var model = IfcModel.Open(inputPath); + WarnOnPartialIfc4x3Import(model); if (gridsPath is not null) { diff --git a/src/IfcIO/Core/StepReader.cs b/src/IfcIO/Core/StepReader.cs index 5500da4..4b12f7d 100644 --- a/src/IfcIO/Core/StepReader.cs +++ b/src/IfcIO/Core/StepReader.cs @@ -154,6 +154,9 @@ public sealed class StepFile public string? OriginatingSystem { get; set; } public string? Authorization { get; set; } public string? Schema { get; set; } + /// All identifiers declared in FILE_SCHEMA. + public IReadOnlyList SchemaIdentifiers { get; internal set; } = []; + internal bool HasSchemaDeclaration { get; set; } public Dictionary Entities { get; } = new(4096); @@ -284,7 +287,25 @@ IEnumerable Strings(int index) switch (statement[..open].TrimEnd().ToUpperInvariant()) { case "FILE_SCHEMA": - file.Schema = Strings(0).FirstOrDefault(); + if (file.HasSchemaDeclaration) + throw new InvalidDataException("The STEP header contains more than one FILE_SCHEMA declaration."); + file.HasSchemaDeclaration = true; + if (arguments.Count != 1 || arguments[0] is not { Length: >= 2 } list + || list[0] != '(' || list[^1] != ')') + throw new InvalidDataException("FILE_SCHEMA must contain one list of schema identifiers."); + var schemaTokens = StepEntity.ParseArguments(list[1..^1]); + if (schemaTokens.Count == 0 || list.AsSpan(1, list.Length - 2).TrimEnd().EndsWith(",")) + throw new InvalidDataException("FILE_SCHEMA must contain a nonempty list of schema identifiers."); + var identifiers = new List(schemaTokens.Count); + foreach (string token in schemaTokens) + { + if (token.Length < 2 || token[0] != '\'' || token[^1] != '\'' + || StepEntity.DecodeString(token) is not { Length: > 0 } identifier) + throw new InvalidDataException("FILE_SCHEMA identifiers must be nonempty STEP strings."); + identifiers.Add(identifier); + } + file.SchemaIdentifiers = identifiers.AsReadOnly(); + file.Schema = identifiers[0]; break; case "FILE_DESCRIPTION": file.Descriptions = Strings(0).ToArray(); diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index 54e2fd2..5ae609a 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -18,6 +18,12 @@ public sealed partial class IfcModel private const string DegreeInRadians = "0.017453292519943278"; public IfcSchema Schema { get; set; } = IfcSchema.Ifc2x3; + /// The exact FILE_SCHEMA identifier of the source file, or null for a new model. + public string? SourceSchemaIdentifier { get; internal set; } + + internal bool IsIfc4x3Subset => Schema == IfcSchema.Ifc4x3 || IsIfc4x3Identifier(SourceSchemaIdentifier); + /// Number of IFC4X3 product representations or ports omitted because their placement is unsupported. + public int UnsupportedPlacementCount { get; internal set; } public IfcLengthUnit LengthUnit { get; set; } = IfcLengthUnit.Millimetre; public IfcPlaneAngleUnit AngleUnit { get; set; } = IfcPlaneAngleUnit.Degree; @@ -662,6 +668,7 @@ public Validation.Ids.IfcIdsValidationReport ValidateIds(System.Xml.Linq.XDocume public void Save(string path) { ArgumentNullException.ThrowIfNull(path); + EnsureWritableSchema(); if (path.EndsWith(".ifczip", StringComparison.OrdinalIgnoreCase)) { SaveZip(path); @@ -677,6 +684,7 @@ public void Save(string path) public void SaveZip(string path) { ArgumentNullException.ThrowIfNull(path); + EnsureWritableSchema(); string innerName = Path.GetFileNameWithoutExtension(path) + ".ifc"; using var fs = File.Create(path); @@ -691,6 +699,7 @@ public void SaveZip(string path) public void Save(Stream stream, string fileName = "model.ifc") { ArgumentNullException.ThrowIfNull(stream); + EnsureWritableSchema(); using var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: 65536, leaveOpen: true); Save(writer, fileName); } @@ -707,6 +716,7 @@ public string ToStepString(string fileName = "model.ifc") public void Save(TextWriter writer, string fileName = "model.ifc") { ArgumentNullException.ThrowIfNull(writer); + EnsureWritableSchema(); var w = new StepWriter(); string schemaStr = Schema == IfcSchema.Ifc4 ? "IFC4" : "IFC2X3"; @@ -1410,6 +1420,14 @@ string ProductGuid(IfcElement element, string domain) w.WriteTo(writer, fileName, schemaStr, viewDef, Application, Organization); } + internal void EnsureWritableSchema() + { + if (IsIfc4x3Subset) + throw new NotSupportedException("IFC4X3 is supported for subset import only. Rewriting it as IFC is not supported."); + if (Schema is not (IfcSchema.Ifc2x3 or IfcSchema.Ifc4)) + throw new NotSupportedException($"Writing IFC schema '{Schema}' is not supported."); + } + private void WritePropertyAndQuantitySets(StepWriter w, IfcElement element, int entityId, int ownerHistoryId) { // Property sets @@ -1569,14 +1587,13 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions ArgumentNullException.ThrowIfNull(reader); var step = StepReader.Read(reader); - var schema = (step.Schema?.Contains("IFC4", StringComparison.OrdinalIgnoreCase) == true) - ? IfcSchema.Ifc4 - : IfcSchema.Ifc2x3; + var schema = ReadSchema(step); var model = new IfcModel { ProjectName = modelName ?? step.FileName ?? "Imported IFC Project", Schema = schema, + SourceSchemaIdentifier = step.Schema, }; model.Storeys.Clear(); // Clear default storey @@ -1802,6 +1819,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions geomToMaterialMap, IfcTransform.Scale(geometryScale).Multiply(ParseWorldCoordinateSystem(step)), radiansPerAngleUnit, + omitUnsupportedPlacements: schema == IfcSchema.Ifc4x3, keepParametric: geometryScale == 1.0); var defaultStorey = model.Storeys[0]; var allElementsMap = new Dictionary(); @@ -1889,9 +1907,8 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions // Parse Mesh / Solid Geometry int? shapeDefId = entity.GetRef(6); - if (shapeDefId.HasValue) + if (shapeDefId.HasValue && ResolveObjectPlacement(geometry, entity.GetRef(5)) is { } placement) { - var placement = ResolveObjectPlacement(geometry, entity.GetRef(5)); var mesh = ParseGeometry(geometry, shapeDefId.Value, name, placement, out var mat, out var solid, out var revSolid, out var boolResult); if (mesh is not null) { @@ -1914,6 +1931,10 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions element.Material = mat; } } + else if (shapeDefId.HasValue) + { + model.UnsupportedPlacementCount++; + } allElementsMap[entity.Id] = element; if (isSpace) @@ -2479,7 +2500,11 @@ openElem is IfcOpeningElement opening && string portName = portEnt.GetString(2) ?? "Port"; string? desc = portEnt.GetString(3); string? sysType = portEnt.GetString(4); - var portPlacement = ResolveObjectPlacement(geometry, portEnt.GetRef(5)); + if (ResolveObjectPlacement(geometry, portEnt.GetRef(5)) is not { } portPlacement) + { + model.UnsupportedPlacementCount++; + continue; + } var pos = portPlacement.Origin; var dir = portPlacement.Z.Normalized(); if (dir == IfcVector3.Zero) dir = IfcVector3.UnitZ; @@ -2535,6 +2560,36 @@ openElem is IfcOpeningElement opening && return model; } + private static IfcSchema ReadSchema(StepFile step) + { + if (step.SchemaIdentifiers.Count > 1) + throw new NotSupportedException($"Multiple IFC schema identifiers are not supported: {string.Join(", ", step.SchemaIdentifiers)}."); + if (string.IsNullOrWhiteSpace(step.Schema)) + throw new InvalidDataException("The STEP file does not declare an IFC schema in FILE_SCHEMA."); + string? name = SchemaName(step.Schema); + if (string.Equals(name, "IFC2X3", StringComparison.OrdinalIgnoreCase)) return IfcSchema.Ifc2x3; + if (string.Equals(name, "IFC4", StringComparison.OrdinalIgnoreCase)) return IfcSchema.Ifc4; + if (IsIfc4x3Identifier(step.Schema)) return IfcSchema.Ifc4x3; + throw new NotSupportedException($"IFC schema '{step.Schema}' is not supported."); + } + + private static bool IsIfc4x3Identifier(string? identifier) => + identifier is not null && SchemaName(identifier)?.ToUpperInvariant() is "IFC4X3" or "IFC4X3_ADD1" or "IFC4X3_ADD2"; + + private static string? SchemaName(string identifier) + { + // Part 21 allows a numeric object identifier after the exact EXPRESS schema name. + int brace = identifier.IndexOf('{'); + if (brace < 0) return identifier; + if (brace == 0 || !identifier.EndsWith('}')) return null; + string[] arcs = identifier[(brace + 1)..^1].Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (arcs.Length < 2 || arcs[0] is not ("0" or "1" or "2") || arcs.Any(arc => !arc.All(char.IsAsciiDigit))) + return null; + if (arcs[0] != "2" && (!int.TryParse(arcs[1], NumberStyles.None, CultureInfo.InvariantCulture, out int second) || second > 39)) + return null; + return identifier[..brace].TrimEnd(' '); + } + private int WriteElementShape(StepWriter w, IfcElement element, int bodySubContextId, Dictionary styleCache, bool useTessellation) { int? styleId = null; @@ -2753,7 +2808,8 @@ private int WriteRevolvedAreaSolid(StepWriter w, IfcRevolvedAreaSolid solid) /// State shared while reading product geometry: caches for placements and mapped representations. private sealed class GeometryReadContext( - StepFile step, Dictionary geomToMaterialMap, IfcTransform root, double radiansPerAngleUnit, bool keepParametric) + StepFile step, Dictionary geomToMaterialMap, IfcTransform root, double radiansPerAngleUnit, + bool omitUnsupportedPlacements, bool keepParametric) { public StepFile Step { get; } = step; public Dictionary GeomToMaterialMap { get; } = geomToMaterialMap; @@ -2761,6 +2817,7 @@ private sealed class GeometryReadContext( /// Unit scale applied after the world coordinate system of the model context. public IfcTransform Root { get; } = root; public double RadiansPerAngleUnit { get; } = radiansPerAngleUnit; + public bool OmitUnsupportedPlacements { get; } = omitUnsupportedPlacements; /// False when geometry is rescaled to metres: parametric solids stay in file units and would disagree with LengthUnit. public bool KeepParametric { get; } = keepParametric; @@ -3027,7 +3084,7 @@ private static (IfcMesh? Mesh, IfcMaterial? Material) ParseMappedRepresentation( } /// Resolves an IfcObjectPlacement (PlacementRelTo chain) into a world transform in model length units. - private static IfcTransform ResolveObjectPlacement(GeometryReadContext ctx, int? placementId) + private static IfcTransform? ResolveObjectPlacement(GeometryReadContext ctx, int? placementId) { // Walk up to a resolved or root placement, then compose downwards (iterative: chains may be deep). var chain = new List(); @@ -3042,8 +3099,12 @@ private static IfcTransform ResolveObjectPlacement(GeometryReadContext ctx, int? } var ent = ctx.Step.Find(id.Value); - // shortcut: IfcGridPlacement (and any non-local placement) resolves to the world origin; add grid intersection support when a model needs it. - if (ent is null || !ent.Type.Equals("IFCLOCALPLACEMENT", StringComparison.OrdinalIgnoreCase)) break; + if (ent is null || !ent.Type.Equals("IFCLOCALPLACEMENT", StringComparison.OrdinalIgnoreCase)) + { + // A linear or grid placement cannot be reduced to a local origin. + if (ctx.OmitUnsupportedPlacements) return null; + break; + } if (!visited.Add(id.Value)) { throw new InvalidDataException($"IFC placement #{id.Value} is relative to itself (PlacementRelTo cycle)."); diff --git a/src/IfcIO/Patch/IfcPatch.cs b/src/IfcIO/Patch/IfcPatch.cs index 267b877..1cff9db 100644 --- a/src/IfcIO/Patch/IfcPatch.cs +++ b/src/IfcIO/Patch/IfcPatch.cs @@ -191,6 +191,8 @@ public static IfcModel Extract(IfcModel source, Func predicate LengthUnit = source.LengthUnit, AngleUnit = source.AngleUnit, Schema = source.Schema, + SourceSchemaIdentifier = source.SourceSchemaIdentifier, + UnsupportedPlacementCount = source.UnsupportedPlacementCount, }; target.Storeys.Clear(); @@ -238,6 +240,9 @@ public static IfcModel Merge(IEnumerable models, string mergedProjectN return modelList[0]; } + if (modelList.Any(model => model.IsIfc4x3Subset)) + throw new NotSupportedException("Merging IFC4X3 models is not supported because their import is limited to a subset."); + var baseModel = modelList[0]; var merged = new IfcModel { @@ -344,6 +349,9 @@ private static IfcElement CloneElement(IfcElement source, int newId) public static void MigrateSchema(IfcModel model, IfcSchema targetSchema) { ArgumentNullException.ThrowIfNull(model); + model.EnsureWritableSchema(); + if (targetSchema is not (IfcSchema.Ifc2x3 or IfcSchema.Ifc4)) + throw new NotSupportedException($"Migrating to IFC schema '{targetSchema}' is not supported."); model.Schema = targetSchema; if (targetSchema == IfcSchema.Ifc4) { diff --git a/src/IfcIO/Schema/IfcEnums.cs b/src/IfcIO/Schema/IfcEnums.cs index ab2b202..dc0ca70 100644 --- a/src/IfcIO/Schema/IfcEnums.cs +++ b/src/IfcIO/Schema/IfcEnums.cs @@ -10,6 +10,9 @@ public enum IfcSchema /// IFC4 Reference View / Design Transfer View. Ifc4, + + /// IFC4.3. Import supports a subset of the schema; IFC export is not supported. + Ifc4x3, } /// diff --git a/src/IfcIO/Validation/IfcValidator.cs b/src/IfcIO/Validation/IfcValidator.cs index 01a1198..4b1c904 100644 --- a/src/IfcIO/Validation/IfcValidator.cs +++ b/src/IfcIO/Validation/IfcValidator.cs @@ -32,7 +32,25 @@ public static IfcValidationResult Validate(IfcModel model) }); } - if (model.Schema != IfcSchema.Ifc2x3 && model.Schema != IfcSchema.Ifc4) + if (model.IsIfc4x3Subset) + { + issues.Add(new IfcValidationIssue + { + RuleId = "IFC_SCHEMA_SUBSET", + Severity = IfcIssueSeverity.Warning, + Message = "IFC4X3 is read as a subset. These checks do not validate full IFC4X3 conformance.", + }); + if (model.UnsupportedPlacementCount > 0) + { + issues.Add(new IfcValidationIssue + { + RuleId = "IFC_UNSUPPORTED_PLACEMENTS", + Severity = IfcIssueSeverity.Warning, + Message = $"Omitted {model.UnsupportedPlacementCount} representations or ports with unsupported IFC4X3 placements.", + }); + } + } + else if (model.Schema != IfcSchema.Ifc2x3 && model.Schema != IfcSchema.Ifc4) { issues.Add(new IfcValidationIssue { diff --git a/tests/IfcIO.Tests/SchemaDetectionTests.cs b/tests/IfcIO.Tests/SchemaDetectionTests.cs new file mode 100644 index 0000000..e9b0a43 --- /dev/null +++ b/tests/IfcIO.Tests/SchemaDetectionTests.cs @@ -0,0 +1,178 @@ +using IfcIO.Cli; +using IfcIO.Core; +using IfcIO.Patch; +using IfcIO.Schema; +using Xunit; + +namespace IfcIO.Tests; + +public sealed class SchemaDetectionTests +{ + private static string ModelText(string schemaDeclaration) => $""" + ISO-10303-21; + HEADER; + {schemaDeclaration} + ENDSEC; + DATA; + #1=IFCPROJECT('01vctVUKr0kugbFTf53O9L',$,'Schema test',$,$,$,$,(),$); + #2=IFCWALL('02vctVUKr0kugbFTf53O9L',$,'Wall',$,$,$,$,$,$); + ENDSEC; + END-ISO-10303-21; + """; + + [Theory] + [InlineData("IFC2X3", IfcSchema.Ifc2x3)] + [InlineData("ifc4", IfcSchema.Ifc4)] + [InlineData("IFC4 { 2 999 1 }", IfcSchema.Ifc4)] + public void Open_RecognizesExactWritableSchemaNames(string schema, IfcSchema expected) + { + var model = IfcModel.Open(new StringReader(ModelText($"FILE_SCHEMA(('{schema}'));"))); + Assert.Equal(expected, model.Schema); + Assert.Equal(schema, model.SourceSchemaIdentifier); + Assert.Single(model.AllElements); + Assert.Contains(expected == IfcSchema.Ifc4 ? "FILE_SCHEMA(('IFC4'))" : "FILE_SCHEMA(('IFC2X3'))", model.ToStepString()); + } + + [Theory] + [InlineData("IFC4X3")] + [InlineData("IFC4X3_ADD1")] + [InlineData("IFC4X3_ADD2")] + [InlineData("IFC4X3_ADD2 { 2 999 1 }")] + public void Open_RecognizesIfc4x3ButDoesNotEnableWriting(string schema) + { + var model = IfcModel.Open(new StringReader(ModelText($"FILE_SCHEMA(('{schema}'));"))); + Assert.Equal(IfcSchema.Ifc4x3, model.Schema); + Assert.Equal(schema, model.SourceSchemaIdentifier); + Assert.Single(model.AllElements); + Assert.Contains(model.Validate().Warnings, warning => warning.RuleId == "IFC_SCHEMA_SUBSET"); + Assert.Throws(() => model.ToStepString()); + Assert.Throws(() => model.Extract(_ => true).ToStepString()); + + model.Schema = IfcSchema.Ifc4; + Assert.Throws(() => model.ToStepString()); + } + + [Theory] + [InlineData("not-IFC4")] + [InlineData("IFC4X3_UNKNOWN")] + [InlineData("IFC4 { unknown }")] + [InlineData("IFC5")] + public void Open_RejectsAnUnknownSchemaBeforeInterpretingTheModel(string schema) + { + var input = ModelText($"FILE_SCHEMA(('{schema}'));"); + var file = StepReader.Read(new StringReader(input)); + Assert.Equal(schema, file.Schema); + + var error = Assert.Throws(() => IfcModel.Open(new StringReader(input))); + Assert.Contains(schema, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Open_RejectsMissingAndAmbiguousSchemaDeclarations() + { + const string ambiguous = "FILE_SCHEMA(('IFC2X3','IFC4'));"; + Assert.Throws(() => IfcModel.Open(new StringReader(ModelText("")))); + var step = StepReader.Read(new StringReader(ModelText(ambiguous))); + Assert.Collection(step.SchemaIdentifiers, first => Assert.Equal("IFC2X3", first), second => Assert.Equal("IFC4", second)); + Assert.Throws(() => + IfcModel.Open(new StringReader(ModelText(ambiguous)))); + Assert.Throws(() => + IfcModel.Open(new StringReader(ModelText("FILE_SCHEMA(('IFC4X3')); FILE_SCHEMA(('IFC4'));")))); + } + + [Theory] + [InlineData("FILE_SCHEMA((IFC4));")] + [InlineData("FILE_SCHEMA(('IFC4',$));")] + [InlineData("FILE_SCHEMA(('IFC4'),('IFC4X3_ADD2'));")] + [InlineData("FILE_SCHEMA(('IFC4',));")] + public void Open_RejectsMalformedSchemaDeclarations(string declaration) + { + Assert.Throws(() => IfcModel.Open(new StringReader(ModelText(declaration)))); + } + + [Fact] + public void Open_Ifc4x3OmitsGeometryUnderANonLocalPlacement() + { + const string text = """ + HEADER; FILE_SCHEMA(('IFC4X3_ADD2')); ENDSEC; + DATA; + #1=IFCBUILDINGELEMENTPROXY('01vctVUKr0kugbFTf53O9L',$,'Linear placement',$,$,#12,#30,$,$); + #2=IFCBUILDINGELEMENTPROXY('02vctVUKr0kugbFTf53O9L',$,'Local below linear',$,$,#11,#30,$,$); + #3=IFCBUILDINGELEMENTPROXY('03vctVUKr0kugbFTf53O9L',$,'Local placement',$,$,#19,#30,$,$); + #11=IFCLOCALPLACEMENT(#12,#20); + #12=IFCLINEARPLACEMENT($,#13,$); + #13=IFCAXIS2PLACEMENTLINEAR(#14,$,$); + #14=IFCPOINTBYDISTANCEEXPRESSION(IFCLENGTHMEASURE(0.),$,$,$,#15); + #15=IFCPOLYLINE((#16,#17)); + #16=IFCCARTESIANPOINT((0.,0.,0.)); + #17=IFCCARTESIANPOINT((100.,0.,0.)); + #19=IFCLOCALPLACEMENT($,#20); + #20=IFCAXIS2PLACEMENT3D(#16,$,$); + #30=IFCPRODUCTDEFINITIONSHAPE($,$,(#31)); + #31=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#32)); + #32=IFCEXTRUDEDAREASOLID(#33,#20,#34,10.); + #33=IFCCIRCLEPROFILEDEF(.AREA.,$,$,2.); + #34=IFCDIRECTION((0.,0.,1.)); + ENDSEC; + """; + var model = IfcModel.Open(new StringReader(text)); + + Assert.Equal(2, model.UnsupportedPlacementCount); + Assert.Single(model.AllElements, element => element.GetEffectiveMesh() is not null); + Assert.Contains(model.Validate().Warnings, warning => warning.RuleId == "IFC_UNSUPPORTED_PLACEMENTS"); + } + + [Theory] + [InlineData("existing.ifc")] + [InlineData("existing.ifczip")] + public void Save_DoesNotTruncateAFileWhenTheSchemaIsReadOnly(string name) + { + var model = IfcModel.Open(new StringReader(ModelText("FILE_SCHEMA(('IFC4X3_ADD2'));"))); + var dir = Directory.CreateTempSubdirectory("ifcio-schema-"); + try + { + string path = Path.Combine(dir.FullName, name); + File.WriteAllText(path, "keep this"); + Assert.Throws(() => model.Save(path)); + Assert.Equal("keep this", File.ReadAllText(path)); + } + finally { dir.Delete(recursive: true); } + } + + [Fact] + public void Cli_ReportsUnsupportedSchemaAndDoesNotRewriteIfc4x3() + { + var dir = Directory.CreateTempSubdirectory("ifcio-schema-cli-"); + try + { + string input = Path.Combine(dir.FullName, "model.ifc"); + string target = Path.Combine(dir.FullName, "target.ifc"); + File.WriteAllText(input, ModelText("FILE_SCHEMA(('IFC4X3_ADD2'));")); + File.WriteAllText(target, "previous file"); + + Assert.Equal(0, Program.Main(["info", input])); + Assert.Equal(1, Program.Main(["export", input, "--ifc", target, "--schema", "ifc4"])); + Assert.Equal(1, Program.Main(["patch", input, "--migrate", "ifc4", "-o", target])); + Assert.Equal("previous file", File.ReadAllText(target)); + + File.WriteAllText(input, ModelText("FILE_SCHEMA(('NOT_IFC4'));")); + Assert.Equal(1, Program.Main(["info", input])); + File.WriteAllText(input, ModelText("FILE_SCHEMA(('IFC4'));")); + Assert.Equal(1, Program.Main(["export", input, "--ifc", target, "--schema", "ifc4x3"])); + Assert.Equal(1, Program.Main(["patch", input, "--migrate", "ifc4x3", "-o", target])); + Assert.Equal("previous file", File.ReadAllText(target)); + } + finally { dir.Delete(recursive: true); } + } + + [Fact] + public void Patch_RejectsMergingAndMigrationFromAnIfc4x3Subset() + { + var imported = IfcModel.Open(new StringReader(ModelText("FILE_SCHEMA(('IFC4X3_ADD1'));"))); + var writable = IfcModel.Create("Other model", IfcSchema.Ifc4); + + Assert.Throws(() => IfcPatch.MigrateSchema(imported, IfcSchema.Ifc4)); + Assert.Throws(() => IfcModel.Merge([imported, writable])); + Assert.Equal(IfcSchema.Ifc4x3, imported.Schema); + } +}