From 81c279c51d4ccb90d14844c5b36bc4adc9d4d8d1 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:15:45 +0300 Subject: [PATCH] Preserve IFC length and plane angle units --- CHANGELOG.md | 4 + docs/public-api.md | 11 ++ docs/scene-adapter.md | 4 +- src/IfcIO.Cli/Program.cs | 17 ++- src/IfcIO.Scene/IfcSceneReader.cs | 2 +- src/IfcIO/Geometry/SweptSolidTypes.cs | 1 + src/IfcIO/IfcModel.cs | 145 +++++++++++++++++------- src/IfcIO/IfcReadOptions.cs | 11 ++ tests/IfcIO.Tests/IfcModelTests.cs | 50 ++++++++ tests/IfcIO.Tests/RevolvedSolidTests.cs | 109 ++++++++++++++++++ 10 files changed, 307 insertions(+), 47 deletions(-) create mode 100644 src/IfcIO/IfcReadOptions.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 92aa037..b2cf39b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ All notable changes to the `IfcIO` library are documented in this file. ## [Unreleased] ### Fixed +- IFC export declares feet and inches as conversion-based length units and respects the selected plane angle unit. + Revolved-solid geometry converts between the file's angle unit and radians in memory. The CLI labels storey elevations in the model's units. +- Length quantities follow the model length unit after import, and metre-based cost quantities retain their explicit unit. +- Read options and `ifcio patch --legacy-ifcio-radian-sweeps` let callers repair older IfcIO files with mislabeled sweep angles. - IFC import no longer treats type definitions, styles, or lining properties as building element occurrences. - IFC2x3 and IFC4 exports write the profile attributes expected by each schema for I, L and U sections. IFC2x3 parameterized profiles also get the required local placement, including at the origin. diff --git a/docs/public-api.md b/docs/public-api.md index cadb53f..5261621 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -15,6 +15,17 @@ This page summarizes the public types and entry points of the `IfcIO` package. | `IfcBuildingStorey`, `IfcSpace` | Storeys hold elements and spaces and carry elevations. The model does not expose separate `IfcSite`, `IfcBuilding`, or `IfcProject` objects. | | `IfcGuid` | buildingSMART 22-character compressed GlobalId encoder/decoder with bidirectional conversion to 128-bit .NET `Guid`. | +`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. +If the file has no usable plane angle unit, the reader assumes radians. Length quantities are read in the same +length unit as geometry; area and volume quantity handling is unchanged. + +Older IfcIO exports declared degrees but stored revolved-solid angles in radians. Normal reads trust the IFC unit +declaration. For a file known to have this legacy error, use +`IfcModel.Open(path, new IfcReadOptions { LegacyIfcIoRevolvedAnglesInRadians = true })`, then save the model, or run +`ifcio patch old.ifc --legacy-ifcio-radian-sweeps -o repaired.ifc`. + ## Geometry & Representation | Type | Description | diff --git a/docs/scene-adapter.md b/docs/scene-adapter.md index 0d361d4..7ab4092 100644 --- a/docs/scene-adapter.md +++ b/docs/scene-adapter.md @@ -93,8 +93,8 @@ rebases them, for example on `ComputeBounds().Center`, before narrowing them to `ifc:` keys and come after the occurrence sets in `PropertySetIds`, so a lookup by key finds the occurrence value first. - Property values are text even when the IFC value is a number or a boolean: IfcIO keeps only the text. -- Length, area, volume and weight quantities are text in file units. For a file whose length unit IfcIO converts to - metres while reading (for example centimetres), geometry is in metres but quantities stay in file units. +- Length quantities are text in the model's length unit, which may be metres for a file in a different length + unit (for example centimetres). Area, volume and weight quantities retain the file's values. - An element without a GlobalId in the file gets a new random GlobalId from IfcIO each time it is read, so its `SourceId` is not stable. - Transparency is not read from files by IfcIO; materials built in memory keep their alpha. diff --git a/src/IfcIO.Cli/Program.cs b/src/IfcIO.Cli/Program.cs index 79562f2..758aa02 100644 --- a/src/IfcIO.Cli/Program.cs +++ b/src/IfcIO.Cli/Program.cs @@ -101,6 +101,8 @@ private static void PrintUsage() --purge Remove empty/duplicate property sets, quantity sets, and empty storeys --reset-coords Shift large UTM coordinates to local origin (0,0,0) to prevent jitter --offset Translate model geometry by given coordinate offset + --legacy-ifcio-radian-sweeps + Repair old IfcIO files that stored sweep angles in radians despite declaring degrees --extract Extract matching elements into a separate IFC model -o, --output Output file path for patched IFC model @@ -229,9 +231,17 @@ private static int ExecuteInfo(string[] args) Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(" Spatial Hierarchy (Storeys):"); Console.ResetColor(); + string elevationUnit = model.LengthUnit switch + { + IfcLengthUnit.Millimetre => "mm", + IfcLengthUnit.Metre => "m", + IfcLengthUnit.Foot => "ft", + IfcLengthUnit.Inch => "in", + _ => "?", + }; foreach (var storey in model.Storeys) { - Console.WriteLine($" - {storey.Name,-24} Elevation: {storey.Elevation,8:F2} mm | Elements: {storey.Elements.Count} | Spaces: {storey.Spaces.Count}"); + Console.WriteLine($" - {storey.Name,-24} Elevation: {storey.Elevation,8:F2} {elevationUnit} | Elements: {storey.Elements.Count} | Spaces: {storey.Spaces.Count}"); } } @@ -723,7 +733,10 @@ private static int ExecutePatch(string[] args) } var sw = Stopwatch.StartNew(); - var model = IfcModel.Open(inputPath); + var model = IfcModel.Open(inputPath, new IfcReadOptions + { + LegacyIfcIoRevolvedAnglesInRadians = args.Contains("--legacy-ifcio-radian-sweeps", StringComparer.OrdinalIgnoreCase), + }); if (!string.IsNullOrEmpty(extractQuery)) { diff --git a/src/IfcIO.Scene/IfcSceneReader.cs b/src/IfcIO.Scene/IfcSceneReader.cs index 1e61e2f..4d2cee3 100644 --- a/src/IfcIO.Scene/IfcSceneReader.cs +++ b/src/IfcIO.Scene/IfcSceneReader.cs @@ -249,7 +249,7 @@ private static bool IsNotProduct(string ifcType) => private static SceneDiagnostic Issue(SceneSeverity severity, string code, string reason, IfcElement element) => new(severity, code, $"{reason}; element #{element.Id} '{element.Name}' ({element.IfcType}) has no geometry in the scene.", element.GlobalId); - // Quantities are doubles in IfcIO, in the file's units (not always IfcModel.LengthUnit), which IfcIO does not report. + // Length quantities use the model's length unit; the other quantities retain their file values. // A number with a null Unit means dimensionless, so only a count is a number; every other quantity is text. private static SceneValue QuantityValue(IfcPhysicalQuantity quantity) { diff --git a/src/IfcIO/Geometry/SweptSolidTypes.cs b/src/IfcIO/Geometry/SweptSolidTypes.cs index 43ffb58..820b018 100644 --- a/src/IfcIO/Geometry/SweptSolidTypes.cs +++ b/src/IfcIO/Geometry/SweptSolidTypes.cs @@ -362,6 +362,7 @@ public sealed class IfcRevolvedAreaSolid public IfcProfileDef Profile { get; set; } public IfcVector3 Position { get; set; } = IfcVector3.Zero; public IfcAxis1Placement Axis { get; set; } = new(); + /// Sweep angle in radians, regardless of the model's IFC plane angle unit. public double Angle { get; set; } = 2.0 * Math.PI; public IfcRevolvedAreaSolid(IfcProfileDef profile, double angle = 2.0 * Math.PI, IfcVector3? position = null, IfcAxis1Placement? axis = null) diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index d2e5091..64e6d40 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -680,20 +680,14 @@ public void Save(TextWriter writer, string fileName = "model.ifc") $"{StepWriter.Ref(personOrgId)},{StepWriter.Ref(appId)},.READWRITE.,.NOCHANGE.,$,$,$,{epochSeconds}"); // 2. Units & Geometric Context - int lengthUnitId = LengthUnit == IfcLengthUnit.Millimetre - ? w.Add("IFCSIUNIT", "*,.LENGTHUNIT.,.MILLI.,.METRE.") - : w.Add("IFCSIUNIT", "*,.LENGTHUNIT.,$,.METRE."); - - int radianId = w.Add("IFCSIUNIT", "*,.PLANEANGLEUNIT.,$,.RADIAN."); - int dimExpId = w.Add("IFCDIMENSIONALEXPONENTS", "0,0,0,0,0,0,0"); - int angleMeasureId = w.Add("IFCMEASUREWITHUNIT", $"IFCPLANEANGLEMEASURE({DegreeInRadians}),{StepWriter.Ref(radianId)}"); - int degreeUnitId = w.Add("IFCCONVERSIONBASEDUNIT", $"{StepWriter.Ref(dimExpId)},.PLANEANGLEUNIT.,'DEGREE',{StepWriter.Ref(angleMeasureId)}"); + int lengthUnitId = WriteLengthUnit(w, LengthUnit); + int angleUnitId = WritePlaneAngleUnit(w, AngleUnit); int areaUnitId = w.Add("IFCSIUNIT", "*,.AREAUNIT.,$,.SQUARE_METRE."); int volumeUnitId = w.Add("IFCSIUNIT", "*,.VOLUMEUNIT.,$,.CUBIC_METRE."); int unitAssignmentId = w.Add("IFCUNITASSIGNMENT", - StepWriter.List(StepWriter.Ref(lengthUnitId), StepWriter.Ref(degreeUnitId), StepWriter.Ref(areaUnitId), StepWriter.Ref(volumeUnitId))); + StepWriter.List(StepWriter.Ref(lengthUnitId), StepWriter.Ref(angleUnitId), StepWriter.Ref(areaUnitId), StepWriter.Ref(volumeUnitId))); int originPointId = w.Add("IFCCARTESIANPOINT", StepWriter.List(StepWriter.Real(0), StepWriter.Real(0), StepWriter.Real(0))); int axisZId = w.Add("IFCDIRECTION", StepWriter.List(StepWriter.Real(0), StepWriter.Real(0), StepWriter.Real(1))); @@ -1068,6 +1062,7 @@ public void Save(TextWriter writer, string fileName = "model.ifc") } // 5D Cost Schedules & Cost Items (IFCCOSTSCHEDULE, IFCCOSTITEM, IFCAPPLIEDVALUE, IFCRELASSIGNSTOCONTROL, IFCRELNESTING) + int? costMetreId = LengthUnit == IfcLengthUnit.Metre ? lengthUnitId : null; foreach (var cs in CostSchedules) { string csGuid = cs.GlobalId ?? IfcGuid.NewGuid(); @@ -1112,7 +1107,10 @@ public void Save(TextWriter writer, string fileName = "model.ifc") "m" or "lm" => "IFCQUANTITYLENGTH", _ => "IFCQUANTITYCOUNT" }; - int qId = w.Add(qtyType, $"{StepWriter.Str("Quantity")},{StepWriter.Str(item.UnitBasis)},$,{StepWriter.Real(item.Quantity.Value)},$"); + string unit = qtyType == "IFCQUANTITYLENGTH" + ? StepWriter.Ref(costMetreId ??= WriteLengthUnit(w, IfcLengthUnit.Metre)) : "$"; + string formula = Schema == IfcSchema.Ifc4 ? ",$" : ""; + int qId = w.Add(qtyType, $"{StepWriter.Str("Quantity")},{StepWriter.Str(item.UnitBasis)},{unit},{StepWriter.Real(item.Quantity.Value)}{formula}"); qtyValIds.Add(qId); } @@ -1353,7 +1351,7 @@ public void Save(TextWriter writer, string fileName = "model.ifc") w.WriteTo(writer, fileName, schemaStr, viewDef, Application, Organization); } - private static void WritePropertyAndQuantitySets(StepWriter w, IfcElement element, int entityId, int ownerHistoryId) + private void WritePropertyAndQuantitySets(StepWriter w, IfcElement element, int entityId, int ownerHistoryId) { // Property sets if (element.PropertySets.Count > 0) @@ -1387,6 +1385,7 @@ private static void WritePropertyAndQuantitySets(StepWriter w, IfcElement elemen // Quantity sets if (element.QuantitySets.Count > 0) { + string formula = Schema == IfcSchema.Ifc4 ? ",$" : ""; foreach (var qset in element.QuantitySets) { var qIds = new List(); @@ -1394,8 +1393,8 @@ private static void WritePropertyAndQuantitySets(StepWriter w, IfcElement elemen { int qId = q switch { - IfcQuantityLength ql => w.Add("IFCQUANTITYLENGTH", - $"{StepWriter.Str(ql.Name)},{StepWriter.Str(ql.Description)},$,{StepWriter.Real(ql.LengthValue)}"), + IfcQuantityLength ql => w.Add("IFCQUANTITYLENGTH", + $"{StepWriter.Str(ql.Name)},{StepWriter.Str(ql.Description)},$,{StepWriter.Real(ql.LengthValue)}{formula}"), IfcQuantityArea qa => w.Add("IFCQUANTITYAREA", $"{StepWriter.Str(qa.Name)},{StepWriter.Str(qa.Description)},$,{StepWriter.Real(qa.AreaValue)}"), IfcQuantityVolume qv => w.Add("IFCQUANTITYVOLUME", @@ -1422,7 +1421,10 @@ private static void WritePropertyAndQuantitySets(StepWriter w, IfcElement elemen } /// Parses an existing IFC STEP file (.ifc or .ifczip) from disk into a structured model. - public static IfcModel Open(string path) + public static IfcModel Open(string path) => Open(path, options: null); + + /// Parses an IFC file from disk with the specified read options. + public static IfcModel Open(string path, IfcReadOptions? options) { ArgumentNullException.ThrowIfNull(path); if (path.EndsWith(".ifczip", StringComparison.OrdinalIgnoreCase)) @@ -1433,24 +1435,30 @@ public static IfcModel Open(string path) ?? throw new InvalidDataException("The .ifczip archive does not contain an .ifc file."); using var stream = entry.Open(); using var reader = new StreamReader(stream, Encoding.UTF8); - return Open(reader, Path.GetFileNameWithoutExtension(path)); + return Open(reader, Path.GetFileNameWithoutExtension(path), options); } using var fileStream = File.OpenRead(path); using var fileReader = new StreamReader(fileStream, Encoding.UTF8); - return Open(fileReader, Path.GetFileNameWithoutExtension(path)); + return Open(fileReader, Path.GetFileNameWithoutExtension(path), options); } /// Parses an existing IFC STEP physical file or stream into a structured model. - public static IfcModel Open(Stream stream, string? modelName = null) + public static IfcModel Open(Stream stream, string? modelName = null) => Open(stream, modelName, options: null); + + /// Parses an IFC byte stream with the specified read options. + public static IfcModel Open(Stream stream, string? modelName, IfcReadOptions? options) { ArgumentNullException.ThrowIfNull(stream); using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 65536, leaveOpen: true); - return Open(reader, modelName); + return Open(reader, modelName, options); } /// Parses an existing IFC STEP stream into a structured model with storeys, elements, properties, and meshes. - public static IfcModel Open(TextReader reader, string? modelName = null) + public static IfcModel Open(TextReader reader, string? modelName = null) => Open(reader, modelName, options: null); + + /// Parses an IFC text stream with the specified read options. + public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions? options) { ArgumentNullException.ThrowIfNull(reader); @@ -1480,7 +1488,8 @@ public static IfcModel Open(TextReader reader, string? modelName = null) // 1b. Units: geometry is kept in model length units. A unit without an IfcLengthUnit // counterpart (e.g. centimetres) is converted to metres while reading. - double? fileMetresPerUnit = ParseLengthUnit(step, projectEntity); + var assignment = step.Find(projectEntity?.GetRef(8)) ?? step.OfType("IFCUNITASSIGNMENT").FirstOrDefault(); + double? fileMetresPerUnit = ParseProjectUnitFactor(step, assignment, ".LENGTHUNIT."); double geometryScale = 1.0; if (fileMetresPerUnit.HasValue) { @@ -1488,6 +1497,12 @@ public static IfcModel Open(TextReader reader, string? modelName = null) model.LengthUnit = knownUnit ?? IfcLengthUnit.Metre; if (knownUnit is null) geometryScale = fileMetresPerUnit.Value; } + double radiansPerAngleUnit = ParseProjectUnitFactor(step, assignment, ".PLANEANGLEUNIT.") ?? 1.0; + const double radiansPerDegree = Math.PI / 180.0; + model.AngleUnit = Math.Abs(radiansPerAngleUnit - radiansPerDegree) <= radiansPerDegree * 1e-6 + ? IfcPlaneAngleUnit.Degree : IfcPlaneAngleUnit.Radian; + if (options?.LegacyIfcIoRevolvedAnglesInRadians == true) + radiansPerAngleUnit = 1.0; // 2. Parse Storeys var storeyMap = new Dictionary(); @@ -1613,6 +1628,11 @@ public static IfcModel Open(TextReader reader, string? modelName = null) if (qEnt.Type.Equals("IFCQUANTITYLENGTH", StringComparison.OrdinalIgnoreCase)) { + double? metresPerQuantityUnit = qEnt.GetRef(2) is int unitId + ? PositiveUnitFactor(step, step.Find(unitId), ".LENGTHUNIT.") + : fileMetresPerUnit; + if (metresPerQuantityUnit is double metres) + val *= metres / model.LengthUnit.MetresPerUnit(); qset.AddLength(qName, val, qDesc); } else if (qEnt.Type.Equals("IFCQUANTITYAREA", StringComparison.OrdinalIgnoreCase)) @@ -1675,6 +1695,7 @@ public static IfcModel Open(TextReader reader, string? modelName = null) step, geomToMaterialMap, IfcTransform.Scale(geometryScale).Multiply(ParseWorldCoordinateSystem(step)), + radiansPerAngleUnit, keepParametric: geometryScale == 1.0); var defaultStorey = model.Storeys[0]; var allElementsMap = new Dictionary(); @@ -2616,17 +2637,23 @@ private int WriteRevolvedAreaSolid(StepWriter w, IfcRevolvedAreaSolid solid) int axisDirId = w.Add("IFCDIRECTION", StepWriter.List(StepWriter.Real(solid.Axis.Axis.X), StepWriter.Real(solid.Axis.Axis.Y), StepWriter.Real(solid.Axis.Axis.Z))); int axisPlacementId = w.Add("IFCAXIS1PLACEMENT", $"{StepWriter.Ref(axisLocPtId)},{StepWriter.Ref(axisDirId)}"); - return w.Add("IFCREVOLVEDAREASOLID", $"{StepWriter.Ref(profileId)},{StepWriter.Ref(solidPlacementId)},{StepWriter.Ref(axisPlacementId)},{StepWriter.Real(solid.Angle)}"); + double angle = AngleUnit == IfcPlaneAngleUnit.Degree ? solid.Angle * (180.0 / Math.PI) : solid.Angle; + string angleText = StepWriter.Real(angle); + if (angle > 0 && angleText == "0.") + angleText = angle.ToString("0.0##############E+0", CultureInfo.InvariantCulture); + return w.Add("IFCREVOLVEDAREASOLID", $"{StepWriter.Ref(profileId)},{StepWriter.Ref(solidPlacementId)},{StepWriter.Ref(axisPlacementId)},{angleText}"); } /// State shared while reading product geometry: caches for placements and mapped representations. - private sealed class GeometryReadContext(StepFile step, Dictionary geomToMaterialMap, IfcTransform root, bool keepParametric) + private sealed class GeometryReadContext( + StepFile step, Dictionary geomToMaterialMap, IfcTransform root, double radiansPerAngleUnit, bool keepParametric) { public StepFile Step { get; } = step; public Dictionary GeomToMaterialMap { get; } = geomToMaterialMap; /// Unit scale applied after the world coordinate system of the model context. public IfcTransform Root { get; } = root; + public double RadiansPerAngleUnit { get; } = radiansPerAngleUnit; /// False when geometry is rescaled to metres: parametric solids stay in file units and would disagree with LengthUnit. public bool KeepParametric { get; } = keepParametric; @@ -2770,7 +2797,7 @@ public void ChargeVertices(int count) if (mesh is not null) return mesh; // C/D. IFCEXTRUDEDAREASOLID / IFCREVOLVEDAREASOLID - var swept = ParseSweptSolid(step, itemEnt, meshName, out var extruded, out var revolved, out _); + var swept = ParseSweptSolid(step, itemEnt, meshName, ctx.RadiansPerAngleUnit, out var extruded, out var revolved, out _); if (swept is not null) { parametric = new ParametricBody(extruded, revolved, null); @@ -2781,7 +2808,7 @@ public void ChargeVertices(int count) if (itemEnt.Type.Equals("IFCBOOLEANRESULT", StringComparison.OrdinalIgnoreCase) || itemEnt.Type.Equals("IFCBOOLEANCLIPPINGRESULT", StringComparison.OrdinalIgnoreCase)) { - var boolRes = ParseBooleanResult(step, itemEnt); + var boolRes = ParseBooleanResult(step, itemEnt, ctx.RadiansPerAngleUnit); if (boolRes is null) return null; parametric = new ParametricBody(null, null, boolRes); return boolRes.ToMesh(meshName); @@ -2809,6 +2836,7 @@ public void ChargeVertices(int count) /// The STEP file that holds the solid and the entities it references. /// The IfcExtrudedAreaSolid or IfcRevolvedAreaSolid entity. /// The name given to the returned mesh. + /// Conversion from project plane angle units to radians. /// The parametric extrusion, or null when the entity is not an extrusion or cannot be read. /// The parametric revolution, or null when the entity is not a revolution or cannot be read. /// True when Position or the profile Position rotates, so the parametric form does not describe the mesh. @@ -2816,6 +2844,7 @@ public void ChargeVertices(int count) StepFile step, StepEntity ent, string meshName, + double radiansPerAngleUnit, out IfcExtrudedAreaSolid? extruded, out IfcRevolvedAreaSolid? revolved, out bool fullPlacement) @@ -2851,8 +2880,7 @@ public void ChargeVertices(int count) return position.Multiply(shear).Multiply(profileRotation).ApplyTo(local); } - // Angle is read as radians, matching what IfcModel writes. - double angle = ent.GetReal(3) ?? (2.0 * Math.PI); + double angle = ent.GetReal(3) is double fileAngle ? fileAngle * radiansPerAngleUnit : 2.0 * Math.PI; var axis = ParseAxis1Placement(step, ent.GetRef(2)); revolved = new IfcRevolvedAreaSolid(profile, angle, position.Origin, axis); if (!fullPlacement) return revolved.ToMesh(16, 24, meshName); @@ -3035,26 +3063,56 @@ double Component(int i) => return new IfcVector3(Component(0), Component(1), Component(2)); } - /// - /// Metres per length unit from the project's IfcUnitAssignment (SI or conversion-based unit). - /// Null when absent or unrecognised: LengthUnit then keeps its default, as before. - /// - private static double? ParseLengthUnit(StepFile step, StepEntity? project) + private static int WriteLengthUnit(StepWriter w, IfcLengthUnit unit) => unit switch + { + IfcLengthUnit.Millimetre => w.Add("IFCSIUNIT", "*,.LENGTHUNIT.,.MILLI.,.METRE."), + IfcLengthUnit.Metre => w.Add("IFCSIUNIT", "*,.LENGTHUNIT.,$,.METRE."), + IfcLengthUnit.Foot or IfcLengthUnit.Inch => WriteImperialLengthUnit(w, unit), + _ => throw new ArgumentOutOfRangeException(nameof(unit), unit, "Unsupported IFC length unit."), + }; + + private static int WriteImperialLengthUnit(StepWriter w, IfcLengthUnit unit) + { + int metre = w.Add("IFCSIUNIT", "*,.LENGTHUNIT.,$,.METRE."); + int dimensions = w.Add("IFCDIMENSIONALEXPONENTS", "1,0,0,0,0,0,0"); + int factor = w.Add("IFCMEASUREWITHUNIT", $"IFCLENGTHMEASURE({StepWriter.Real(unit.MetresPerUnit())}),{StepWriter.Ref(metre)}"); + string name = unit == IfcLengthUnit.Foot ? "FOOT" : "INCH"; + return w.Add("IFCCONVERSIONBASEDUNIT", $"{StepWriter.Ref(dimensions)},.LENGTHUNIT.,'{name}',{StepWriter.Ref(factor)}"); + } + + private static int WritePlaneAngleUnit(StepWriter w, IfcPlaneAngleUnit unit) + { + int radianId = w.Add("IFCSIUNIT", "*,.PLANEANGLEUNIT.,$,.RADIAN."); + if (unit == IfcPlaneAngleUnit.Radian) return radianId; + if (unit != IfcPlaneAngleUnit.Degree) + throw new ArgumentOutOfRangeException(nameof(unit), unit, "Unsupported IFC plane angle unit."); + int dimensions = w.Add("IFCDIMENSIONALEXPONENTS", "0,0,0,0,0,0,0"); + int factor = w.Add("IFCMEASUREWITHUNIT", $"IFCPLANEANGLEMEASURE({DegreeInRadians}),{StepWriter.Ref(radianId)}"); + return w.Add("IFCCONVERSIONBASEDUNIT", $"{StepWriter.Ref(dimensions)},.PLANEANGLEUNIT.,'DEGREE',{StepWriter.Ref(factor)}"); + } + + /// Metres or radians per project length or plane angle unit. Null when absent or unrecognised. + private static double? ParseProjectUnitFactor(StepFile step, StepEntity? assignment, string unitType) { - var assignment = step.Find(project?.GetRef(8)) ?? step.OfType("IFCUNITASSIGNMENT").FirstOrDefault(); var unit = assignment?.GetRefList(0) .Select(id => step.Find(id)) - .FirstOrDefault(u => string.Equals(u?.GetRaw(1), ".LENGTHUNIT.", StringComparison.OrdinalIgnoreCase)); - return ParseUnitFactor(step, unit, 0); + .FirstOrDefault(u => string.Equals(u?.GetRaw(1), unitType, StringComparison.OrdinalIgnoreCase)); + return PositiveUnitFactor(step, unit, unitType); } + private static double? PositiveUnitFactor(StepFile step, StepEntity? unit, string unitType) => + ParseUnitFactor(step, unit, unitType, 0) is double value && double.IsFinite(value) && value > 0 ? value : null; + /// Factor of a named unit relative to its SI base unit. - private static double? ParseUnitFactor(StepFile step, StepEntity? unit, int depth) + private static double? ParseUnitFactor(StepFile step, StepEntity? unit, string unitType, int depth) { - if (unit is null || depth > 8) return null; + if (unit is null || depth > 8 || !string.Equals(unit.GetRaw(1), unitType, StringComparison.OrdinalIgnoreCase)) + return null; if (unit.Type.Equals("IFCSIUNIT", StringComparison.OrdinalIgnoreCase)) { + string baseUnit = unitType == ".LENGTHUNIT." ? ".METRE." : ".RADIAN."; + if (!string.Equals(unit.GetRaw(3), baseUnit, StringComparison.OrdinalIgnoreCase)) return null; return unit.GetRaw(2)?.Trim('.').ToUpperInvariant() switch { null => 1.0, @@ -3078,12 +3136,14 @@ double Component(int i) => }; } - if (unit.Type.StartsWith("IFCCONVERSIONBASEDUNIT", StringComparison.OrdinalIgnoreCase)) + if (unit.Type.Equals("IFCCONVERSIONBASEDUNIT", StringComparison.OrdinalIgnoreCase) + || unit.Type.Equals("IFCCONVERSIONBASEDUNITWITHOFFSET", StringComparison.OrdinalIgnoreCase) && unit.GetReal(4) == 0) { var measure = step.Find(unit.GetRef(3)); - if (measure is null) return null; - if (!double.TryParse(ExtractNominalValue(measure.GetRaw(0)), NumberStyles.Float, CultureInfo.InvariantCulture, out double value)) return null; - return value * ParseUnitFactor(step, step.Find(measure.GetRef(1)), depth + 1); + if (measure is null || !measure.Type.Equals("IFCMEASUREWITHUNIT", StringComparison.OrdinalIgnoreCase)) return null; + if (!double.TryParse(ExtractNominalValue(measure.GetRaw(0)), NumberStyles.Float, CultureInfo.InvariantCulture, out double value) + || !double.IsFinite(value) || value <= 0) return null; + return value * ParseUnitFactor(step, step.Find(measure.GetRef(1)), unitType, depth + 1); } return null; @@ -3215,7 +3275,7 @@ double Component(int i) => return null; } - private static IfcBooleanResult? ParseBooleanResult(StepFile step, StepEntity itemEnt) + private static IfcBooleanResult? ParseBooleanResult(StepFile step, StepEntity itemEnt, double radiansPerAngleUnit) { string? opStr = itemEnt.GetRaw(0); var op = IfcBooleanOperator.Difference; @@ -3234,7 +3294,8 @@ double Component(int i) => var firstEnt = step.Find(firstOpId.Value); if (firstEnt is not null) { - var sweptMesh = ParseSweptSolid(step, firstEnt, "BooleanOperand", out var extruded, out var revolved, out bool fullPlacement); + var sweptMesh = ParseSweptSolid(step, firstEnt, "BooleanOperand", radiansPerAngleUnit, + out var extruded, out var revolved, out bool fullPlacement); if (sweptMesh is null) { boolResult.FirstMesh = ParseMeshEntity(step, firstEnt); diff --git a/src/IfcIO/IfcReadOptions.cs b/src/IfcIO/IfcReadOptions.cs new file mode 100644 index 0000000..558725d --- /dev/null +++ b/src/IfcIO/IfcReadOptions.cs @@ -0,0 +1,11 @@ +namespace IfcIO; + +/// Options for reading IFC models. +public sealed class IfcReadOptions +{ + /// + /// Treat revolved-solid sweep values as radians in older IfcIO files that incorrectly declared degrees. + /// Use only when the source file is known to have been written by the affected exporter. + /// + public bool LegacyIfcIoRevolvedAnglesInRadians { get; init; } +} diff --git a/tests/IfcIO.Tests/IfcModelTests.cs b/tests/IfcIO.Tests/IfcModelTests.cs index 9ace43f..9a3ce3f 100644 --- a/tests/IfcIO.Tests/IfcModelTests.cs +++ b/tests/IfcIO.Tests/IfcModelTests.cs @@ -190,6 +190,56 @@ public void IfcModel_TypeProducts_EmitsTypeDefinitionsAndRelation() Assert.Contains("W200_Concrete", ifc); } + [Fact] + public void IfcModel_Open_NormalizesLengthQuantitiesToTheModelLengthUnit() + { + const string input = """ + ISO-10303-21; + HEADER; FILE_SCHEMA(('IFC4')); ENDSEC; + DATA; + #1=IFCPROJECT('01vctVUKr0kugbFTf53O9L',$,'Units',$,$,$,$,(),#2); + #2=IFCUNITASSIGNMENT((#3)); + #3=IFCSIUNIT(*,.LENGTHUNIT.,.CENTI.,.METRE.); + #4=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.); + #5=IFCDIMENSIONALEXPONENTS(1,0,0,0,0,0,0); + #6=IFCMEASUREWITHUNIT(IFCLENGTHMEASURE(0.3048),#4); + #7=IFCCONVERSIONBASEDUNITWITHOFFSET(#5,.LENGTHUNIT.,'FOOT',#6,0.); + #10=IFCWALL('10vctVUKr0kugbFTf53O9L',$,'Wall',$,$,$,$,$,.STANDARD.); + #11=IFCQUANTITYLENGTH('Project length',$,$,250.,$); + #12=IFCQUANTITYLENGTH('Explicit units',$,#7,3.,$); + #13=IFCELEMENTQUANTITY('13vctVUKr0kugbFTf53O9L',$,'Dimensions',$,$,(#11,#12)); + #14=IFCRELDEFINESBYPROPERTIES('14vctVUKr0kugbFTf53O9L',$,$,$,(#10),#13); + ENDSEC; + END-ISO-10303-21; + """; + + var model = IfcModel.Open(new StringReader(input)); + Assert.Equal(IfcLengthUnit.Metre, model.LengthUnit); + var reopened = IfcModel.Open(new StringReader(model.ToStepString())); + var quantities = Assert.Single(Assert.Single(reopened.AllElements).QuantitySets).Quantities; + Assert.Collection(quantities, + q => Assert.Equal(2.5, Assert.IsType(q).LengthValue), + q => Assert.Equal(0.9144, Assert.IsType(q).LengthValue, 9)); + } + + [Fact] + public void IfcModel_Save_MetreBasedCostQuantityHasExplicitUnitInImperialProject() + { + var model = IfcModel.Create("Imperial cost plan", IfcSchema.Ifc4); + model.LengthUnit = IfcLengthUnit.Foot; + model.AddCostSchedule("Materials").AddCostItem("Pipe", unitRate: 15, quantity: 10, unitBasis: "m"); + + var step = StepReader.Read(new StringReader(model.ToStepString())); + + var quantity = Assert.Single(step.OfType("IFCQUANTITYLENGTH")); + Assert.Equal(10.0, quantity.GetReal(3)); + var unit = step.Find(quantity.GetRef(2)); + Assert.NotNull(unit); + Assert.Equal("IFCSIUNIT", unit.Type); + Assert.Equal(".METRE.", unit.GetRaw(3)); + Assert.Null(unit.GetRaw(2)); + } + [Fact] public void IfcModel_Open_ImportsOnlySupportedProductOccurrences() { diff --git a/tests/IfcIO.Tests/RevolvedSolidTests.cs b/tests/IfcIO.Tests/RevolvedSolidTests.cs index 7e6ff23..edbcbfe 100644 --- a/tests/IfcIO.Tests/RevolvedSolidTests.cs +++ b/tests/IfcIO.Tests/RevolvedSolidTests.cs @@ -1,5 +1,7 @@ +using IfcIO.Core; using IfcIO.Geometry; using IfcIO.Model; +using IfcIO.Schema; using Xunit; namespace IfcIO.Tests; @@ -75,6 +77,113 @@ public void RevolvedSolid_StepRoundtrip_PreservesGeometryAndSolid() } } + [Theory] + [InlineData(IfcSchema.Ifc2x3, IfcLengthUnit.Foot, 0.3048, IfcPlaneAngleUnit.Degree)] + [InlineData(IfcSchema.Ifc2x3, IfcLengthUnit.Inch, 0.0254, IfcPlaneAngleUnit.Radian)] + [InlineData(IfcSchema.Ifc4, IfcLengthUnit.Foot, 0.3048, IfcPlaneAngleUnit.Radian)] + [InlineData(IfcSchema.Ifc4, IfcLengthUnit.Inch, 0.0254, IfcPlaneAngleUnit.Degree)] + public void SaveAndOpen_PreservesImperialLengthsAndUsesTheDeclaredAngleUnit( + IfcSchema schema, IfcLengthUnit length, double metresPerUnit, IfcPlaneAngleUnit angle) + { + var model = IfcModel.Create("Imperial", schema); + model.LengthUnit = length; + model.AngleUnit = angle; + var storey = model.AddStorey("Raised floor", 12); + var profile = new IfcCircleProfileDef(radius: 2, position: new IfcVector3(12, 0, 0)); + var element = model.AddRevolvedSolid("Bend", profile, angle: Math.PI / 2, + axis: new IfcAxis1Placement(IfcVector3.Zero, IfcVector3.UnitY), + storey: storey, ifcType: "IFCPIPEFITTING"); + + string text = model.ToStepString(); + var step = StepReader.Read(new StringReader(text)); + var assignment = Assert.Single(step.OfType("IFCUNITASSIGNMENT")); + var lengthUnit = Assert.Single(assignment.GetRefList(0).Select(id => step.Find(id)!), + unit => unit.GetRaw(1) == ".LENGTHUNIT."); + Assert.Equal("IFCCONVERSIONBASEDUNIT", lengthUnit.Type); + Assert.Equal(length == IfcLengthUnit.Foot ? "FOOT" : "INCH", lengthUnit.GetString(2)); + var factor = step.Find(lengthUnit.GetRef(3))!; + Assert.Equal(FormattableString.Invariant($"IFCLENGTHMEASURE({metresPerUnit})"), factor.GetRaw(0)); + Assert.Equal(".METRE.", step.Find(factor.GetRef(1))!.GetRaw(3)); + + var angleUnit = Assert.Single(assignment.GetRefList(0).Select(id => step.Find(id)!), + unit => unit.GetRaw(1) == ".PLANEANGLEUNIT."); + if (angle == IfcPlaneAngleUnit.Degree) + { + Assert.Equal("IFCCONVERSIONBASEDUNIT", angleUnit.Type); + Assert.Equal("DEGREE", angleUnit.GetString(2)); + } + else + { + Assert.Equal("IFCSIUNIT", angleUnit.Type); + Assert.Equal(".RADIAN.", angleUnit.GetRaw(3)); + } + var revolution = Assert.Single(step.OfType("IFCREVOLVEDAREASOLID")); + Assert.Equal(angle == IfcPlaneAngleUnit.Degree ? 90.0 : Math.PI / 2, revolution.GetReal(3)!.Value, 5); + + var opened = IfcModel.Open(new StringReader(text)); + Assert.Equal(length, opened.LengthUnit); + Assert.Equal(angle, opened.AngleUnit); + Assert.Equal(12.0, Assert.Single(opened.Storeys).Elevation); + var reopened = Assert.Single(opened.AllElements); + Assert.Equal(Math.PI / 2, reopened.RevolvedSolid!.Angle, 5); + Assert.Equal(2.0, Assert.IsType(reopened.RevolvedSolid.Profile).Radius); + var originalBox = element.GetEffectiveMesh()!.BoundingBox; + var reopenedBox = reopened.GetEffectiveMesh()!.BoundingBox; + Assert.Equal(originalBox.Min.X, reopenedBox.Min.X, 4); + Assert.Equal(originalBox.Max.Z, reopenedBox.Max.Z, 4); + } + + [Fact] + public void LegacyMislabeledAngle_RequiresExplicitOptInAndSavesWithCorrectUnits() + { + const string legacy = """ + ISO-10303-21; + HEADER; FILE_SCHEMA(('IFC4')); ENDSEC; + DATA; + #1=IFCPROJECT('01vctVUKr0kugbFTf53O9L',$,'Legacy',$,$,$,$,(),#2); + #2=IFCUNITASSIGNMENT((#3,#5)); + #3=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.); + #4=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.); + #5=IFCCONVERSIONBASEDUNIT(#6,.PLANEANGLEUNIT.,'DEGREE',#7); + #6=IFCDIMENSIONALEXPONENTS(0,0,0,0,0,0,0); + #7=IFCMEASUREWITHUNIT(IFCPLANEANGLEMEASURE(0.017453293),#4); + #8=IFCCARTESIANPOINT((0.,0.,0.)); + #9=IFCDIRECTION((0.,1.,0.)); + #10=IFCAXIS1PLACEMENT(#8,#9); + #11=IFCRECTANGLEPROFILEDEF(.AREA.,'Profile',$,2.,3.); + #12=IFCREVOLVEDAREASOLID(#11,$,#10,1.570796); + #13=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#12)); + #14=IFCPRODUCTDEFINITIONSHAPE($,$,(#13)); + #15=IFCBUILDINGELEMENTPROXY('02vctVUKr0kugbFTf53O9L',$,'Sweep',$,$,$,#14,$,.NOTDEFINED.); + ENDSEC; + END-ISO-10303-21; + """; + + var standardRead = IfcModel.Open(new StringReader(legacy)); + Assert.Equal(IfcPlaneAngleUnit.Degree, standardRead.AngleUnit); + Assert.Equal(1.570796 * 0.017453293, Assert.Single(standardRead.AllElements).RevolvedSolid!.Angle, 12); + + var repaired = IfcModel.Open(new StringReader(legacy), modelName: null, + options: new IfcReadOptions { LegacyIfcIoRevolvedAnglesInRadians = true }); + Assert.Equal(1.570796, Assert.Single(repaired.AllElements).RevolvedSolid!.Angle); + + var reopened = IfcModel.Open(new StringReader(repaired.ToStepString())); + Assert.Equal(IfcPlaneAngleUnit.Degree, reopened.AngleUnit); + Assert.Equal(1.570796, Assert.Single(reopened.AllElements).RevolvedSolid!.Angle, 7); + } + + [Fact] + public void Save_PreservesSmallPositiveRevolutionAngles() + { + var model = IfcModel.Create("Small angle", IfcSchema.Ifc4); + model.AngleUnit = IfcPlaneAngleUnit.Radian; + model.AddRevolvedSolid("Short sweep", new IfcCircleProfileDef(2), angle: 1e-8); + + var step = StepReader.Read(new StringReader(model.ToStepString())); + + Assert.Equal("1.0E-8", Assert.Single(step.OfType("IFCREVOLVEDAREASOLID")).GetRaw(3)); + } + [Fact] public void Validator_RevolvedAngleOutOfRange_ReportsError() {