From 62d9bddec593371e6a342c3944d8eede62f28704 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:29:24 +0300 Subject: [PATCH] Apply model length units to measurements and camera exports --- docs/getting-started.md | 4 +- docs/public-api.md | 11 ++ src/NwcIO.Cli/Program.cs | 1 + .../Clash/NwcClashBcfExporter.cs | 31 +-- .../Compatibility/Clash/NwcClashDetector.cs | 5 +- .../Compatibility/Clash/NwcClashMatrix.cs | 6 +- .../Compatibility/Clash/NwcClashTypes.cs | 2 + src/NwcIO/Compatibility/Diff/NwcDiffEngine.cs | 6 + src/NwcIO/Compatibility/Diff/NwcDiffTypes.cs | 4 +- src/NwcIO/Compatibility/Export/BcfExporter.cs | 32 ++-- .../Compatibility/Grids/NwcGridSystem.cs | 39 +++- .../Compatibility/Measure/NwcMeasureEngine.cs | 41 +++- .../NwcAssembly.Compatibility.cs | 17 +- .../Compatibility/NwcDocument.AsyncExports.cs | 10 +- .../NwcDocument.Compatibility.cs | 16 +- .../Viewer/NwcHtmlViewerExporter.cs | 20 +- src/NwcIO/Model/NwcAssembly.cs | 12 +- tests/NwcIO.Tests/GridSystemTests.cs | 6 +- tests/NwcIO.Tests/NwcLengthUnitTests.cs | 176 +++++++++++++++++- 19 files changed, 354 insertions(+), 85 deletions(-) diff --git a/docs/getting-started.md b/docs/getting-started.md index f692007..2cf0cb0 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -99,8 +99,8 @@ matrix.PopulateStandardMatrix(defaultTolerance: 0.002); // Configure tolerance per cell in document units; PopulateStandardMatrix fills cells in // discipline order: [0]=Architecture-Structure, [1]=Architecture-MEP, [2]=Structure-MEP -matrix.Cells.Single(c => c.DisciplineA == "Architecture" && c.DisciplineB == "Structure").Tolerance = 0.005; // 5 document units -matrix.Cells.Single(c => c.DisciplineA == "Structure" && c.DisciplineB == "MEP").Tolerance = 0.010; // 10 document units +matrix.Cells.Single(c => c.DisciplineA == "Architecture" && c.DisciplineB == "Structure").Tolerance = 0.005; +matrix.Cells.Single(c => c.DisciplineA == "Structure" && c.DisciplineB == "MEP").Tolerance = 0.010; // Execute the entire coordination matrix matrix.Execute(assembly); diff --git a/docs/public-api.md b/docs/public-api.md index 3dfb7ab..e922bb6 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -58,6 +58,17 @@ synchronous counterparts. Directory discovery and reference resolution use synch The `load-models` phase reports each folder model, or the primary NWF and each of its reference entries, including missing, duplicate and unsupported references. +`NwcDocument.LengthUnit` and `MetresPerUnit` describe the original coordinates. Set +`NwcReaderOptions.LengthUnit` to override inference. Clash detection, proximity grouping, +clash matrix cells and revision diff all interpret tolerances in the input coordinate units. +Grid locations and length measurements keep these values and display the corresponding unit +symbol. The measurement overloads accept a unit when their input is a standalone point or mesh. +IFC converts known coordinates to its selected output unit. BCF camera positions and orthogonal +view scales are exported in metres, using the original coordinates when the unit is unknown. +Viewpoint XML labels default to the document's unit when known and accept an explicit label. +`NwcAssembly.HasMixedLengthUnits` and the `MixedLengthUnits` diagnostic report mixed units. +Assembly geometry retains its original coordinates. + ## Coordination & Clash Detection (`NwcIO.Model.Clash`) | Type | Description | diff --git a/src/NwcIO.Cli/Program.cs b/src/NwcIO.Cli/Program.cs index 83813d0..f7b1385 100644 --- a/src/NwcIO.Cli/Program.cs +++ b/src/NwcIO.Cli/Program.cs @@ -45,6 +45,7 @@ Reads Autodesk Navisworks files (.nwc, .nwd, .nwf) or assemblies of models --clash-xml Run clash detection and export Navisworks Clash Report XML (.xml) --clash-bcf Run clash detection and export buildingSMART BCF 2.1 archive (.bcfzip) --clash-matrix Execute multi-discipline coordination matrix and export JSON report + Matrix tolerances are in document units --clash-matrix-md Export clash matrix coordination report as Markdown table --clash-matrix-bcf Export clash matrix conflicts to buildingSMART BCF 2.1 zip --clash-group Group clashes: proximity, element, grid, layer diff --git a/src/NwcIO/Compatibility/Clash/NwcClashBcfExporter.cs b/src/NwcIO/Compatibility/Clash/NwcClashBcfExporter.cs index b68566a..af6c4fc 100644 --- a/src/NwcIO/Compatibility/Clash/NwcClashBcfExporter.cs +++ b/src/NwcIO/Compatibility/Clash/NwcClashBcfExporter.cs @@ -67,7 +67,9 @@ public static void Write(Stream stream, NwcClashTest test, string projectName = /// /// Saves clash tests, including both standalone results and grouped clashes, to one BCF 2.1 archive file. /// - internal static void SaveTests(string path, IEnumerable tests, string projectName = "Navisworks Clash Coordination") + internal static void SaveTests( + string path, IEnumerable tests, string projectName = "Navisworks Clash Coordination", + NwcLengthUnit lengthUnit = NwcLengthUnit.Unknown) { ArgumentNullException.ThrowIfNull(path); ArgumentNullException.ThrowIfNull(tests); @@ -79,14 +81,16 @@ internal static void SaveTests(string path, IEnumerable tests, str } using var fs = File.Create(path); - WriteTests(fs, tests, projectName); + WriteTests(fs, tests, projectName, lengthUnit); } /// /// Writes clash tests, including both standalone results and grouped clashes, to one BCF 2.1 zip stream: /// a topic per clash group and a topic per clash that is in no group. /// - internal static void WriteTests(Stream stream, IEnumerable tests, string projectName = "Navisworks Clash Coordination") + internal static void WriteTests( + Stream stream, IEnumerable tests, string projectName = "Navisworks Clash Coordination", + NwcLengthUnit lengthUnit = NwcLengthUnit.Unknown) { ArgumentNullException.ThrowIfNull(stream); ArgumentNullException.ThrowIfNull(tests); @@ -98,11 +102,11 @@ internal static void WriteTests(Stream stream, IEnumerable tests, foreach (var test in tests) { - WriteTest(archive, test, projectName); + WriteTest(archive, test, projectName, lengthUnit); } } - private static void WriteTest(ZipArchive archive, NwcClashTest test, string projectName) + private static void WriteTest(ZipArchive archive, NwcClashTest test, string projectName, NwcLengthUnit lengthUnit) { // Export Clash Groups as unified topics foreach (var group in test.Groups) @@ -120,7 +124,7 @@ private static void WriteTest(ZipArchive archive, NwcClashTest test, string proj using (var s = vpEntry.Open()) using (var xml = XmlWriter.Create(s, Settings)) { - WriteGroupViewpointXml(xml, group); + WriteGroupViewpointXml(xml, group, lengthUnit); } } @@ -140,7 +144,7 @@ private static void WriteTest(ZipArchive archive, NwcClashTest test, string proj using (var s = vpEntry.Open()) using (var xml = XmlWriter.Create(s, Settings)) { - WriteViewpointXml(xml, clash); + WriteViewpointXml(xml, clash, lengthUnit); } } } @@ -259,7 +263,7 @@ private static void WriteMarkupXml(XmlWriter xml, NwcClashResult clash, string p xml.WriteEndDocument(); } - private static void WriteViewpointXml(XmlWriter xml, NwcClashResult clash) + private static void WriteViewpointXml(XmlWriter xml, NwcClashResult clash, NwcLengthUnit lengthUnit = NwcLengthUnit.Unknown) { xml.WriteStartDocument(); xml.WriteStartElement("VisualizationInfo"); @@ -290,7 +294,8 @@ private static void WriteViewpointXml(XmlWriter xml, NwcClashResult clash) // Camera positioning xml.WriteStartElement("PerspectiveCamera"); - var target = clash.ClashPoint; + double scale = clash.LengthUnit.GetMetresPerUnit() ?? lengthUnit.GetMetresPerUnit() ?? 1.0; + var target = clash.ClashPoint * scale; var offset = new Vector3d(5.0, -5.0, 3.5); var eye = target + offset; var dir = (target - eye).Normalize(); @@ -386,7 +391,7 @@ private static void WriteGroupMarkupXml(XmlWriter xml, NwcClashGroup group, stri xml.WriteEndDocument(); } - private static void WriteGroupViewpointXml(XmlWriter xml, NwcClashGroup group) + private static void WriteGroupViewpointXml(XmlWriter xml, NwcClashGroup group, NwcLengthUnit lengthUnit) { xml.WriteStartDocument(); xml.WriteStartElement("VisualizationInfo"); @@ -420,7 +425,11 @@ private static void WriteGroupViewpointXml(XmlWriter xml, NwcClashGroup group) // Camera positioning xml.WriteStartElement("PerspectiveCamera"); - var target = group.ClashPoint; + var units = group.Clashes.Select(clash => clash.LengthUnit).Distinct().Take(2).ToArray(); + double scale = units is [var unit] + ? unit.GetMetresPerUnit() ?? lengthUnit.GetMetresPerUnit() ?? 1.0 + : lengthUnit.GetMetresPerUnit() ?? 1.0; + var target = group.ClashPoint * scale; var offset = new Vector3d(8.0, -8.0, 5.0); var eye = target + offset; var dir = (target - eye).Normalize(); diff --git a/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs b/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs index b06aae9..2cee25a 100644 --- a/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs +++ b/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs @@ -78,7 +78,7 @@ public static NwcClashTest Run( } RunWithCancellation(test, itemsA.Count, progress, - () => RunCoreMultiModel(itemsA, itemsB, test, progress, cancellationToken), cancellationToken); + () => RunCoreMultiModel(itemsA, itemsB, test, assembly.CommonLengthUnit, progress, cancellationToken), cancellationToken); return test; } @@ -196,6 +196,7 @@ private static void RunCore( var result = new NwcClashResult(clashName, obj1, obj2, clashPoint, distance, NwcClashStatus.New) { + LengthUnit = document.LengthUnit, Description = test.TestType switch { NwcClashTestType.Clearance => $"Clearance between {item1Name} and {item2Name}", @@ -221,6 +222,7 @@ private static void RunCoreMultiModel( List<(NwcMesh Mesh, string ModelName, string? Layer, string ModelKey)> itemsA, List<(NwcMesh Mesh, string ModelName, string? Layer, string ModelKey)> itemsB, NwcClashTest test, + NwcLengthUnit lengthUnit, IProgress? progress, CancellationToken cancellationToken) { @@ -298,6 +300,7 @@ private static void RunCoreMultiModel( var result = new NwcClashResult(clashName, obj1, obj2, clashPoint, distance, NwcClashStatus.New) { + LengthUnit = lengthUnit, Description = test.TestType switch { NwcClashTestType.Clearance => $"Clearance between {itemA.ModelName} ({name1}) and {itemB.ModelName} ({name2})", diff --git a/src/NwcIO/Compatibility/Clash/NwcClashMatrix.cs b/src/NwcIO/Compatibility/Clash/NwcClashMatrix.cs index ea2862b..daba404 100644 --- a/src/NwcIO/Compatibility/Clash/NwcClashMatrix.cs +++ b/src/NwcIO/Compatibility/Clash/NwcClashMatrix.cs @@ -196,6 +196,7 @@ public void Run(NwcAssembly assembly) } var modelKeys = NwcElementGuid.ModelKeys(assembly.Models); + var lengthUnit = assembly.CommonLengthUnit; var keyByDocument = new Dictionary(ReferenceEqualityComparer.Instance); for (int i = 0; i < assembly.Models.Count; i++) { @@ -318,7 +319,10 @@ public void Run(NwcAssembly assembly) IfcGuid = NwcElementGuid.ForMesh(mB, keyByDocument[docB]), }; - var clash = new NwcClashResult($"Clash_{clashId++}", c1, c2, clashPoint, -penetration); + var clash = new NwcClashResult($"Clash_{clashId++}", c1, c2, clashPoint, -penetration) + { + LengthUnit = lengthUnit, + }; if (!test.Rules.Any(rule => rule.ShouldIgnore(clash))) { diff --git a/src/NwcIO/Compatibility/Clash/NwcClashTypes.cs b/src/NwcIO/Compatibility/Clash/NwcClashTypes.cs index 8d7162c..e6273c5 100644 --- a/src/NwcIO/Compatibility/Clash/NwcClashTypes.cs +++ b/src/NwcIO/Compatibility/Clash/NwcClashTypes.cs @@ -243,6 +243,8 @@ public sealed class NwcClashResult public NwcClashObject Item1 { get; set; } = new(); public NwcClashObject Item2 { get; set; } = new(); public Vector3d ClashPoint { get; set; } + internal NwcLengthUnit LengthUnit { get; init; } + public double Distance { get; set; } // Negative for hard clash penetration, positive for clearance public string? GridLocation { get; set; } public DateTimeOffset CreatedDate { get; set; } = DateTimeOffset.UtcNow; diff --git a/src/NwcIO/Compatibility/Diff/NwcDiffEngine.cs b/src/NwcIO/Compatibility/Diff/NwcDiffEngine.cs index dcb10f9..e627840 100644 --- a/src/NwcIO/Compatibility/Diff/NwcDiffEngine.cs +++ b/src/NwcIO/Compatibility/Diff/NwcDiffEngine.cs @@ -17,6 +17,7 @@ private sealed class DiffItem public Guid? ElementGuid { get; init; } public NwcNode? Node { get; init; } public NwcMesh? Mesh { get; init; } + public NwcLengthUnit LengthUnit { get; init; } public NwcTransform? Transform { get; init; } public IReadOnlyList Properties { get; init; } = []; public BoundingBox3d WorldBounds { get; set; } = BoundingBox3d.Empty; @@ -119,6 +120,7 @@ private static void PerformDiff( ChangeKind = NwcChangeKind.Added, RevisionNode = rev.Node, RevisionMesh = rev.Mesh, + LengthUnit = rev.LengthUnit, }); } else @@ -181,6 +183,7 @@ private static void PerformDiff( RevisionNode = rev.Node, BaselineMesh = baseItem.Mesh, RevisionMesh = rev.Mesh, + LengthUnit = rev.Mesh is not null || baseItem.Mesh is null ? rev.LengthUnit : baseItem.LengthUnit, }; diff.PropertyChanges.AddRange(propChanges); @@ -211,6 +214,7 @@ private static void PerformDiff( ChangeKind = NwcChangeKind.Deleted, BaselineNode = b.Node, BaselineMesh = b.Mesh, + LengthUnit = b.LengthUnit, }); } } @@ -367,6 +371,7 @@ node.Mesh is not null || ElementGuid = node.ElementGuid, Node = node, Mesh = node.Mesh, + LengthUnit = doc.LengthUnit, Transform = node.Transform, Properties = node.Properties, WorldBounds = bounds, @@ -401,6 +406,7 @@ node.Mesh is not null || Name = name, ClassName = "MeshGeometry", Mesh = m, + LengthUnit = doc.LengthUnit, Transform = m.Transform, WorldBounds = m.GetWorldBoundingBox(), MatchKey = matchKey, diff --git a/src/NwcIO/Compatibility/Diff/NwcDiffTypes.cs b/src/NwcIO/Compatibility/Diff/NwcDiffTypes.cs index 8892eae..f5925bb 100644 --- a/src/NwcIO/Compatibility/Diff/NwcDiffTypes.cs +++ b/src/NwcIO/Compatibility/Diff/NwcDiffTypes.cs @@ -78,6 +78,8 @@ public sealed class NwcElementDiff public NwcMesh? RevisionMesh { get; init; } + internal NwcLengthUnit LengthUnit { get; init; } + /// /// Gets the best available 3D centroid for this element (from mesh or transform). /// @@ -358,7 +360,7 @@ void WriteTopic(NwcElementDiff item, string changePrefix, string priority) xml.WriteStartElement("VisualizationInfo"); xml.WriteAttributeString("Guid", vpGuid); - var center = item.Centroid; + var center = item.Centroid * (item.LengthUnit.GetMetresPerUnit() ?? 1.0); var eye = center + new Vector3d(5.0, -5.0, 4.0); var dir = (center - eye).Normalize(); diff --git a/src/NwcIO/Compatibility/Export/BcfExporter.cs b/src/NwcIO/Compatibility/Export/BcfExporter.cs index e3ed4bb..c44c37f 100644 --- a/src/NwcIO/Compatibility/Export/BcfExporter.cs +++ b/src/NwcIO/Compatibility/Export/BcfExporter.cs @@ -40,7 +40,8 @@ public static void WriteFile(IReadOnlyList clashes, string path, strin /// /// Writes the saved viewpoints list as a BCF 2.1 (.bcfzip) file to disk. /// - public static void WriteViewpointsFile(IReadOnlyList viewpoints, string path, string? assemblyName = null) + public static void WriteViewpointsFile( + IReadOnlyList viewpoints, string path, string? assemblyName = null, double metresPerUnit = 1.0) { ArgumentNullException.ThrowIfNull(viewpoints); ArgumentNullException.ThrowIfNull(path); @@ -52,7 +53,7 @@ public static void WriteViewpointsFile(IReadOnlyList viewpoin } using var fs = File.Create(path); - WriteViewpoints(viewpoints, fs, assemblyName); + WriteViewpoints(viewpoints, fs, assemblyName, metresPerUnit); } /// @@ -60,7 +61,7 @@ public static void WriteViewpointsFile(IReadOnlyList viewpoin /// public static void WriteViewpoints( IReadOnlyList viewpoints, Stream stream, string? assemblyName = null, - CancellationToken cancellationToken = default) + double metresPerUnit = 1.0, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(viewpoints); ArgumentNullException.ThrowIfNull(stream); @@ -97,7 +98,7 @@ public static void WriteViewpoints( using (var s = viewpointEntry.Open()) using (var xml = XmlWriter.Create(s, XmlSettings)) { - WriteCameraViewpointXml(xml, vp.Camera, viewpointGuid); + WriteCameraViewpointXml(xml, vp.Camera, viewpointGuid, metresPerUnit); } } } @@ -184,7 +185,7 @@ private static void WriteMarkupXml( xml.WriteElementString("CreationAuthor", "NwcIO"); string desc = FormattableString.Invariant( - $"Geometric clash detected between {clash.ModelAName} (Mesh #{clash.MeshA.Id}, {clash.IfcGuidA}) and {clash.ModelBName} (Mesh #{clash.MeshB.Id}, {clash.IfcGuidB}). Overlap volume: {clash.Volume:F4} m³ at center ({clash.Center.X:F3}, {clash.Center.Y:F3}, {clash.Center.Z:F3})."); + $"Geometric clash detected between {clash.ModelAName} (Mesh #{clash.MeshA.Id}, {clash.IfcGuidA}) and {clash.ModelBName} (Mesh #{clash.MeshB.Id}, {clash.IfcGuidB}). Overlap volume: {clash.Volume:F4} cubic document units at center ({clash.Center.X:F3}, {clash.Center.Y:F3}, {clash.Center.Z:F3})."); xml.WriteElementString("Description", desc); xml.WriteEndElement(); // Topic @@ -244,8 +245,9 @@ private static void WriteViewpointXml(XmlWriter xml, NwcClash clash, string view xml.WriteEndElement(); // Components // Camera Calculation - var center = clash.Center; - var size = clash.IntersectionBox.Size; + double scale = clash.ModelA.LengthUnit == clash.ModelB.LengthUnit ? clash.ModelA.MetresPerUnit ?? 1.0 : 1.0; + var center = clash.Center * scale; + var size = clash.IntersectionBox.Size * scale; double maxDim = Math.Max(size.X, Math.Max(size.Y, size.Z)); double viewDistance = maxDim > 0.05 ? Math.Max(3.0, maxDim * 4.0) : 5.0; @@ -331,7 +333,7 @@ private static void WriteViewpointMarkupXml( xml.WriteEndDocument(); } - private static void WriteCameraViewpointXml(XmlWriter xml, NwcCamera cam, string viewpointGuid) + private static void WriteCameraViewpointXml(XmlWriter xml, NwcCamera cam, string viewpointGuid, double metresPerUnit) { xml.WriteStartDocument(); xml.WriteStartElement("VisualizationInfo"); @@ -343,9 +345,9 @@ private static void WriteCameraViewpointXml(XmlWriter xml, NwcCamera cam, string { xml.WriteStartElement("OrthogonalCamera"); xml.WriteStartElement("CameraViewPoint"); - xml.WriteElementString("X", cam.Position.X.ToString("F4", CultureInfo.InvariantCulture)); - xml.WriteElementString("Y", cam.Position.Y.ToString("F4", CultureInfo.InvariantCulture)); - xml.WriteElementString("Z", cam.Position.Z.ToString("F4", CultureInfo.InvariantCulture)); + xml.WriteElementString("X", (cam.Position.X * metresPerUnit).ToString("F4", CultureInfo.InvariantCulture)); + xml.WriteElementString("Y", (cam.Position.Y * metresPerUnit).ToString("F4", CultureInfo.InvariantCulture)); + xml.WriteElementString("Z", (cam.Position.Z * metresPerUnit).ToString("F4", CultureInfo.InvariantCulture)); xml.WriteEndElement(); xml.WriteStartElement("CameraDirection"); @@ -360,16 +362,16 @@ private static void WriteCameraViewpointXml(XmlWriter xml, NwcCamera cam, string xml.WriteElementString("Z", cam.Up.Z.ToString("F4", CultureInfo.InvariantCulture)); xml.WriteEndElement(); - xml.WriteElementString("ViewToWorldScale", cam.FocalDistance.ToString("F4", CultureInfo.InvariantCulture)); + xml.WriteElementString("ViewToWorldScale", (cam.FocalDistance * metresPerUnit).ToString("F4", CultureInfo.InvariantCulture)); xml.WriteEndElement(); } else { xml.WriteStartElement("PerspectiveCamera"); xml.WriteStartElement("CameraViewPoint"); - xml.WriteElementString("X", cam.Position.X.ToString("F4", CultureInfo.InvariantCulture)); - xml.WriteElementString("Y", cam.Position.Y.ToString("F4", CultureInfo.InvariantCulture)); - xml.WriteElementString("Z", cam.Position.Z.ToString("F4", CultureInfo.InvariantCulture)); + xml.WriteElementString("X", (cam.Position.X * metresPerUnit).ToString("F4", CultureInfo.InvariantCulture)); + xml.WriteElementString("Y", (cam.Position.Y * metresPerUnit).ToString("F4", CultureInfo.InvariantCulture)); + xml.WriteElementString("Z", (cam.Position.Z * metresPerUnit).ToString("F4", CultureInfo.InvariantCulture)); xml.WriteEndElement(); xml.WriteStartElement("CameraDirection"); diff --git a/src/NwcIO/Compatibility/Grids/NwcGridSystem.cs b/src/NwcIO/Compatibility/Grids/NwcGridSystem.cs index 6a1cded..3a55b6b 100644 --- a/src/NwcIO/Compatibility/Grids/NwcGridSystem.cs +++ b/src/NwcIO/Compatibility/Grids/NwcGridSystem.cs @@ -15,6 +15,9 @@ public sealed class NwcGridSystem { public string Name { get; set; } = "Grids"; + /// Unit of the grid coordinates and location offsets. + public NwcLengthUnit LengthUnit { get; set; } + public List Lines { get; } = []; public NwcGridSystem() { } @@ -133,10 +136,14 @@ public IReadOnlyList GetIntersections() /// /// Formats a human-readable grid location descriptor for a 3D coordinate (e.g. "A / 1", "A (+1.20m) / 2 (-0.50m)"). /// - public string FormatLocation(Vector3d point, double snapTolerance = 0.05) + public string FormatLocation(Vector3d point, double snapTolerance = 0.05) => + FormatLocation(point, snapTolerance, LengthUnit); + + private string FormatLocation(Vector3d point, double snapTolerance, NwcLengthUnit lengthUnit) { if (Lines.Count == 0) return string.Empty; + string suffix = lengthUnit.GetSymbol() ?? " units"; var inter = FindNearestIntersection(point, out double interDist); if (inter is not null) { @@ -156,8 +163,8 @@ public string FormatLocation(Vector3d point, double snapTolerance = 0.05) return $"{l1.Name} / {l2.Name}"; } - string part1 = snap1 ? l1.Name : string.Create(CultureInfo.InvariantCulture, $"{l1.Name} ({off1:+0.00;-0.00;0.00}m)"); - string part2 = snap2 ? l2.Name : string.Create(CultureInfo.InvariantCulture, $"{l2.Name} ({off2:+0.00;-0.00;0.00}m)"); + string part1 = snap1 ? l1.Name : string.Create(CultureInfo.InvariantCulture, $"{l1.Name} ({off1:+0.00;-0.00;0.00}{suffix})"); + string part2 = snap2 ? l2.Name : string.Create(CultureInfo.InvariantCulture, $"{l2.Name} ({off2:+0.00;-0.00;0.00}{suffix})"); return $"{part1} / {part2}"; } @@ -172,7 +179,7 @@ public string FormatLocation(Vector3d point, double snapTolerance = 0.05) { return $"Grid {nearestLine.Name}"; } - return string.Create(CultureInfo.InvariantCulture, $"Grid {nearestLine.Name} ({off:+0.00;-0.00;0.00}m)"); + return string.Create(CultureInfo.InvariantCulture, $"Grid {nearestLine.Name} ({off:+0.00;-0.00;0.00}{suffix})"); } return string.Empty; @@ -181,23 +188,25 @@ public string FormatLocation(Vector3d point, double snapTolerance = 0.05) /// /// Automatically populates for all clash results in a test. /// - public int AssignGridLocations(NwcClashTest test) + public int AssignGridLocations(NwcClashTest test) => AssignGridLocations(test, LengthUnit); + + internal int AssignGridLocations(NwcClashTest test, NwcLengthUnit lengthUnit) { ArgumentNullException.ThrowIfNull(test); int count = 0; foreach (var clash in test.Results) { - clash.GridLocation = FormatLocation(clash.ClashPoint); + clash.GridLocation = FormatLocation(clash.ClashPoint, 0.05, lengthUnit); count++; } foreach (var group in test.Groups) { - group.GridLocation = FormatLocation(group.ClashPoint); + group.GridLocation = FormatLocation(group.ClashPoint, 0.05, lengthUnit); foreach (var c in group.Clashes) { - c.GridLocation = FormatLocation(c.ClashPoint); + c.GridLocation = FormatLocation(c.ClashPoint, 0.05, lengthUnit); count++; } } @@ -212,9 +221,10 @@ public int AssignGridLocations(NwcDocument doc) { ArgumentNullException.ThrowIfNull(doc); int count = 0; + var lengthUnit = LengthUnit == NwcLengthUnit.Unknown ? doc.LengthUnit : LengthUnit; foreach (var test in doc.ClashTests) { - count += AssignGridLocations(test); + count += AssignGridLocations(test, lengthUnit); } return count; } @@ -225,7 +235,7 @@ public int AssignGridLocations(NwcDocument doc) public static NwcGridSystem ExtractFromDocument(NwcDocument doc) { ArgumentNullException.ThrowIfNull(doc); - var system = new NwcGridSystem("Model Grids"); + var system = new NwcGridSystem("Model Grids") { LengthUnit = doc.LengthUnit }; if (doc.RootNode is null) return system; @@ -313,6 +323,10 @@ public void SaveXml(Stream stream) xml.WriteStartElement("grids"); xml.WriteStartElement("grid_system"); xml.WriteAttributeString("name", Name); + if (LengthUnit.GetMetresPerUnit().HasValue) + { + xml.WriteAttributeString("units", LengthUnit.ToString()); + } foreach (var line in Lines) { @@ -367,6 +381,11 @@ public static NwcGridSystem ReadXml(Stream stream) string sysName = sysElem?.Attribute("name")?.Value ?? "Grids"; var system = new NwcGridSystem(sysName); + if (Enum.TryParse(sysElem?.Attribute("units")?.Value, ignoreCase: true, out NwcLengthUnit unit) && + unit.GetMetresPerUnit().HasValue) + { + system.LengthUnit = unit; + } var lineElems = doc.Descendants("grid_line"); foreach (var elem in lineElems) diff --git a/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs b/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs index cbdf621..0e77e39 100644 --- a/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs +++ b/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs @@ -19,8 +19,11 @@ public sealed record NwcDistanceMeasurement( double AzimuthDegrees ) { + /// Unit of the distance and coordinates. + public NwcLengthUnit LengthUnit { get; init; } + public override string ToString() => - string.Create(CultureInfo.InvariantCulture, $"Distance: {Distance:F3} m (dX: {DeltaX:F3}, dY: {DeltaY:F3}, dZ: {DeltaZ:F3}, Horiz: {HorizontalDistance:F3}, Pitch: {PitchDegrees:F1}°)"); + string.Create(CultureInfo.InvariantCulture, $"Distance: {Distance:F3} {LengthUnit.GetSymbol() ?? "units"} (dX: {DeltaX:F3}, dY: {DeltaY:F3}, dZ: {DeltaZ:F3}, Horiz: {HorizontalDistance:F3}, Pitch: {PitchDegrees:F1}°)"); } /// @@ -34,8 +37,11 @@ public sealed record NwcPointToMeshMeasurement( Vector3d Normal ) { + /// Unit of the distance and coordinates. + public NwcLengthUnit LengthUnit { get; init; } + public override string ToString() => - string.Create(CultureInfo.InvariantCulture, $"Point-to-Mesh Distance: {Distance:F3} m at ({ClosestPoint.X:F3}, {ClosestPoint.Y:F3}, {ClosestPoint.Z:F3})"); + string.Create(CultureInfo.InvariantCulture, $"Point-to-Mesh Distance: {Distance:F3} {LengthUnit.GetSymbol() ?? "units"} at ({ClosestPoint.X:F3}, {ClosestPoint.Y:F3}, {ClosestPoint.Z:F3})"); } /// @@ -49,8 +55,11 @@ public sealed record NwcMeshToMeshMeasurement( Vector3d PointB ) { + /// Unit of the distance and coordinates. + public NwcLengthUnit LengthUnit { get; init; } + public override string ToString() => - string.Create(CultureInfo.InvariantCulture, $"Mesh-to-Mesh Clearance: {Distance:F3} m between ({PointA.X:F3},{PointA.Y:F3},{PointA.Z:F3}) and ({PointB.X:F3},{PointB.Y:F3},{PointB.Z:F3})"); + string.Create(CultureInfo.InvariantCulture, $"Mesh-to-Mesh Clearance: {Distance:F3} {LengthUnit.GetSymbol() ?? "units"} between ({PointA.X:F3},{PointA.Y:F3},{PointA.Z:F3}) and ({PointB.X:F3},{PointB.Y:F3},{PointB.Z:F3})"); } /// @@ -71,7 +80,11 @@ public static class NwcMeasureEngine /// /// Measures the 3D Euclidean distance and directional projections between two points. /// - public static NwcDistanceMeasurement MeasureDistance(Vector3d a, Vector3d b) + public static NwcDistanceMeasurement MeasureDistance(Vector3d a, Vector3d b) => + MeasureDistance(a, b, NwcLengthUnit.Unknown); + + /// Measures the distance in the supplied coordinate unit. + public static NwcDistanceMeasurement MeasureDistance(Vector3d a, Vector3d b, NwcLengthUnit lengthUnit) { double dx = b.X - a.X; double dy = b.Y - a.Y; @@ -85,7 +98,7 @@ public static NwcDistanceMeasurement MeasureDistance(Vector3d a, Vector3d b) double azimuth = horiz > 1e-12 ? Math.Atan2(dy, dx) * (180.0 / Math.PI) : 0.0; if (azimuth < 0.0) azimuth += 360.0; - return new NwcDistanceMeasurement(a, b, dist, dx, dy, dz, horiz, vert, pitch, azimuth); + return new NwcDistanceMeasurement(a, b, dist, dx, dy, dz, horiz, vert, pitch, azimuth) { LengthUnit = lengthUnit }; } /// @@ -202,7 +215,12 @@ public static Vector3d ClosestPointOnTriangle(Vector3d p, Vector3d a, Vector3d b /// /// Measures the shortest distance from a 3D point to a mesh surface, locating the closest point. /// - public static NwcPointToMeshMeasurement MeasurePointToMesh(Vector3d point, NwcMesh mesh, bool useWorldCoordinates = true) + public static NwcPointToMeshMeasurement MeasurePointToMesh(Vector3d point, NwcMesh mesh, bool useWorldCoordinates = true) => + MeasurePointToMesh(point, mesh, useWorldCoordinates, NwcLengthUnit.Unknown); + + /// Measures the point-to-mesh distance in the supplied coordinate unit. + public static NwcPointToMeshMeasurement MeasurePointToMesh( + Vector3d point, NwcMesh mesh, bool useWorldCoordinates, NwcLengthUnit lengthUnit) { ArgumentNullException.ThrowIfNull(mesh); @@ -211,7 +229,7 @@ public static NwcPointToMeshMeasurement MeasurePointToMesh(Vector3d point, NwcMe if (verts.Count == 0 || indices.Count < 3) { - return new NwcPointToMeshMeasurement(point, point, 0.0, -1, Vector3d.Zero); + return new NwcPointToMeshMeasurement(point, point, 0.0, -1, Vector3d.Zero) { LengthUnit = lengthUnit }; } double minDistance = double.PositiveInfinity; @@ -247,14 +265,19 @@ public static NwcPointToMeshMeasurement MeasurePointToMesh(Vector3d point, NwcMe } } - return new NwcPointToMeshMeasurement(point, closestPt, minDistance, closestTri, closestNormal); + return new NwcPointToMeshMeasurement(point, closestPt, minDistance, closestTri, closestNormal) { LengthUnit = lengthUnit }; } /// /// Measures the clearance (minimum distance) between two 3D polygon meshes. /// public static NwcMeshToMeshMeasurement MeasureMeshToMesh(NwcMesh meshA, NwcMesh meshB, bool useWorldCoordinates = true) => - MeasureMeshToMesh(meshA, meshB, useWorldCoordinates, default); + MeasureMeshToMesh(meshA, meshB, useWorldCoordinates, cancellationToken: default); + + /// Measures the clearance in the supplied coordinate unit. + public static NwcMeshToMeshMeasurement MeasureMeshToMesh( + NwcMesh meshA, NwcMesh meshB, bool useWorldCoordinates, NwcLengthUnit lengthUnit) => + MeasureMeshToMesh(meshA, meshB, useWorldCoordinates, cancellationToken: default) with { LengthUnit = lengthUnit }; internal static NwcMeshToMeshMeasurement MeasureMeshToMesh( NwcMesh meshA, NwcMesh meshB, bool useWorldCoordinates, CancellationToken cancellationToken) diff --git a/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs b/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs index 8805ef0..56d4fcf 100644 --- a/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs +++ b/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs @@ -266,7 +266,7 @@ public void ExportClashReportXml(string path) /// Exports detected clash results to a buildingSMART BCF 2.1 zip archive (.bcfzip). public void ExportClashBcf(string path) { - Clash.NwcClashBcfExporter.SaveTests(path, ClashTests, Name); + Clash.NwcClashBcfExporter.SaveTests(path, ClashTests, Name, CommonLengthUnit); } /// Exports the 4D TimeLiner schedule to Navisworks XML exchange format (.xml). @@ -398,7 +398,7 @@ public void SaveBcf(Stream stream, IReadOnlyList? clashes = null) public void SaveViewpointsBcf(string path, IReadOnlyList? viewpoints = null) { viewpoints ??= SavedViewpoints; - BcfExporter.WriteViewpointsFile(viewpoints, path, Name); + BcfExporter.WriteViewpointsFile(viewpoints, path, Name, CommonLengthUnit.GetMetresPerUnit() ?? 1.0); } /// @@ -407,25 +407,25 @@ public void SaveViewpointsBcf(string path, IReadOnlyList? vie public void SaveViewpointsBcf(Stream stream, IReadOnlyList? viewpoints = null) { viewpoints ??= SavedViewpoints; - BcfExporter.WriteViewpoints(viewpoints, stream, Name); + BcfExporter.WriteViewpoints(viewpoints, stream, Name, CommonLengthUnit.GetMetresPerUnit() ?? 1.0); } /// /// Exports saved viewpoints of the assembly to an Autodesk Navisworks XML viewpoints file. /// - public void SaveViewpointsXml(string path, IReadOnlyList? viewpoints = null, string units = "m") + public void SaveViewpointsXml(string path, IReadOnlyList? viewpoints = null, string? units = null) { viewpoints ??= SavedViewpoints; - Sectioning.NwcXmlViewpointSerializer.Save(path, viewpoints, units); + Sectioning.NwcXmlViewpointSerializer.Save(path, viewpoints, units ?? CommonLengthUnit.GetSymbol() ?? "m"); } /// /// Serializes saved viewpoints of the assembly to an Autodesk Navisworks XML viewpoints string. /// - public string ToViewpointsXml(IReadOnlyList? viewpoints = null, string units = "m") + public string ToViewpointsXml(IReadOnlyList? viewpoints = null, string? units = null) { viewpoints ??= SavedViewpoints; - return Sectioning.NwcXmlViewpointSerializer.Serialize(viewpoints, units); + return Sectioning.NwcXmlViewpointSerializer.Serialize(viewpoints, units ?? CommonLengthUnit.GetSymbol() ?? "m"); } /// @@ -483,10 +483,11 @@ public int AssignGridLocations(Grids.NwcGridSystem? gridSystem = null) grids ??= new Grids.NwcGridSystem("Assembly Grids"); GridSystem = grids; + var lengthUnit = grids.LengthUnit == NwcLengthUnit.Unknown ? CommonLengthUnit : grids.LengthUnit; int count = 0; foreach (var test in ClashTests) { - count += grids.AssignGridLocations(test); + count += grids.AssignGridLocations(test, lengthUnit); } foreach (var m in Models) { diff --git a/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs b/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs index 5540cd3..0df07b5 100644 --- a/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs +++ b/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs @@ -68,19 +68,19 @@ public Task SaveViewpointsBcfAsync(Stream stream, CancellationToken cancellation private void WriteViewpointsBcf(Stream output, CancellationToken cancellationToken) => BcfExporter.WriteViewpoints(SavedViewpoints, output, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model"), - cancellationToken); + MetresPerUnit ?? 1.0, cancellationToken); /// Exports saved viewpoints to a Navisworks XML file asynchronously. - public Task SaveViewpointsXmlAsync(string path, string units = "m", CancellationToken cancellationToken = default) => + public Task SaveViewpointsXmlAsync(string path, string? units = null, CancellationToken cancellationToken = default) => CompatibilityExport.WriteFileAsync(path, output => WriteViewpointsXml(output, units, cancellationToken), cancellationToken); /// Exports saved viewpoints to a Navisworks XML stream asynchronously. - public Task SaveViewpointsXmlAsync(Stream stream, string units = "m", CancellationToken cancellationToken = default) => + public Task SaveViewpointsXmlAsync(Stream stream, string? units = null, CancellationToken cancellationToken = default) => CompatibilityExport.WriteAsync(stream, output => WriteViewpointsXml(output, units, cancellationToken), cancellationToken); - private void WriteViewpointsXml(Stream output, string units, CancellationToken cancellationToken) => + private void WriteViewpointsXml(Stream output, string? units, CancellationToken cancellationToken) => CompatibilityExport.WriteText(output, Encoding.UTF8, - writer => writer.Write(NwcXmlViewpointSerializer.Serialize(SavedViewpoints, units, cancellationToken))); + writer => writer.Write(NwcXmlViewpointSerializer.Serialize(SavedViewpoints, units ?? LengthUnit.GetSymbol() ?? "m", cancellationToken))); /// Exports a standalone HTML viewer to a file asynchronously. public Task SaveHtmlViewerAsync(string path, NwcHtmlViewerOptions? options = null, CancellationToken cancellationToken = default) => diff --git a/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs b/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs index 5c286fb..42ddbe4 100644 --- a/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs +++ b/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs @@ -235,7 +235,7 @@ public void ExportClashBcf(string path, string? testName = null) var tests = string.IsNullOrEmpty(testName) ? ClashTests : ClashTests.Where(t => string.Equals(t.Name, testName, StringComparison.OrdinalIgnoreCase)); - Model.Clash.NwcClashBcfExporter.SaveTests(path, tests, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model")); + Model.Clash.NwcClashBcfExporter.SaveTests(path, tests, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model"), LengthUnit); } /// Exports detected clash results to a BCF 2.1 stream. @@ -244,7 +244,7 @@ public void ExportClashBcf(Stream stream, string? testName = null) var tests = string.IsNullOrEmpty(testName) ? ClashTests : ClashTests.Where(t => string.Equals(t.Name, testName, StringComparison.OrdinalIgnoreCase)); - Model.Clash.NwcClashBcfExporter.WriteTests(stream, tests, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model")); + Model.Clash.NwcClashBcfExporter.WriteTests(stream, tests, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model"), LengthUnit); } /// Loads clash detective tests and results from a Navisworks Clash Report XML file. @@ -302,25 +302,25 @@ public string ToIfcString(NwcIfcExportOptions? options = null) /// Exports saved viewpoints to a buildingSMART BCF 2.1 zip archive (.bcfzip). public void SaveViewpointsBcf(string path) { - Internal.Export.BcfExporter.WriteViewpointsFile(SavedViewpoints, path, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model")); + Internal.Export.BcfExporter.WriteViewpointsFile(SavedViewpoints, path, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model"), MetresPerUnit ?? 1.0); } /// Exports saved viewpoints to a buildingSMART BCF 2.1 zip stream. public void SaveViewpointsBcf(Stream stream) { - Internal.Export.BcfExporter.WriteViewpoints(SavedViewpoints, stream, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model")); + Internal.Export.BcfExporter.WriteViewpoints(SavedViewpoints, stream, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model"), MetresPerUnit ?? 1.0); } /// Exports saved viewpoints, cameras, clipping planes, and redlines to an Autodesk Navisworks XML viewpoints file. - public void SaveViewpointsXml(string path, string units = "m") + public void SaveViewpointsXml(string path, string? units = null) { - Model.Sectioning.NwcXmlViewpointSerializer.Save(path, SavedViewpoints, units); + Model.Sectioning.NwcXmlViewpointSerializer.Save(path, SavedViewpoints, units ?? LengthUnit.GetSymbol() ?? "m"); } /// Serializes saved viewpoints, cameras, clipping planes, and redlines to an Autodesk Navisworks XML viewpoints string. - public string ToViewpointsXml(string units = "m") + public string ToViewpointsXml(string? units = null) { - return Model.Sectioning.NwcXmlViewpointSerializer.Serialize(SavedViewpoints, units); + return Model.Sectioning.NwcXmlViewpointSerializer.Serialize(SavedViewpoints, units ?? LengthUnit.GetSymbol() ?? "m"); } /// diff --git a/src/NwcIO/Compatibility/Viewer/NwcHtmlViewerExporter.cs b/src/NwcIO/Compatibility/Viewer/NwcHtmlViewerExporter.cs index aa76732..7889442 100644 --- a/src/NwcIO/Compatibility/Viewer/NwcHtmlViewerExporter.cs +++ b/src/NwcIO/Compatibility/Viewer/NwcHtmlViewerExporter.cs @@ -95,7 +95,7 @@ internal static NwcHtmlViewerExportResult WriteDocument( options.GridSystem ??= doc.GridSystem; options.TimeLiner ??= doc.TimeLiner; options.SelectionSets ??= doc.SelectionSets; - return WriteWithResult(writer, doc.Meshes, doc.SavedViewpoints, doc.ClashTests, doc.BoundingBox, options, cancellationToken); + return WriteWithResult(writer, doc.Meshes, doc.SavedViewpoints, doc.ClashTests, doc.BoundingBox, options, doc.LengthUnit, cancellationToken); } /// @@ -123,7 +123,8 @@ public static NwcHtmlViewerExportResult SaveWithResult(string path, NwcAssembly options.SelectionSets ??= assembly.SelectionSets; using var fs = File.Create(path); using var writer = new StreamWriter(fs, Encoding.UTF8); - return WriteWithResult(writer, assembly.AllMeshes, assembly.SavedViewpoints, assembly.ClashTests, assembly.BoundingBox, options); + return WriteWithResult(writer, assembly.AllMeshes, assembly.SavedViewpoints, assembly.ClashTests, assembly.BoundingBox, + options, assembly.CommonLengthUnit, default); } /// @@ -175,7 +176,7 @@ public static NwcHtmlViewerExportResult WriteWithResult( IReadOnlyList clashTests, BoundingBox3d bounds, NwcHtmlViewerOptions options) - => WriteWithResult(writer, meshes, viewpoints, clashTests, bounds, options, default); + => WriteWithResult(writer, meshes, viewpoints, clashTests, bounds, options, NwcLengthUnit.Unknown, default); private static NwcHtmlViewerExportResult WriteWithResult( TextWriter writer, @@ -184,13 +185,14 @@ private static NwcHtmlViewerExportResult WriteWithResult( IReadOnlyList clashTests, BoundingBox3d bounds, NwcHtmlViewerOptions options, + NwcLengthUnit lengthUnit, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(meshes); options ??= new NwcHtmlViewerOptions(); - var (jsonPayload, result) = BuildJsonPayload(meshes, viewpoints, clashTests, bounds, options, cancellationToken); + var (jsonPayload, result) = BuildJsonPayload(meshes, viewpoints, clashTests, bounds, options, lengthUnit, cancellationToken); writer.WriteLine(""); writer.WriteLine(""); @@ -311,8 +313,8 @@ private static string GetHeaderAndLayout(string title)
3D Measure
Click 2 points to measure
@@ -1117,8 +1119,8 @@ function zoomCamera(factor) { document.getElementById('measure-status').textContent = 'Measurement complete:'; document.getElementById('measure-results').style.display = 'block'; - document.getElementById('m-dist').textContent = `${dist.toFixed(3)} m`; - document.getElementById('m-horiz').textContent = `${horiz.toFixed(3)} m`; + document.getElementById('m-dist').textContent = `${dist.toFixed(3)} ${modelData.lengthUnit}`; + document.getElementById('m-horiz').textContent = `${horiz.toFixed(3)} ${modelData.lengthUnit}`; document.getElementById('m-deltas').textContent = `${dx.toFixed(2)} / ${dy.toFixed(2)} / ${dz.toFixed(2)} m`; document.getElementById('m-pitch').textContent = `${pitch.toFixed(1)}°`; } @@ -1809,6 +1811,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( IReadOnlyList clashTests, BoundingBox3d bounds, NwcHtmlViewerOptions options, + NwcLengthUnit lengthUnit, CancellationToken cancellationToken) { using var stream = new MemoryStream(); @@ -1816,6 +1819,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( writer.WriteStartObject(); writer.WriteString("title", options.Title); + writer.WriteString("lengthUnit", lengthUnit.GetSymbol() ?? "units"); // Bounding Box: left out when it isn't finite (a document without geometry), so the viewer uses its default if (IsFinite(bounds.Min) && IsFinite(bounds.Max)) diff --git a/src/NwcIO/Model/NwcAssembly.cs b/src/NwcIO/Model/NwcAssembly.cs index 46b1521..b6130b7 100644 --- a/src/NwcIO/Model/NwcAssembly.cs +++ b/src/NwcIO/Model/NwcAssembly.cs @@ -22,6 +22,10 @@ public sealed partial class NwcAssembly .Skip(1) .Any(); + internal NwcLengthUnit CommonLengthUnit => HasMixedLengthUnits + ? NwcLengthUnit.Unknown + : Models.Select(model => model.LengthUnit).FirstOrDefault(unit => unit.GetMetresPerUnit().HasValue); + /// /// Synthetic assembly root. Its id is negative so it cannot collide with the /// document roots (id 0); node ids are otherwise unique only within a document. @@ -184,7 +188,13 @@ public static NwcAssembly Create(string name, IEnumerable models) rootNode.Children.AddRange(rootChildren); var assembly = new NwcAssembly(name, modelList, rootNode, allMeshes, [.. matSet], totalBox, allViewpoints, meshModelIndexes); - assembly.Diagnostics = modelList.SelectMany(m => m.Diagnostics).ToList(); + var diagnostics = modelList.SelectMany(m => m.Diagnostics).ToList(); + if (assembly.HasMixedLengthUnits) + { + diagnostics.Add(new NwcDiagnostic(NwcDiagnosticSeverity.Warning, "MixedLengthUnits", + "The assembly contains models with different length units. Their original coordinates were retained.")); + } + assembly.Diagnostics = diagnostics; return assembly; } diff --git a/tests/NwcIO.Tests/GridSystemTests.cs b/tests/NwcIO.Tests/GridSystemTests.cs index f69322c..e897297 100644 --- a/tests/NwcIO.Tests/GridSystemTests.cs +++ b/tests/NwcIO.Tests/GridSystemTests.cs @@ -37,7 +37,7 @@ public void GridSystem_AfterEndpointEdit_UpdatesIntersectionsAndLocation(bool ed [Fact] public void GridSystem_AfterDirectLineAddition_UpdatesIntersectionsAndLocation() { - var grids = new NwcGridSystem(); + var grids = new NwcGridSystem { LengthUnit = NwcLengthUnit.Meters }; grids.AddLine("A", new Vector3d(0, -10, 0), new Vector3d(0, 10, 0)); grids.AddLine("1", new Vector3d(-10, 0, 0), new Vector3d(30, 0, 0)); Assert.Single(grids.GetIntersections()); @@ -54,7 +54,7 @@ public void GridSystem_AfterDirectLineAddition_UpdatesIntersectionsAndLocation() [Fact] public void GridSystem_AfterDirectLineRemoval_UpdatesIntersectionsAndLocation() { - var grids = new NwcGridSystem(); + var grids = new NwcGridSystem { LengthUnit = NwcLengthUnit.Meters }; var line = grids.AddLine("A", new Vector3d(0, -10, 0), new Vector3d(0, 10, 0)); grids.AddLine("B", new Vector3d(20, -10, 0), new Vector3d(20, 10, 0)); grids.AddLine("1", new Vector3d(-10, 0, 0), new Vector3d(30, 0, 0)); @@ -92,7 +92,7 @@ public void GridLine_CalculatesDistanceAndIntersection() [Fact] public void GridSystem_FindsNearestAndFormatsLocation() { - var grids = new NwcGridSystem("Building Grids"); + var grids = new NwcGridSystem("Building Grids") { LengthUnit = NwcLengthUnit.Meters }; grids.AddLine("A", new Vector3d(0, -20, 0), new Vector3d(0, 20, 0)); grids.AddLine("B", new Vector3d(6, -20, 0), new Vector3d(6, 20, 0)); grids.AddLine("1", new Vector3d(-10, 0, 0), new Vector3d(20, 0, 0)); diff --git a/tests/NwcIO.Tests/NwcLengthUnitTests.cs b/tests/NwcIO.Tests/NwcLengthUnitTests.cs index 1642ed1..d3a5dc9 100644 --- a/tests/NwcIO.Tests/NwcLengthUnitTests.cs +++ b/tests/NwcIO.Tests/NwcLengthUnitTests.cs @@ -1,4 +1,11 @@ +using System.IO.Compression; +using System.Text; +using System.Xml.Linq; using NwcIO.Model; +using NwcIO.Model.Clash; +using NwcIO.Model.Diff; +using NwcIO.Model.Grids; +using NwcIO.Model.Measure; using Xunit; namespace NwcIO.Tests; @@ -64,8 +71,12 @@ public void Assembly_ReportsMixedLengthUnits() var unknown = NwcDocument.Create(fileInfo: new NwcFileInfo { LengthUnit = NwcLengthUnit.Unknown }); - Assert.True(NwcAssembly.Create("mixed", feet, meters).HasMixedLengthUnits); - Assert.False(NwcAssembly.Create("same", meters, same).HasMixedLengthUnits); + var mixed = NwcAssembly.Create("mixed", feet, meters); + Assert.True(mixed.HasMixedLengthUnits); + Assert.Equal(NwcDiagnosticSeverity.Warning, Assert.Single(mixed.Diagnostics, d => d.Code == "MixedLengthUnits").Severity); + var homogeneous = NwcAssembly.Create("same", meters, same); + Assert.False(homogeneous.HasMixedLengthUnits); + Assert.DoesNotContain(homogeneous.Diagnostics, d => d.Code == "MixedLengthUnits"); Assert.False(NwcAssembly.Create("nwf", unknown, feet, feet).HasMixedLengthUnits); Assert.False(NwcAssembly.Create("unknown", unknown, unknown).HasMixedLengthUnits); } @@ -106,6 +117,167 @@ public void IfcExport_KeepsMetreCoordinatesOfAMetresDocumentWithMetreOutput() Assert.Contains("1234", ifc, StringComparison.Ordinal); } + [Theory] + [InlineData(NwcLengthUnit.Meters, 1)] + [InlineData(NwcLengthUnit.Millimeters, 1000)] + public void IfcExport_ConvertsKnownCoordinatesToMetres(NwcLengthUnit unit, double unitsPerMetre) + { + var doc = Document(unit, Triangle(1, unitsPerMetre, 0)); + var options = new NwcIfcExportOptions { LengthUnit = NwcIfcLengthUnit.Metre }; + + Assert.Contains("IFCCARTESIANPOINT((2.,0.,0.))", doc.ToIfcString(options), StringComparison.Ordinal); + using var assemblyIfc = new StringWriter(); + NwcAssembly.Create("Model", doc).SaveIfc(assemblyIfc, options); + Assert.Contains("IFCCARTESIANPOINT((2.,0.,0.))", assemblyIfc.ToString(), StringComparison.Ordinal); + } + + [Theory] + [InlineData(NwcLengthUnit.Meters, 1)] + [InlineData(NwcLengthUnit.Millimeters, 1000)] + public void ClashAndDiff_UseTolerancesInDocumentUnits(NwcLengthUnit unit, double unitsPerMetre) + { + double shift = 0.002 * unitsPerMetre; + var a = Triangle(1, unitsPerMetre, 0); + var b = Triangle(2, unitsPerMetre, shift); + var document = Document(unit, a, b); + + var belowDistance = new NwcClashTest("Below", NwcClashTestType.Clearance, shift / 2); + var aboveDistance = new NwcClashTest("Above", NwcClashTestType.Clearance, shift * 2); + Assert.Empty(NwcClashDetector.Run(document, belowDistance).Results); + Assert.Equal(shift, Assert.Single(NwcClashDetector.Run(document, aboveDistance).Results).Distance, 8); + + var baseline = Document(unit, a); + var revision = Document(unit, Triangle(1, unitsPerMetre, shift)); + Assert.Single(NwcDiffEngine.Compare(baseline, revision, new NwcDiffOptions { GeometricTolerance = shift / 2 }).Modified); + Assert.Single(NwcDiffEngine.Compare(baseline, revision, new NwcDiffOptions { GeometricTolerance = shift * 2 }).Unchanged); + } + + [Theory] + [InlineData(NwcLengthUnit.Meters, 1, "m", "+1.00m", "1.000 m")] + [InlineData(NwcLengthUnit.Millimeters, 1000, "mm", "+1000.00mm", "1000.000 mm")] + public async Task GridMeasurementsAndViewpointXml_UseSourceUnits( + NwcLengthUnit unit, double unitsPerMetre, string symbol, string offset, string distance) + { + var doc = Document(unit, Triangle(1, unitsPerMetre, 0)); + var grid = doc.ExtractGridSystem(); + grid.AddLine("A", new(0, -2 * unitsPerMetre, 0), new(0, 2 * unitsPerMetre, 0)); + Assert.Equal(unit, grid.LengthUnit); + Assert.Equal($"Grid A ({offset})", grid.FormatLocation(new Vector3d(unitsPerMetre, 0, 0))); + using var gridXml = new MemoryStream(); + grid.SaveXml(gridXml); + gridXml.Position = 0; + Assert.Equal(unit, NwcGridSystem.ReadXml(gridXml).LengthUnit); + + Assert.Contains(distance, NwcMeasureEngine.MeasureDistance(Vector3d.Zero, new(unitsPerMetre, 0, 0), unit).ToString(), + StringComparison.Ordinal); + var b = Triangle(2, unitsPerMetre, unitsPerMetre); + Assert.Contains(distance, NwcMeasureEngine.MeasurePointToMesh(Vector3d.Zero, b, true, unit).ToString(), StringComparison.Ordinal); + Assert.Contains(distance, NwcMeasureEngine.MeasureMeshToMesh(doc.Meshes[0], b, true, unit).ToString(), StringComparison.Ordinal); + + Assert.Equal(symbol, XDocument.Parse(doc.ToViewpointsXml()).Root!.Attribute("units")!.Value); + Assert.Equal("ft", XDocument.Parse(doc.ToViewpointsXml("ft")).Root!.Attribute("units")!.Value); + using var viewpointXml = new MemoryStream(); + await doc.SaveViewpointsXmlAsync(viewpointXml); + viewpointXml.Position = 0; + Assert.Equal(symbol, XDocument.Load(viewpointXml).Root!.Attribute("units")!.Value); + + using var html = new MemoryStream(); + await doc.SaveHtmlViewerAsync(html); + Assert.Contains($"\"lengthUnit\":\"{symbol}\"", Encoding.UTF8.GetString(html.ToArray()), StringComparison.Ordinal); + } + + [Theory] + [InlineData(NwcLengthUnit.Meters, 1)] + [InlineData(NwcLengthUnit.Millimeters, 1000)] + public async Task BcfCameraPositionsAndViewScale_AreInMetres(NwcLengthUnit unit, double unitsPerMetre) + { + var a = Triangle(1, unitsPerMetre, 0); + var b = Triangle(2, unitsPerMetre, 0.002 * unitsPerMetre); + var baseline = Document(unit, a); + var revision = Document(unit, a, b); + + using var diffBcf = new MemoryStream(); + NwcDiffEngine.Compare(baseline, revision).SaveBcf(diffBcf); + Assert.Equal(new Vector3d(6, -4, 4.002), ReadCameraPoint(ReadBcfCamera(diffBcf))); + + var test = new NwcClashTest("Clearance", NwcClashTestType.Clearance, 0.004 * unitsPerMetre); + var clash = Assert.Single(NwcClashDetector.Run(revision, test).Results); + using var clashBcf = new MemoryStream(); + NwcClashBcfExporter.Write(clashBcf, test); + Assert.Equal(clash.ClashPoint / unitsPerMetre + new Vector3d(5, -5, 3.5), ReadCameraPoint(ReadBcfCamera(clashBcf))); + + var group = new NwcClashGroup("Clearance group"); + group.AddClash(clash); + test.Groups.Add(group); + test.Results.Clear(); + using var groupBcf = new MemoryStream(); + NwcClashBcfExporter.Write(groupBcf, test); + Assert.Equal(clash.ClashPoint / unitsPerMetre + new Vector3d(8, -8, 5), ReadCameraPoint(ReadBcfCamera(groupBcf))); + + var overlap = new BoundingBox3d(new Vector3d(1, 2, 3) * unitsPerMetre, new Vector3d(2, 3, 4) * unitsPerMetre); + using var spatialBcf = new MemoryStream(); + NwcAssembly.Create("Assembly", baseline, revision).SaveBcf(spatialBcf, [new NwcClash(baseline, a, revision, b, overlap)]); + var actual = ReadCameraPoint(ReadBcfCamera(spatialBcf)); + var expected = new Vector3d(1.5, 2.5, 3.5) + new Vector3d(1, -1, 0.75).Normalize() * 4; + Assert.Equal(expected.X, actual.X, 4); + Assert.Equal(expected.Y, actual.Y, 4); + Assert.Equal(expected.Z, actual.Z, 4); + + var viewpoint = new NwcSavedViewpoint + { + Name = "Orthogonal", + Camera = new NwcCamera + { + Position = new Vector3d(2, 3, 4) * unitsPerMetre, + Projection = NwcCameraProjection.Orthographic, + FocalDistance = 6 * unitsPerMetre, + }, + }; + var withViewpoint = NwcDocument.Create(fileInfo: new NwcFileInfo { LengthUnit = unit }, savedViewpoints: [viewpoint]); + using var viewpointsBcf = new MemoryStream(); + await withViewpoint.SaveViewpointsBcfAsync(viewpointsBcf); + XElement camera = ReadBcfCamera(viewpointsBcf); + Assert.Equal(new Vector3d(2, 3, 4), ReadCameraPoint(camera)); + Assert.Equal(6.0, (double)camera.Element("ViewToWorldScale")!); + } + + [Fact] + public void UnknownGridAndMeasurement_DoNotClaimMetres() + { + var grid = new NwcGridSystem(); + grid.AddLine("A", new(0, -2, 0), new(0, 2, 0)); + + Assert.Equal("Grid A (+1.00 units)", grid.FormatLocation(new Vector3d(1, 0, 0))); + Assert.Contains("1.000 units", NwcMeasureEngine.MeasureDistance(Vector3d.Zero, new(1, 0, 0)).ToString(), StringComparison.Ordinal); + } + + private static NwcDocument Document(NwcLengthUnit unit, params NwcMesh[] meshes) => + NwcDocument.Create(fileInfo: new NwcFileInfo { LengthUnit = unit }, meshes: meshes); + + private static NwcMesh Triangle(int id, double scale, double z) => new() + { + Id = id, + Name = $"Triangle {id}", + Vertices = [new(0, 0, z), new(2 * scale, 0, z), new(0, 2 * scale, z)], + Indices = [0, 1, 2], + }; + + private static XElement ReadBcfCamera(MemoryStream stream) + { + stream.Position = 0; + using var archive = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true); + var entry = Assert.Single(archive.Entries, e => e.Name == "viewpoint.bcfv"); + using var data = entry.Open(); + var root = XDocument.Load(data).Root!; + return root.Element("PerspectiveCamera") ?? root.Element("OrthogonalCamera")!; + } + + private static Vector3d ReadCameraPoint(XElement camera) + { + var p = camera.Element("CameraViewPoint")!; + return new Vector3d((double)p.Element("X")!, (double)p.Element("Y")!, (double)p.Element("Z")!); + } + [Fact] public void Unknown_ReturnsNullFactorAndSymbol() {