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 595627cf..2e83cfb2 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 Dictionary AreaReinforcementPlanes { get; } = new(); public (List Paths, HashSet Members)? GridAxes { get; set; } 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 6ba398fc..b4c9aab4 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; @@ -167,9 +168,57 @@ 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)]; + } + // 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). 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 38b167ba..082e6fe1 100644 --- a/src/RvtIO/Model/Element.cs +++ b/src/RvtIO/Model/Element.cs @@ -1058,6 +1058,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 35c69acf..ea5c4e3f 100644 --- a/src/RvtIO/Parsing/ElementBuilder.cs +++ b/src/RvtIO/Parsing/ElementBuilder.cs @@ -3601,6 +3601,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 0875c956..71900915 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -2524,9 +2524,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 657d7e11..54b0dd5b 100644 --- a/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs +++ b/tests/RvtIO.Tests/NwcSupplementalGeometryTests.cs @@ -158,6 +158,37 @@ public void NativeAreaReinforcementKeepsBothCopiesOfTheHostOutline() Assert.Equal(2, points.Chunk(2).Count(pair => pair[0].X != pair[1].X && pair[0].Y != pair[1].Y)); } + [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([1, -4, 5, 0], [0, 0, 2], [0, 1, 0], [-1, 0, 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)); + 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)); + } + [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" : "";