From 142581be939a1b669d257326080be53957213cb3 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:56:27 +0300 Subject: [PATCH 1/2] Export Revit grid and level reference geometry as hidden NWC nodes --- Directory.Packages.props | 2 +- src/RvtIO.Scene/RvtSceneOptions.cs | 3 ++ src/RvtIO.Scene/RvtSceneReader.cs | 9 +++- src/RvtIO.Scene/RvtSceneResult.cs | 3 ++ src/RvtIO/Internal/ParsingState.cs | 1 + src/RvtIO/Meshes/ElementMeshOptions.cs | 3 ++ src/RvtIO/Meshes/ElementMeshes.cs | 44 +++++++++++++++++++ src/RvtIO/Meshes/MeshSet.cs | 3 ++ src/RvtIO/Model/Element.cs | 3 ++ src/RvtIO/Parsing/ElementBuilder.cs | 1 + src/RvtIO/Parsing/TfBlockDeserializer.cs | 12 ++--- src/RvtIO/RvtFileReader.cs | 8 ++-- .../NwcSupplementalGeometryTests.cs | 26 +++++++++++ tools/RvtIO.Nwc/NwcExport.cs | 4 +- tools/RvtIO.Nwc/Program.cs | 8 +++- 15 files changed, 116 insertions(+), 14 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index daaeb8b4..bdf30cbf 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + diff --git a/src/RvtIO.Scene/RvtSceneOptions.cs b/src/RvtIO.Scene/RvtSceneOptions.cs index 24f74650..9ad5ad87 100644 --- a/src/RvtIO.Scene/RvtSceneOptions.cs +++ b/src/RvtIO.Scene/RvtSceneOptions.cs @@ -10,4 +10,7 @@ public sealed class RvtSceneOptions /// Includes straight model lines and reinforcement described by its centre lines. public bool IncludeModelLinesAndReinforcement { get; set; } + + /// Includes reference geometry for project grids and levels. + public bool IncludeDatumGeometry { get; set; } } diff --git a/src/RvtIO.Scene/RvtSceneReader.cs b/src/RvtIO.Scene/RvtSceneReader.cs index a8cea305..ef07ca20 100644 --- a/src/RvtIO.Scene/RvtSceneReader.cs +++ b/src/RvtIO.Scene/RvtSceneReader.cs @@ -118,7 +118,11 @@ public static RvtSceneResult Read(RvtDocument document, MeshSet meshes, RvtScene } private static ElementMeshOptions? MeshOptions(RvtSceneOptions? options) => - options?.IncludeModelLinesAndReinforcement == true ? new() { IncludeModelLinesAndReinforcement = true } : null; + options is null ? null : new() + { + IncludeModelLinesAndReinforcement = options.IncludeModelLinesAndReinforcement, + IncludeDatumGeometry = options.IncludeDatumGeometry, + }; private static string RequiredKey(RvtSceneOptions? options) => options?.ModelKey is { Length: > 0 } key ? key : throw new ArgumentException("A document has no file name: give the model key in RvtSceneOptions.ModelKey.", nameof(options)); @@ -168,7 +172,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m { Id = mesh.ElementId, ModelId = ModelId, - LevelId = storeys.GetStoreyId(mesh.ElementId), + LevelId = mesh.IsDatum ? null : storeys.GetStoreyId(mesh.ElementId), SourceId = element?.UniqueId, IfcGuid = element != null ? IfcGuidOf(element) : null, Kind = SceneNodeKind.Element, @@ -273,6 +277,7 @@ private static RvtSceneResult Map(RvtDocument document, MeshSet meshes, string m Diagnostics = report, ElementCount = scene.Elements.Count, ElementsWithGeometry = withGeometry, + HiddenDatumIds = meshes.Elements.Where(mesh => mesh.IsDatum).Select(mesh => (long)mesh.ElementId).ToArray(), Coverage = coverage, GeometryCount = scene.Geometries.Count, InstanceCount = scene.Instances.Count, diff --git a/src/RvtIO.Scene/RvtSceneResult.cs b/src/RvtIO.Scene/RvtSceneResult.cs index a45e4578..9aacba17 100644 --- a/src/RvtIO.Scene/RvtSceneResult.cs +++ b/src/RvtIO.Scene/RvtSceneResult.cs @@ -20,6 +20,9 @@ public sealed class RvtSceneResult /// The number of elements that have at least one instance. public int ElementsWithGeometry { get; init; } + /// Revit datum IDs whose reference geometry is hidden by default in native export. + public IReadOnlyList HiddenDatumIds { get; init; } = []; + /// The number of elements by the coverage of their meshes; a coverage that no element has is not listed. public IReadOnlyDictionary Coverage { get; init; } = new Dictionary(); diff --git a/src/RvtIO/Internal/ParsingState.cs b/src/RvtIO/Internal/ParsingState.cs index 580d358e..484ca0de 100644 --- a/src/RvtIO/Internal/ParsingState.cs +++ b/src/RvtIO/Internal/ParsingState.cs @@ -390,6 +390,7 @@ public TfBlockDeserializer.UnitsElemOptions? OwnDocumentUnitOptions /// the serialized datum text, free end, bubble end and cut vector. The element-level /// name remains authoritative for the grid mark because datum text may name its head type. public Dictionary GridDatums { get; } = new(); + public Dictionary LevelPlanes { get; } = new(); public (List Paths, HashSet Members)? GridAxes { get; set; } /// Line-style element id for 0x0346 curves whose GStyleElemId was a real id diff --git a/src/RvtIO/Meshes/ElementMeshOptions.cs b/src/RvtIO/Meshes/ElementMeshOptions.cs index 2013bdc4..8bdf99e4 100644 --- a/src/RvtIO/Meshes/ElementMeshOptions.cs +++ b/src/RvtIO/Meshes/ElementMeshOptions.cs @@ -9,4 +9,7 @@ public sealed class ElementMeshOptions /// Includes decoded straight model lines and meshes of reinforcement described by its centre lines. public bool IncludeModelLinesAndReinforcement { get; set; } + + /// Includes the finite reference lines of grids and levels for native cache export. + public bool IncludeDatumGeometry { get; set; } } diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index f9e650ed..963e98dd 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -1,5 +1,6 @@ using RvtIO.BuiltIns; using RvtIO.Geometry.Meshing; +using RvtIO.Internal; using RvtIO.Model; using RvtIO.Parsing; @@ -166,9 +167,52 @@ int MaterialOf(GeoFace face) UntriangulatedFaces = failed, }); } + if (options.IncludeDatumGeometry) + { + var existing = elements.Select(element => element.ElementId).ToHashSet(); + double lowestLevel = info.Elements.Where(element => BuildingStoreyResolver.IsProjectLevel(element) && element.LevelPlane != null) + .Select(element => element.LevelPlane!.Origin[2]).Where(double.IsFinite).DefaultIfEmpty(double.NaN).Min(); + foreach (var element in info.Elements) + if (!existing.Contains(element.Id) && DatumLinePairs(element, lowestLevel) is { } linePairs) + { + elements.Add(new ElementMesh + { + ElementId = element.Id, LinePairs = linePairs, IsDatum = true, Coverage = MeshCoverage.Complete, + }); + } + } return new MeshSet { Elements = elements, Symbols = placedSymbols, GeometryUndecoded = info.WideLayoutNotRewritten }; } + private static MeshVector[]? DatumLinePairs(Element element, double lowestLevel) + { + var plane = element.CategoryId switch + { + (int)BuiltInCategory.OST_Levels when BuildingStoreyResolver.IsProjectLevel(element) => element.LevelPlane, + (int)BuiltInCategory.OST_Grids => element.GridPlane, + _ => null, + }; + if (plane?.Envelope is not [var u0, var v0, var u1, var v1] + || plane.Origin.Length != 3 || plane.XVector.Length != 3 || plane.YVector.Length != 3 + || !plane.Envelope.Concat(plane.Origin).Concat(plane.XVector).Concat(plane.YVector).All(double.IsFinite) + || !(u1 > u0 && v1 > v0)) return null; + + MeshVector Point(double u, double v) => new( + plane.Origin[0] + u * plane.XVector[0] + v * plane.YVector[0], + plane.Origin[1] + u * plane.XVector[1] + v * plane.YVector[1], + plane.Origin[2] + u * plane.XVector[2] + v * plane.YVector[2]); + + if (element.CategoryId == (int)BuiltInCategory.OST_Grids) + { + double bottom = plane.YVector[2] >= 0 ? v0 : v1; + if (double.IsFinite(lowestLevel) && plane.YVector[2] != 0) + bottom = Math.Clamp((lowestLevel - plane.Origin[2]) / plane.YVector[2], v0, v1); + return [Point(u0, bottom), Point(u1, bottom)]; + } + var corner = Point(u0, v1); + return [Point(u0, v0), corner, corner, Point(u1, v1)]; + } + // A ghost node is a Geometry node Revit exports that has no polygon here (display surfaces, or a duplicate of another node). private static MeshCoverage CoverageOf(bool drawn, GeometryData geometry, int failed, bool symbolGhosts) => !drawn ? MeshCoverage.NoGeometry diff --git a/src/RvtIO/Meshes/MeshSet.cs b/src/RvtIO/Meshes/MeshSet.cs index ac40c3df..991c7691 100644 --- a/src/RvtIO/Meshes/MeshSet.cs +++ b/src/RvtIO/Meshes/MeshSet.cs @@ -42,6 +42,9 @@ public sealed class ElementMesh /// Independent line segments listed as consecutive endpoint pairs, in document feet. public IReadOnlyList? LinePairs { get; init; } + /// Whether the line pairs are datum references that are hidden by default. + public bool IsDatum { get; init; } + /// How completely and represent the element. public MeshCoverage Coverage { get; init; } diff --git a/src/RvtIO/Model/Element.cs b/src/RvtIO/Model/Element.cs index d9272094..975aa377 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -1055,6 +1055,9 @@ internal bool RootClassIs(string className) => NativeRootClassName != null [JsonIgnore] internal GridPlaneData? GridPlane { get; set; } + [JsonIgnore] + internal GridPlaneData? LevelPlane { get; set; } + /// CompoundStructure layers (wall/floor/ceiling types). Each layer has thickness, function, material. public List? Layers { get; set; } diff --git a/src/RvtIO/Parsing/ElementBuilder.cs b/src/RvtIO/Parsing/ElementBuilder.cs index 74d9a5fe..241b3d9a 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -3600,6 +3600,7 @@ void ApplyType(int typeId) if (np.Fields.ContainsKey("__isLevel")) { e.IsNativeLevel = true; + e.LevelPlane = state.LevelPlanes.GetValueOrDefault((uint)e.Id); if (np.DoubleFields.TryGetValue("__levelElevation", out double levelElevation) && double.IsFinite(levelElevation)) Apply(-1007102, StorageType.Double, levelElevation, force: true); diff --git a/src/RvtIO/Parsing/TfBlockDeserializer.cs b/src/RvtIO/Parsing/TfBlockDeserializer.cs index b22f2271..3a90f02b 100644 --- a/src/RvtIO/Parsing/TfBlockDeserializer.cs +++ b/src/RvtIO/Parsing/TfBlockDeserializer.cs @@ -4146,17 +4146,19 @@ double[] PointAt(double parameter) => origin.ToArray(), yVector.ToArray()); } - /// Decode the exact Level elevation from its authored datum Plane origin. - public static double? ExtractLevelElevation(byte[] d, int blockStart, uint dataSize, + /// Decode a Level's authored finite datum plane. + public static Model.GridPlaneData? ExtractLevelPlane(byte[] d, int blockStart, uint dataSize, ushort classId) { if (classId != 2299) return null; var surface = ExtractDatumPlaneSurface(d, blockStart, dataSize, classId); - if (surface == null) return null; - double elevation = surface.Value.Origin[2]; - return double.IsFinite(elevation) ? elevation : null; + return surface is { } plane ? new(plane.Envelope, plane.Origin, plane.XVector, plane.YVector) : null; } + public static double? ExtractLevelElevation(byte[] d, int blockStart, uint dataSize, ushort classId) => + ExtractLevelPlane(d, blockStart, dataSize, classId) is { } plane && double.IsFinite(plane.Origin[2]) + ? plane.Origin[2] : null; + private static (double[] Envelope, double[] Origin, double[] XVector, double[] YVector)? ExtractDatumPlaneSurface(byte[] d, int blockStart, uint dataSize, ushort classId) { diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 31d178bc..5902d81c 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -2523,9 +2523,11 @@ internal static void RunTfStreamWalk(ParsingState state) seg, bs, (uint)ds, cls); if (!string.IsNullOrWhiteSpace(levelName)) np.StringFields["m_text"] = levelName; - if (TfBlockDeserializer.ExtractLevelElevation( - seg, bs, (uint)ds, cls) is double levelElevation) - np.DoubleFields["__levelElevation"] = levelElevation; + if (TfBlockDeserializer.ExtractLevelPlane(seg, bs, (uint)ds, cls) is { } plane) + { + state.LevelPlanes[eid] = plane; + if (double.IsFinite(plane.Origin[2])) np.DoubleFields["__levelElevation"] = plane.Origin[2]; + } } if (np is { Count: > 0 }) state.NativeParams[eid] = np; if (cls == 0x083C diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs index bdc95f2d..7cec11ad 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -148,6 +148,32 @@ public void NativeAreaReinforcementKeepsTheTwelveEdgesOfItsStoredBounds() Assert.Equal(2, new[] { pair[0].X == pair[1].X, pair[0].Y == pair[1].Y, pair[0].Z == pair[1].Z }.Count(same => same)); } + [Fact] + public void NativeDatumsKeepTheirIdsAndHiddenReferenceGeometry() + { + var level = new Element + { + Id = 1, Name = "Level", CategoryId = (int)BuiltInCategory.OST_Levels, + IsNativeLevel = true, SerializedFamilyId = -1, SerializedUnplacedOwnerId = -1, SerializedOwnerDbViewId = -1, + LevelPlane = new([0, 1, 4, 5], [0, 0, 2], [1, 0, 0], [0, 1, 0]), + }; + var grid = new Element + { + Id = 2, Name = "Grid", CategoryId = (int)BuiltInCategory.OST_Grids, + GridPlane = new([1, 0, 6, 10], [0, 0, 0], [1, 0, 0], [0, 0, 1]), + }; + var document = RvtDocument.FromInfo(new RevitFileInfo { Elements = [level, grid] }); + Assert.Empty(RvtSceneReader.Read(document, new() { ModelKey = "model" }).Document.Elements); + var scene = RvtSceneReader.Read(document, new() { ModelKey = "model", IncludeDatumGeometry = true }); + Assert.Equal([1L, 2L], scene.HiddenDatumIds); + var native = Nwc.NwcExport.Build(scene.Document, "model.rvt", 0, DateTime.UnixEpoch, native: true, scene.HiddenDatumIds.ToHashSet()); + Assert.All(native.Meshes, mesh => Assert.True(mesh.Node!.IsHidden)); + Assert.Equal(4, native.Meshes.Single(mesh => mesh.Node!.Name == "Level").LineIndices.Count); + var gridMesh = native.Meshes.Single(mesh => mesh.Node!.Name == "Grid"); + Assert.Equal(2, gridMesh.LineIndices.Count); + Assert.All(gridMesh.GetWorldVertices(), point => Assert.Equal(2 * 0.3048, point.Z, 12)); + } + [Fact] public void SweepKeepsTheStoredRadiusAndExtentsOfAStraightBar() { diff --git a/tools/RvtIO.Nwc/NwcExport.cs b/tools/RvtIO.Nwc/NwcExport.cs index 226fad19..4bfc4e50 100644 --- a/tools/RvtIO.Nwc/NwcExport.cs +++ b/tools/RvtIO.Nwc/NwcExport.cs @@ -13,7 +13,8 @@ internal static class NwcExport // The optional metadata is written by NwcIO 0.14 and interpreted by the linked-cache reader. private const string MetreCacheOption = "IOExtend.NwcWriter.Scene/1"; private const string LinkClass = "IOExtend.NwcWriter.Link"; - internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp, bool native = false) + internal static NwcDocument Build(SceneDocument scene, string sourceName, long sourceLength, DateTime timestamp, + bool native = false, IReadOnlySet? hiddenDatumIds = null) { if (scene.Validate().FirstOrDefault(d => d.Severity == SceneSeverity.Error) is { } error) throw new InvalidDataException(error.Message); @@ -44,6 +45,7 @@ internal static NwcDocument Build(SceneDocument scene, string sourceName, long s { node.Class = "LcRevitElement"; node.IfcGlobalId = element.IfcGuid; + node.IsHidden = hiddenDatumIds?.Contains(element.Id) == true; } AddText(node, "Revit", "Element ID", id); AddText(node, "Revit", "UniqueId", element.SourceId); diff --git a/tools/RvtIO.Nwc/Program.cs b/tools/RvtIO.Nwc/Program.cs index bf684ace..f4792360 100644 --- a/tools/RvtIO.Nwc/Program.cs +++ b/tools/RvtIO.Nwc/Program.cs @@ -47,13 +47,17 @@ public static int Main(string[] args) var source = new FileInfo(input); long length = source.Length; - var scene = RvtSceneReader.Read(input, native ? new RvtSceneOptions { IncludeModelLinesAndReinforcement = true } : null); + var scene = RvtSceneReader.Read(input, native ? new RvtSceneOptions + { + IncludeModelLinesAndReinforcement = true, + IncludeDatumGeometry = true, + } : null); foreach (var diagnostic in scene.Diagnostics.Where(d => d.Severity != SceneSeverity.Info)) Console.Error.WriteLine($"RVT {diagnostic.Severity} [{diagnostic.Code}]: {diagnostic.Message}"); if (scene.Diagnostics.Any(d => d.Severity == SceneSeverity.Error)) return 2; - var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc, native); + var cache = NwcExport.Build(scene.Document, source.Name, length, source.LastWriteTimeUtc, native, scene.HiddenDatumIds.ToHashSet()); NwcExport.Save(cache, output, native); int lines = cache.Meshes.Count(mesh => mesh.LineIndices.Count != 0); string lineCount = lines > 0 ? $" and {lines} line meshes" : ""; From b86134504140253683b36188af5f8c707beb15c9 Mon Sep 17 00:00:00 2001 From: mie Date: Fri, 20 Nov 2026 04:13:12 +0300 Subject: [PATCH 2/2] Match Autodesk level outlines in project coordinates --- src/RvtIO/Meshes/ElementMeshes.cs | 9 +++++++-- tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/RvtIO/Meshes/ElementMeshes.cs b/src/RvtIO/Meshes/ElementMeshes.cs index 07523b6c..b4c9aab4 100644 --- a/src/RvtIO/Meshes/ElementMeshes.cs +++ b/src/RvtIO/Meshes/ElementMeshes.cs @@ -210,8 +210,13 @@ int MaterialOf(GeoFace face) bottom = Math.Clamp((lowestLevel - plane.Origin[2]) / plane.YVector[2], v0, v1); return [Point(u0, bottom), Point(u1, bottom)]; } - var corner = Point(u0, v1); - return [Point(u0, v0), corner, corner, Point(u1, v1)]; + // Level outlines follow the west and north bounds in project coordinates. + MeshVector[] corners = [Point(u0, v0), Point(u0, v1), Point(u1, v0), Point(u1, v1)]; + double west = corners.Min(point => point.X); + double north = corners.Max(point => point.Y); + double z = plane.Origin[2]; + MeshVector corner = new(west, north, z); + return [new(west, corners.Min(point => point.Y), z), corner, corner, new(corners.Max(point => point.X), north, z)]; } // A ghost node is a Geometry node Revit exports that has no polygon here (display surfaces, or a duplicate of another node). diff --git a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs index a388eb9e..54b0dd5b 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -165,7 +165,7 @@ public void NativeDatumsKeepTheirIdsAndHiddenReferenceGeometry() { Id = 1, Name = "Level", CategoryId = (int)BuiltInCategory.OST_Levels, IsNativeLevel = true, SerializedFamilyId = -1, SerializedUnplacedOwnerId = -1, SerializedOwnerDbViewId = -1, - LevelPlane = new([0, 1, 4, 5], [0, 0, 2], [1, 0, 0], [0, 1, 0]), + LevelPlane = new([1, -4, 5, 0], [0, 0, 2], [0, 1, 0], [-1, 0, 0]), }; var grid = new Element { @@ -178,7 +178,12 @@ public void NativeDatumsKeepTheirIdsAndHiddenReferenceGeometry() Assert.Equal([1L, 2L], scene.HiddenDatumIds); var native = Nwc.NwcExport.Build(scene.Document, "model.rvt", 0, DateTime.UnixEpoch, native: true, scene.HiddenDatumIds.ToHashSet()); Assert.All(native.Meshes, mesh => Assert.True(mesh.Node!.IsHidden)); - Assert.Equal(4, native.Meshes.Single(mesh => mesh.Node!.Name == "Level").LineIndices.Count); + var levelMesh = native.Meshes.Single(mesh => mesh.Node!.Name == "Level"); + var levelPoints = levelMesh.GetWorldVertices().ToArray(); + Assert.Equal(new NwcIO.Model.Vector3d(0, 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[0]]); + Assert.Equal(new NwcIO.Model.Vector3d(0, 5 * 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[1]]); + Assert.Equal(levelPoints[levelMesh.LineIndices[1]], levelPoints[levelMesh.LineIndices[2]]); + Assert.Equal(new NwcIO.Model.Vector3d(4 * 0.3048, 5 * 0.3048, 2 * 0.3048), levelPoints[levelMesh.LineIndices[3]]); var gridMesh = native.Meshes.Single(mesh => mesh.Node!.Name == "Grid"); Assert.Equal(2, gridMesh.LineIndices.Count); Assert.All(gridMesh.GetWorldVertices(), point => Assert.Equal(2 * 0.3048, point.Z, 12));