diff --git a/CHANGELOG.md b/CHANGELOG.md index f01d31e..ddbd4f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte ## [Unreleased] ### Added +- `HierarchyParser` keeps linked Revit placements instead of throwing: a repeated element under another parent is marked `NwcNode.IsLinkPlacement` and points at the first placement. `NwcSceneReader` writes each placement as its own `SceneModel`, so its geometry and `SourceId` are preserved without duplicate ids inside one model. - `NwcIO.Scene` converts an `NwcAssembly` into one scene with one `SceneModel` per component document, unique keys from file names, and scene-wide element, geometry and material ids. The `.nwf` document itself is skipped when components exist. - `NwcIO.Scene` writes Revit level elevations in metres from the level's `LcRevitData_Parameter` length property; a missing, non-finite or unknown-unit value stays null. - `NwcIO.Scene` converts saved viewpoints to `SceneViewpoint`s (camera position, target, up, field of view in radians, near/far in metres and projection). diff --git a/README.md b/README.md index 05d64b2..ec93d53 100644 --- a/README.md +++ b/README.md @@ -155,13 +155,13 @@ The documentation site with API references and guides is at 0` and the next element's index is `X + 2`. The same `X` under different parents, including a node and its descendant, is rejected as a placed model (`NotSupportedException`). + - `X` (element index): 0 on every node that is not a Revit element; on an element node, `X - 1` indexes the GUID table (§2.3). The exporter writes some elements (for example grids) as two sibling nodes with the same `X`, not always adjacent; NwcIO makes the first the element and points the second to it. Such a pair takes two equal GUID table entries (`X - 1` and `X`), so the table size is the number of stored nodes with `X > 0` and the next element's index is `X + 2`. The same `X` under different parents, including a node and its descendant, is a linked placement: NwcIO keeps it with `NwcNode.IsLinkPlacement`, points `Element` at the first placement, and `NwcIO.Scene` writes it as its own `SceneModel`. - `32` (`LcOaPartition`, `.nwd` only): `[i32 0]`, a class-53 body, then a trailer that is not decoded. Class 32 nodes are the top-level children of a `.nwd`; class 53 nodes are the top-level children of a `.nwc`. - `52` display/internal name pair: `[str name][str internal]`. It is the node username, the property tab username and every property key. - **Attributes** (slots may be null): `86` property tab `[str name][ptr 52][i32 flags][i32 n] n x ([ptr 52 key][i32 type][value])` with value by type `0` none, `1,5,6,7,10,11` `f64`, `2,3` `i32`, `4` and `9` string (type 9 was never seen; it is read as a string), `8` class-52 pointer; `31` material; `40` translation; `41` translation and quaternion (`x -> R(q)x + t`); `39` 3x3 column-major matrix and translation; `79` hyperlinks; `200` and `185` material JSON. diff --git a/docs/getting-started.md b/docs/getting-started.md index 3024d33..4472e1d 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -39,9 +39,10 @@ dotnet tool install --global NwcIO.Cli ```csharp using NwcIO; -// Open a .nwc file directly from disk. A .nwd whose scene tree holds partition nodes, and a linked -// Revit model (a tree that places one element under two parents), need -// new NwcReaderOptions { BuildSceneTree = false }, because such trees are not decoded yet. +// Open a .nwc file directly from disk. A .nwd whose scene tree holds partition nodes needs +// new NwcReaderOptions { BuildSceneTree = false }, because those nodes are not decoded yet. +// A linked Revit model (a tree that places one element under two parents) is kept and +// converted into separate scene models. var doc = NwcDocument.Open("model.nwc"); Console.WriteLine($"Source: {doc.FileInfo?.SourcePath}"); diff --git a/docs/public-api.md b/docs/public-api.md index c08ecec..fec7821 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -10,7 +10,7 @@ The supported surface is the `NwcIO` and `NwcIO.Model.*` namespaces listed here | Type | Description | |---|---| -| `NwcDocument` | Primary document container holding the root scene graph node, meshes, materials, viewpoints, selection sets, and TimeLiner schedules. Opens `.nwc`, `.nwd`, and `.nwf` files via `NwcDocument.Open`; `.nwd` scene trees with partition nodes, and trees that place one Revit element under two parents (linked models), throw `NotSupportedException` unless `BuildSceneTree` is false. `IsRevitSource` is true when the loader plugin is exactly the Revit loader `LcNwcLoaderPlugin:lcldrevit` (Navisworks reading a `.rvt`) or the Revit NWC exporter `nwexportrevit`. `LengthUnit` and `MetresPerUnit` give the length unit of coordinates and length values: feet (0.3048 m) for those two loaders, otherwise `Unknown` and null. | +| `NwcDocument` | Primary document container holding the root scene graph node, meshes, materials, viewpoints, selection sets, and TimeLiner schedules. Opens `.nwc`, `.nwd`, and `.nwf` files via `NwcDocument.Open`; `.nwd` scene trees with partition nodes throw `NotSupportedException` unless `BuildSceneTree` is false. Trees that place one Revit element under two parents (linked models) are decoded: the repeated node is marked `IsLinkPlacement`. `IsRevitSource` is true when the loader plugin is exactly the Revit loader `LcNwcLoaderPlugin:lcldrevit` (Navisworks reading a `.rvt`) or the Revit NWC exporter `nwexportrevit`. `LengthUnit` and `MetresPerUnit` give the length unit of coordinates and length values: feet (0.3048 m) for those two loaders, otherwise `Unknown` and null. | | `NwcDocumentBuilder` | Fluent builder API for creating Navisworks documents and geometry programmatically from code. | | `NwcWriter` | Direct `#LcUStream-V1.1` binary container serializer and continuous zlib chunk writer. Throws `ArgumentException` before writing for input it cannot store faithfully: an unrecognised header, scaled transforms, line meshes, triangle indices outside the vertex buffer, out-of-range vertex counts or coordinates, records or nodes without a name/class, and viewpoint names the reader would rename. Mesh ids, names and triangle indices are stored; normals and materials are not. `Materials`, `XRefs`, `DbCache`, `AppearanceProfiler`, `ClashTests` and `GridSystem` are not written; the output is read back by NwcIO but has not been verified in Autodesk Navisworks. | | `NwcReaderOptions` | Per-open options: which streams to read (property records, GUIDs, transforms, meshes, viewpoints, selection sets, TimeLiner), whether to read materials (`ReadMaterials`: decoded from the file on the strict path, named in property records elsewhere, with a neutral inferred colour unless a `revit_Color` record gives one), whether to build the scene tree (`BuildSceneTree`), catalog retention. | diff --git a/docs/scene.md b/docs/scene.md index e4af712..a2412ce 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -37,7 +37,7 @@ The scene has one model per input document. Geometry and instance positions are | `SceneModel.Key`, `Name` | `NwcSceneOptions.ModelKey`, else the file name with its extension. | | `SceneModel` fields | `SourceFormat` is `nwc`; `Path` is set only when the scene is read from a path; `CreatedAt` is the source timestamp as `yyyy-MM-ddTHH:mm:ssZ`; `Application` is the loader plugin after its last `:` (for example `lcldrevit`, or `nwexportrevit` for the Revit NWC exporter); `SourceLengthUnit` is `ft` when the unit used is feet. | | Elements | One `SceneElement` per tree node, `Id` = the node's preorder index with the root as 0, `Name` = the node name. Kind: the root is `Model`; on Revit files a depth-1 node holding a Revit level is `Level`; every node that is a Revit element or lies inside one (its parts, and the second node of a sibling pair) is `Element`; a leaf outside elements (no children, tag other than 53) is `Element` too; every other node is `Group`. | -| Sibling pair | A Revit export may write one element twice under one parent. The first in stored order is the element; the second maps as a part: its `ParentId` is the first, and it has no `SourceId`. The same element under different parents (a linked model) is not supported. | +| Sibling pair | A Revit export may write one element twice under one parent. The first in stored order is the element; the second maps as a part: its `ParentId` is the first, and it has no `SourceId`. The same element under different parents is a linked placement: it becomes its own `SceneModel`, rooted at the placement or, for a shared subtree, at the highest group below the linking element or the root, with the same `SourceId` in that model. | | `SourceId` | The element's export GUID (`NwcNode.ElementGuid`) in format `D`, on element nodes only. This derivation does not change; a golden test pins it. | | `IfcGuid` | The element's IFC GlobalId (`NwcNode.IfcGlobalId`), on element nodes only. This derivation does not change; a golden test pins it. | | `Category`, `TypeName` | Revit files only, on `Element`-kind nodes only, by tree position: the category is the name at depth 2 on the path from the root, the type name the name at depth 4 when the element is at depth 5; otherwise empty. | @@ -89,7 +89,7 @@ A property with no text, a non-finite number, numeric text that does not parse, ## Limits -- `.nwd` partition trees and linked Revit models are not supported: `Read` throws `NotSupportedException`. +- `.nwd` partition trees (class 32) are not supported: `Read` throws `NotSupportedException`. Linked Revit placements are supported: each placement becomes its own `SceneModel`. - A `.nwf` file is read like a `.nwc` by `Read(string)`: the models it refers to are not loaded, so the scene holds only the content of the file itself (`xrefs-skipped`), and its `SourceFormat` is still `nwc`. Use `Read(NwcAssembly, ...)` with `NwcAssembly.OpenNwf` to convert the component models into one scene. - Level elevations are written in metres when the level carries its length parameter and the unit is known; otherwise they stay null. Saved viewpoints are written when their camera is finite and the document unit is known; otherwise they are reported with `viewpoints-skipped`. File viewpoints without the writer trailer (every Navisworks file) use an approximated projection, field of view and far distance (`viewpoint-camera-approximated`), and their section planes, section box, redlines and comments are not part of the scene (`viewpoint-content-skipped`). - Selection sets and search sets, the TimeLiner schedule and clash tests are not converted (`selection-sets-skipped`, `timeliner-skipped`, `clash-tests-skipped`). diff --git a/src/NwcIO.Cli/Program.cs b/src/NwcIO.Cli/Program.cs index 914e0d0..7cb0880 100644 --- a/src/NwcIO.Cli/Program.cs +++ b/src/NwcIO.Cli/Program.cs @@ -74,7 +74,7 @@ Reads Autodesk Navisworks files (.nwc, .nwd, .nwf) or assemblies of models --no-materials Disable material and surface color extraction --catalog Include raw container stream catalog (offsets, sizes, kinds) --no-transforms Exclude 3D transform matrices from JSON export - --no-tree Skip reading the scene tree and exclude it from JSON export (required to open a .nwd with partition nodes or a linked Revit model) + --no-tree Skip reading the scene tree and exclude it from JSON export (required to open a .nwd with partition nodes) --no-indent Write compact JSON instead of pretty-printed indented JSON --bvh-stats Include Bounding Volume Hierarchy (BVH) spatial index statistics --raycast Perform 3D raycast test: "originX,originY,originZ,dirX,dirY,dirZ" @@ -97,7 +97,7 @@ 2 File or folder not found 3 Data format error or parsing failure """; - // The reader throws NotSupportedException only for a scene tree it cannot convert (class-32 partition nodes, linked Revit models); --no-tree reads around both. + // The reader throws NotSupportedException only for a scene tree it cannot convert (class-32 partition nodes); --no-tree reads around it. private const string NoTreeHint = " Use --no-tree to read geometry and placement without the scene tree."; public static int Main(string[] args) => Run(args, null, null, null); diff --git a/src/NwcIO.Scene/NwcSceneReader.Geometry.cs b/src/NwcIO.Scene/NwcSceneReader.Geometry.cs index 7d8154f..8a5dd37 100644 --- a/src/NwcIO.Scene/NwcSceneReader.Geometry.cs +++ b/src/NwcIO.Scene/NwcSceneReader.Geometry.cs @@ -9,6 +9,25 @@ public static partial class NwcSceneReader { private const int MaxLineColourGroups = 64; // shortcut: segments of colours past 64 per record are drawn with the material colour; the corpus has 10 palette entries in all (spike-look (a)); raise it if a real file shows more + // The node a mesh counts for: the nearest linked placement at or above it inside its element, else its element, else the node itself. + private static NwcNode Owner(NwcNode node) + { + if (node.Element is not { } element) + { + return node; + } + + for (var n = node; n is not null; n = n.Parent) + { + if (ReferenceEquals(n, element) || n.IsLinkPlacement) + { + return n; + } + } + + return element; // the second node of a sibling pair: its element is a sibling, not an ancestor + } + // Writes the geometries, materials and instances of the document's meshes in their order, each made at first use; returns // the element of every placed mesh (its node's Element, or the node itself outside elements). private static HashSet AddGeometry(NwcDocument document, SceneDocument scene, double metresPerUnit, Dictionary ids, List diagnostics) @@ -65,7 +84,7 @@ private static HashSet AddGeometry(NwcDocument document, SceneDocument scene.Instances.Add(new SceneInstance { ElementId = elementId, GeometryId = geometryId, Transform = transform, MaterialId = materialId, Color = colour }); } - placed.Add(node.Element ?? node); + placed.Add(Owner(node)); } if (unplaced > 0) diff --git a/src/NwcIO.Scene/NwcSceneReader.cs b/src/NwcIO.Scene/NwcSceneReader.cs index c978b54..2c6d3bf 100644 --- a/src/NwcIO.Scene/NwcSceneReader.cs +++ b/src/NwcIO.Scene/NwcSceneReader.cs @@ -19,12 +19,14 @@ public static partial class NwcSceneReader private static readonly string Producer = "NwcIO.Scene " + typeof(NwcSceneReader).Assembly.GetCustomAttribute()!.InformationalVersion.Split('+')[0]; + private const int MaxModels = 100_000; // models in one scene, linked placements included + /// Reads the model file at with and converts it. /// The model file. /// Conversion options; null uses the defaults. /// The scene with a report of the conversion. /// or is empty. - /// The file's scene tree holds .nwd partition nodes or a Revit link. + /// The file's scene tree holds .nwd partition nodes. public static NwcSceneResult Read(string path, NwcSceneOptions? options = null) { ArgumentException.ThrowIfNullOrEmpty(path); @@ -41,7 +43,7 @@ public static NwcSceneResult Read(string path, NwcSceneOptions? options = null) } catch (NotSupportedException ex) { - throw new NotSupportedException("NwcIO.Scene needs the scene tree: .nwd partition trees and Revit links are not supported yet. " + ex.Message, ex); + throw new NotSupportedException("NwcIO.Scene needs the scene tree: .nwd partition trees are not supported yet. " + ex.Message, ex); } return Convert(document, key, path, options); @@ -62,6 +64,7 @@ public static NwcSceneResult Read(string path, NwcSceneOptions? options = null) /// /// is null or empty, or the document has no scene tree ( is null). /// + /// The linked placements would make the scene hold more than 100,000 models. public static NwcSceneResult Read(NwcDocument document, NwcSceneOptions options) { ArgumentNullException.ThrowIfNull(document); @@ -88,6 +91,7 @@ public static NwcSceneResult Read(NwcDocument document, NwcSceneOptions options) /// Conversion options; names the first converted model. /// The scene with a report of the conversion. /// The assembly has no models, or a model has no scene tree. + /// The documents and their linked placements together would make the scene hold more than 100,000 models. public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options = null) { ArgumentNullException.ThrowIfNull(assembly); @@ -108,16 +112,17 @@ public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options var scene = new SceneDocument { Title = assembly.Name }; var diagnostics = new List(); - var usedKeys = new HashSet(StringComparer.Ordinal); int elementCount = 0; int elementsWithGeometry = 0; NwcLengthUnit? commonUnit = null; bool mixedUnits = false; + var usedKeys = new HashSet(StringComparer.Ordinal); + var nextSuffix = new Dictionary(StringComparer.Ordinal); for (int i = 0; i < documents.Count; i++) { var document = documents[i]; - string key = ModelKey(document, i, options, usedKeys); + string key = ModelKey(document, i, options, usedKeys, nextSuffix); if (document.RootNode is null) { throw new ArgumentException( @@ -125,7 +130,7 @@ public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options nameof(assembly)); } - var result = ConvertInto(scene, document, key, document.LoadedPath, options, modelId: i + 1); + var result = ConvertInto(scene, document, key, document.LoadedPath, options, modelId: scene.Models.Count + 1, usedKeys, nextSuffix); diagnostics.AddRange(result.Diagnostics.Select(d => new SceneDiagnostic( d.Severity, d.Code, @@ -178,7 +183,12 @@ private static string XRefNames(IReadOnlyList references) => private static string? DocumentPath(NwcDocument document) => document.LoadedPath ?? document.FileInfo.SourcePath; - private static string ModelKey(NwcDocument document, int index, NwcSceneOptions? options, HashSet used) + private static string ModelKey( + NwcDocument document, + int index, + NwcSceneOptions? options, + HashSet used, + Dictionary nextSuffix) { string candidate = options?.ModelKey is { Length: > 0 } key && index == 0 ? key @@ -188,19 +198,36 @@ private static string ModelKey(NwcDocument document, int index, NwcSceneOptions? candidate = $"Model_{index + 1}"; } - string unique = candidate; - int suffix = 2; - while (!used.Add(unique)) + return UniqueModelKey(candidate, used, nextSuffix); + } + + private static string UniqueModelKey( + string candidate, + HashSet used, + Dictionary nextSuffix) + { + if (used.Add(candidate)) + { + return candidate; + } + + int suffix = nextSuffix.TryGetValue(candidate, out int next) ? next : 2; + string unique; + do { unique = $"{candidate}#{suffix++}"; } + while (!used.Add(unique)); + + nextSuffix[candidate] = suffix; return unique; } private static NwcSceneResult Convert(NwcDocument document, string key, string? path, NwcSceneOptions? options) { var scene = new SceneDocument { Title = key }; - return ConvertInto(scene, document, key, path, options, modelId: 1); + return ConvertInto(scene, document, key, path, options, modelId: 1, + new HashSet(StringComparer.Ordinal), new Dictionary(StringComparer.Ordinal)); } private static NwcSceneResult ConvertInto( @@ -209,10 +236,13 @@ private static NwcSceneResult ConvertInto( string key, string? path, NwcSceneOptions? options, - int modelId) + int modelId, + HashSet usedKeys, + Dictionary nextSuffix) { var unit = options?.LengthUnit ?? document.LengthUnit; string? loader = document.FileInfo.LoaderPlugin; + usedKeys.Add(key); scene.Models.Add(new SceneModel { Id = modelId, @@ -279,11 +309,11 @@ private static NwcSceneResult ConvertInto( } // Each item carries the names at depth 2 and 4 on its path and the depth of the node's element, for Category and TypeName. - var pending = new Stack<(NwcNode Node, NwcNode? Parent, int Depth, int? LevelId, int ElementDepth, string AtDepth2, string AtDepth4)>(); - pending.Push((root, null, 0, null, 0, "", "")); + var pending = new Stack<(NwcNode Node, NwcNode? Parent, int Depth, int? LevelId, int ElementDepth, string AtDepth2, string AtDepth4, int ModelId, int? LinkModelId)>(); + pending.Push((root, null, 0, null, 0, "", "", modelId, null)); while (pending.TryPop(out var item)) { - var (node, parent, depth, levelId, elementDepth, atDepth2, atDepth4) = item; + var (node, parent, depth, levelId, elementDepth, atDepth2, atDepth4, nodeModelId, linkModelId) = item; atDepth2 = depth == 2 ? node.Name : atDepth2; atDepth4 = depth == 4 ? node.Name : atDepth4; @@ -294,8 +324,46 @@ private static NwcSceneResult ConvertInto( elementDepth = depth; } + bool isLinkRoot = false; + if ((node.IsLinkRoot || node.IsLinkPlacement) && parent is not null && linkModelId is null) + { + if (scene.Models.Count >= MaxModels) + { + throw new InvalidDataException($"The scene would need more than {MaxModels} models."); + } + + nodeModelId = scene.Models.Count + 1; + string linkKey = UniqueModelKey( + string.IsNullOrWhiteSpace(node.Name) ? $"Link_{nodeModelId}" : node.Name, + usedKeys, + nextSuffix); + linkModelId = nodeModelId; + isLinkRoot = true; + scene.Models.Add(new SceneModel + { + Id = nodeModelId, + Key = linkKey, + Name = linkKey, + Path = null, + SourceFormat = "nwc", + Producer = Producer, + SourceLengthUnit = unit.GetSymbol(), + Application = loader?[(loader.LastIndexOf(':') + 1)..], + CreatedAt = document.FileInfo.SourceTimestampUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture), + }); + levelId = null; + } + else if (linkModelId is int enclosingLink) + { + nodeModelId = enclosingLink; + } + SceneNodeKind kind; - if (parent is null) + if (isLinkRoot) + { + kind = SceneNodeKind.Model; + } + else if (parent is null) { kind = SceneNodeKind.Model; } @@ -307,7 +375,7 @@ private static NwcSceneResult ConvertInto( scene.Levels.Add(new SceneLevel { Id = levelId.Value, - ModelId = modelId, + ModelId = nodeModelId, Name = node.Name, Elevation = levelElementId is not null && levelElevations.TryGetValue(levelElementId, out double elevation) ? elevation @@ -333,16 +401,19 @@ private static NwcSceneResult ConvertInto( { if (metresPerUnit is double m && lineMeshes.TryGetValue(node, out var meshes) && IsGrid(node) && GridLine(node, meshes, m) is { } gridLine) { - var gridSystem = scene.Grids.FirstOrDefault(g => g.ModelId == modelId); + var gridSystem = scene.Grids.FirstOrDefault(g => g.ModelId == nodeModelId); if (gridSystem is null) { - gridSystem = new SceneGridSystem { ModelId = modelId, Name = "Grids" }; + gridSystem = new SceneGridSystem { ModelId = nodeModelId, Name = "Grids" }; scene.Grids.Add(gridSystem); } gridSystem.Lines.Add(gridLine); } + } + if (node.IsElement || node.IsLinkPlacement) + { elementCount++; elementsWithGeometry += placed.Contains(node) ? 1 : 0; } @@ -357,18 +428,19 @@ private static NwcSceneResult ConvertInto( var (category, typeName) = !revit || kind != SceneNodeKind.Element ? ("", "") : (elementDepth == 2 ? (node.Element ?? node).Name : elementDepth > 2 ? atDepth2 : "", elementDepth == 5 ? atDepth4 : ""); - // The second node of a sibling pair is a part of the first. - long? parentId = parent is null ? null + // The second node of a sibling pair is a part of the first. A linked placement is a model root. + long? parentId = node.IsLinkPlacement ? null + : parent is null ? null : node.Element is { } owner && owner != node && owner != parent.Element ? ids.TryGetValue(owner, out long o) ? o : ids[parent] : ids[parent]; scene.Elements.Add(new SceneElement { Id = ids[node], - ModelId = modelId, + ModelId = nodeModelId, ParentId = parentId, Kind = kind, Name = node.Name, - SourceId = node.IsElement ? node.ElementGuid?.ToString("D") : null, - IfcGuid = node.IsElement ? node.IfcGlobalId : null, + SourceId = node.IsElement || node.IsLinkPlacement ? (node.Element ?? node).ElementGuid?.ToString("D") : null, + IfcGuid = node.IsElement || node.IsLinkPlacement ? (node.Element ?? node).IfcGlobalId : null, Category = category, TypeName = typeName, LevelId = levelId, @@ -377,7 +449,7 @@ private static NwcSceneResult ConvertInto( for (int i = node.Children.Count - 1; i >= 0; i--) { - pending.Push((node.Children[i], node, depth + 1, levelId, elementDepth, atDepth2, atDepth4)); + pending.Push((node.Children[i], node, depth + 1, levelId, elementDepth, atDepth2, atDepth4, nodeModelId, linkModelId)); } } diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs index d7e2c75..5464c45 100644 --- a/src/NwcIO/Internal/Parsing/HierarchyParser.cs +++ b/src/NwcIO/Internal/Parsing/HierarchyParser.cs @@ -44,7 +44,7 @@ internal static class HierarchyParser /// after the hierarchy tail. It returns null, or is null, when the file has no such segment; an empty list is a segment without streams. /// /// The nodes in preorder; [0] is the synthetic root (Id 0, Name , Class "Model", Tag 0). - /// One element index sits on nodes under different parents (a linked Revit model). + /// A partition (class-32) node or an unknown class is present. public static IReadOnlyList Read( byte[] data, string rootName, @@ -175,7 +175,26 @@ private static List Expand(Node[] top, string rootName, long total, boo } else { - throw new NotSupportedException("Revit links are not supported yet: one element index sits on nodes under different parents in LcOpNwdLogicalHierarchy."); + // A second placement of the same element under another parent is a linked Revit model. + // Keep it in the tree; the adapter can put each placement in its own scene model. + occurrence.Element = first; + occurrence.IsLinkPlacement = true; + // Mark one model root for the whole placed subtree: the element itself when it is a + // direct child, otherwise the highest group below the linking element or the root. + NwcNode linkRoot = parent; + while (linkRoot.Parent is not null && linkRoot.Parent.Id != 0 && !linkRoot.Parent.IsElement) + { + linkRoot = linkRoot.Parent; + } + + if (ReferenceEquals(linkRoot, parent) && (parent.Id == 0 || parent.IsElement)) + { + occurrence.IsLinkRoot = true; + } + else + { + linkRoot.IsLinkRoot = true; + } } parent.Children.Add(occurrence); diff --git a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs index e0e125a..4ab53ae 100644 --- a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs +++ b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs @@ -115,7 +115,7 @@ internal static class ModelGraphReader /// The tree first, so a tree that cannot be read fails before any geometry work; then geometry, fragments and links. /// A segment breaks its grammar or a fragment breaks a link rule. - /// The model's scene tree holds partition (class-32) nodes or places one Revit element under two parents (a linked model); open it with off. + /// The model's scene tree holds partition (class-32) nodes; open it with off. public static ModelGraph Read(ModelSegments segments, NwcReaderOptions options, string rootName) { // The tree needs the table for element GUIDs whatever ReadGuids says. diff --git a/src/NwcIO/Model/NwcNode.cs b/src/NwcIO/Model/NwcNode.cs index 2823557..c994bac 100644 --- a/src/NwcIO/Model/NwcNode.cs +++ b/src/NwcIO/Model/NwcNode.cs @@ -44,6 +44,16 @@ public sealed class NwcNode /// The element occurrence this node belongs to: itself when , else its parent's , or for the second node of a sibling pair that repeats one element the first node of the pair; null outside elements. public NwcNode? Element { get; set; } + /// + /// True when this node is a second placement of an element under another parent, which is how a linked + /// Revit model appears in the strict hierarchy. Its geometry is kept on this node; + /// points to the first placement. + /// + public bool IsLinkPlacement { get; set; } + + /// Root of a repeatedly placed (linked) subtree; only this node starts a scene model. + public bool IsLinkRoot { get; set; } + /// On a Revit element node: the GlobalId the Revit IFC export gives the element, its valid IFC_GUID parameter (tab LcRevitData_Element), else in the IFC base-64 form; null on other nodes. public string? IfcGlobalId { get; set; } diff --git a/src/NwcIO/NwcDocument.cs b/src/NwcIO/NwcDocument.cs index 3ea03ee..c95627d 100644 --- a/src/NwcIO/NwcDocument.cs +++ b/src/NwcIO/NwcDocument.cs @@ -118,7 +118,7 @@ private NwcDocument( /// The file does not exist. /// The file is not an LcUStream container, a stream exceeds or , or its DbCache directory names model segments that break the format. /// The container is larger than the 2 GiB a single in-memory buffer can hold. - /// The model's scene tree holds partition (class-32) nodes or places one Revit element under two parents (a linked model); open it with off. + /// The model's scene tree holds partition (class-32) nodes; open it with off. public static NwcDocument Open(string path, NwcReaderOptions? options = null) { if (!File.Exists(path)) @@ -135,7 +135,7 @@ public static NwcDocument Open(string path, NwcReaderOptions? options = null) /// Opens and parses a Navisworks file from a stream. /// The stream is not an LcUStream container, a stream exceeds or , or its DbCache directory names model segments that break the format. /// The container is larger than the 2 GiB a single in-memory buffer can hold. - /// The model's scene tree holds partition (class-32) nodes or places one Revit element under two parents (a linked model); open it with off. + /// The model's scene tree holds partition (class-32) nodes; open it with off. public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, string? fallbackName = null) { ArgumentNullException.ThrowIfNull(stream); diff --git a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs index 54d2e21..433a57f 100644 --- a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs +++ b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs @@ -53,7 +53,7 @@ public void Read_PartitionTree_ThrowsNotSupportedWithTheAdapterReason() w.Int(0).Int(0).Int(0).Int(0).Int(0).Int(0).Int(0).Int(0).Int(1); using var file = TempFile(SyntheticNwcFile.Build(w.ToArray(), null, [], []), "Site.nwd"); var ex = Assert.Throws(() => NwcSceneReader.Read(file.Path)); - Assert.StartsWith("NwcIO.Scene needs the scene tree: .nwd partition trees and Revit links are not supported yet. ", ex.Message); + Assert.StartsWith("NwcIO.Scene needs the scene tree: .nwd partition trees are not supported yet. ", ex.Message); Assert.IsType(ex.InnerException); } @@ -714,6 +714,192 @@ static NwcDocument Model(string sourcePath, int meshId, double x) } } + [Fact] + public void Read_LinkedPlacement_BecomesItsOwnSceneModel() + { + var root = new NwcNode { Id = 0, Name = "Root", Class = "Model" }; + var element = new NwcNode + { + Id = 1, + Name = "Element", + Class = "LcRevitData_Element", + IsElement = true, + ElementGuid = Guid.Parse("11111111-2222-4333-8444-555555555555"), + }; + element.Element = element; + var link = new NwcNode + { + Id = 2, + Name = "Link A", + Class = "LcOpModelFile", + Element = element, + IsLinkPlacement = true, + }; + root.Children.Add(element); + root.Children.Add(link); + + var elementMesh = Mesh(1, 0, element); + var linkMesh = Mesh(2, 10, link); + var document = NwcDocument.Create( + fileInfo: new NwcFileInfo { SourcePath = "model.nwc" }, + meshes: [elementMesh, linkMesh], + rootNode: root); + + var result = NwcSceneReader.Read(document, new NwcSceneOptions + { + ModelKey = "model.nwc", + LengthUnit = NwcLengthUnit.Meters, + }); + + Assert.Equal(2, result.Document.Models.Count); + Assert.Equal(2, result.Document.Models[1].Id); + Assert.Equal("Link A", result.Document.Models[1].Key); + Assert.Equal(2, result.Document.Instances.Count); + Assert.Equal(2, result.Document.Elements.Select(e => e.ModelId).Distinct().Count()); + Assert.All(result.Document.Elements.Where(e => e.ModelId == 2), + e => Assert.Equal("11111111-2222-4333-8444-555555555555", e.SourceId)); + Assert.Empty(result.Document.Validate()); + + static NwcMesh Mesh(int id, double x, NwcNode node) + { + var mesh = new NwcMesh + { + Id = id, + Vertices = [new NwcIO.Model.Vector3d(x, 0, 0), new NwcIO.Model.Vector3d(x + 1, 0, 0), new NwcIO.Model.Vector3d(x, 1, 0)], + Indices = [0, 1, 2], + BoundingBox = new NwcIO.Model.BoundingBox3d(new(x, 0, 0), new(x + 1, 1, 0)), + }; + mesh.Node = node; + node.Mesh = mesh; + return mesh; + } + } + + [Fact] + public void Read_SharedLinkedSubtree_BecomesOneModel() + { + var root = new NwcNode { Id = 0, Name = "Root", Class = "Model" }; + var first = new NwcNode { Id = 1, Name = "First", Class = "LcRevitData_Element", IsElement = true }; + first.Element = first; + var shared = new NwcNode { Id = 2, Name = "Shared model", Class = "LcOpModelFile", IsLinkRoot = true }; + for (int i = 0; i < 3; i++) + { + shared.Children.Add(new NwcNode + { + Id = 10 + i, + Name = $"Part {i + 1}", + Class = "LcRevitData_Element", + Element = first, + IsLinkPlacement = true, + }); + } + + root.Children.Add(first); + root.Children.Add(shared); + + var result = Valid(NwcSceneReader.Read(NwcDocument.Create(rootNode: root), new NwcSceneOptions + { + ModelKey = "model.nwc", + LengthUnit = NwcLengthUnit.Meters, + })); + + Assert.Equal(2, result.Document.Models.Count); + var linkModel = result.Document.Models[1]; + Assert.Equal("Shared model", linkModel.Key); + Assert.All(result.Document.Elements.Where(element => element.Name.StartsWith("Part ", StringComparison.Ordinal)), + element => Assert.Equal(linkModel.Id, element.ModelId)); + } + + [Fact] + public void Read_GeometryUnderALinkedPlacement_CountsThePlacementNotItsElement() + { + var root = new NwcNode { Id = 0, Name = "Root", Class = "Model" }; + var first = new NwcNode { Id = 1, Name = "First", Class = "LcRevitData_Element", IsElement = true, Parent = root }; + first.Element = first; + var link = new NwcNode { Id = 2, Name = "Link", Class = "LcOpModelFile", Element = first, IsLinkPlacement = true, IsLinkRoot = true, Parent = root }; + var part = new NwcNode { Id = 3, Name = "Part", Class = "LcRevitData_Element", Element = first, Parent = link }; + link.Children.Add(part); + root.Children.Add(first); + root.Children.Add(link); + + var result = Valid(NwcSceneReader.Read( + NwcDocument.Create(meshes: [Mesh(1, 0, first), Mesh(2, 10, part)], rootNode: root), + new NwcSceneOptions { ModelKey = "model.nwc", LengthUnit = NwcLengthUnit.Meters })); + + Assert.Equal(2, result.ElementCount); + Assert.Equal(2, result.ElementsWithGeometry); + + static NwcMesh Mesh(int id, double x, NwcNode node) + { + var mesh = new NwcMesh + { + Id = id, + Vertices = [new NwcIO.Model.Vector3d(x, 0, 0), new NwcIO.Model.Vector3d(x + 1, 0, 0), new NwcIO.Model.Vector3d(x, 1, 0)], + Indices = [0, 1, 2], + BoundingBox = new NwcIO.Model.BoundingBox3d(new(x, 0, 0), new(x + 1, 1, 0)), + }; + mesh.Node = node; + node.Mesh = mesh; + return mesh; + } + } + + [Fact] + public void Read_MoreLinkedPlacementsThanTheModelLimit_Throws() + { + var root = new NwcNode { Id = 0, Name = "Root", Class = "Model" }; + var first = new NwcNode { Id = 1, Name = "First", Class = "LcRevitData_Element", IsElement = true, Parent = root }; + first.Element = first; + root.Children.Add(first); + for (int i = 0; i < 100_000; i++) + { + root.Children.Add(new NwcNode { Id = i + 2, Name = "Link", Class = "LcOpModelFile", Element = first, IsLinkPlacement = true, IsLinkRoot = true, Parent = root }); + } + + var ex = Assert.Throws(() => NwcSceneReader.Read( + NwcDocument.Create(rootNode: root), + new NwcSceneOptions { ModelKey = "model.nwc", LengthUnit = NwcLengthUnit.Meters })); + Assert.Contains("100000", ex.Message); + } + + [Fact] + public void Read_LinkedSubtreesWithTheSameName_GetOneModelPerRoot() + { + var root = new NwcNode { Id = 0, Name = "Root", Class = "Model" }; + for (int i = 1; i <= 2; i++) + { + var link = new NwcNode + { + Id = i, + Name = "Linked model", + Class = "LcOpModelFile", + IsLinkPlacement = true, + }; + var child = new NwcNode + { + Id = 10 + i, + Name = $"Part {i}", + Class = "LcRevitData_Element", + IsElement = true, + Element = link, + }; + link.Children.Add(child); + root.Children.Add(link); + } + + var result = Valid(NwcSceneReader.Read(NwcDocument.Create(rootNode: root), new NwcSceneOptions + { + ModelKey = "model.nwc", + LengthUnit = NwcLengthUnit.Meters, + })); + + Assert.Equal(3, result.Document.Models.Count); + Assert.Equal(["model.nwc", "Linked model", "Linked model#2"], + result.Document.Models.Select(model => model.Key)); + Assert.Equal(2, result.Document.Elements.Single(element => element.Name == "Part 1").ModelId); + Assert.Equal(3, result.Document.Elements.Single(element => element.Name == "Part 2").ModelId); + } + [Fact] public void Read_AssemblyLoadedFromDirectory_UsesFileNamesForKeysAndPaths() { diff --git a/tests/NwcIO.Tests/ElementIdentityTests.cs b/tests/NwcIO.Tests/ElementIdentityTests.cs index df4b5ac..c50ca23 100644 --- a/tests/NwcIO.Tests/ElementIdentityTests.cs +++ b/tests/NwcIO.Tests/ElementIdentityTests.cs @@ -57,25 +57,46 @@ public void Open_ChildOfAPairsSecondNode_PointsToTheFirst() } [Fact] - public void Open_OneIndexUnderDifferentParents_ThrowsRevitLinks() + public void Open_OneIndexUnderDifferentParents_KeepsLinkedPlacement() { - var ex = Assert.Throws(() => Open([ + var doc = Open([ new("A", "LcRevitLayer", Children: [new("E", "LcRevitInstance", X: 1)]), - new("B", "LcRevitLayer", Children: [new("E", "LcRevitInstance", X: 1)])], [G1])); - Assert.StartsWith("Revit links are not supported yet", ex.Message); + new("B", "LcRevitLayer", Children: [new("E", "LcRevitInstance", X: 1)])], [G1]); + + var first = doc.RootNode!.Children[0].Children[0]; + var linked = doc.RootNode.Children[1].Children[0]; + Assert.True(first.IsElement); + Assert.False(linked.IsElement); + Assert.True(linked.IsLinkPlacement); + Assert.Same(first, linked.Element); + Assert.Null(linked.ElementGuid); } [Fact] - public void Open_ElementInASharedSubtree_ThrowsRevitLinks() + public void Open_ElementInASharedSubtree_KeepsLinkedPlacement() { var shared = new TreeNode("S", "LcRevitCollection", Children: [new("E", "LcRevitInstance", X: 1)]); - Assert.Throws(() => Open([new("A", "LcRevitLayer", Children: [shared]), new("B", "LcRevitLayer", Children: [shared])], [G1])); + var doc = Open([new("A", "LcRevitLayer", Children: [shared]), new("B", "LcRevitLayer", Children: [shared])], [G1]); + + var first = doc.RootNode!.Children[0].Children[0].Children[0]; + var linked = doc.RootNode.Children[1].Children[0].Children[0]; + Assert.True(first.IsElement); + Assert.True(linked.IsLinkPlacement); + Assert.Same(first, linked.Element); } [Fact] // design 6.2.1 made the outer node the element here; never seen in the corpus, so the plan rejects it (Decision 3) - public void Open_OneIndexOnANodeAndItsDescendant_ThrowsRevitLinks() => - Assert.Throws(() => Open([new("L", "LcRevitLayer", Children: [ - new("E", "LcRevitComposite", X: 1, Children: [new("P", "LcRevitInstance", X: 1)])])], [G1])); + public void Open_OneIndexOnANodeAndItsDescendant_KeepsLinkedPlacement() + { + var doc = Open([new("L", "LcRevitLayer", Children: [ + new("E", "LcRevitComposite", X: 1, Children: [new("P", "LcRevitInstance", X: 1)])])], [G1]); + + var element = doc.RootNode!.Children[0].Children[0]; + var linked = element.Children[0]; + Assert.True(element.IsElement); + Assert.True(linked.IsLinkPlacement); + Assert.Same(element, linked.Element); + } [Fact] // 309 of the 334 real pairs have siblings between them; a pair takes two equal table entries, the next index is X + 2 public void Open_SiblingPairWithASiblingBetween_StillPairs() diff --git a/tests/NwcIO.Tests/HierarchyParserTests.cs b/tests/NwcIO.Tests/HierarchyParserTests.cs index fcd8fa6..da62925 100644 --- a/tests/NwcIO.Tests/HierarchyParserTests.cs +++ b/tests/NwcIO.Tests/HierarchyParserTests.cs @@ -6,6 +6,49 @@ namespace NwcIO.Tests; public class HierarchyParserTests { + [Fact] + public void Read_DuplicateElementUnderDifferentParents_KeepsBothAsLinkedPlacement() + { + var wrote = Begin(1, 2); + Group(wrote, 1); + LeafWithX(wrote, 1); + Group(wrote, 1); + LeafWithX(wrote, 1); + var guids = new[] { Guid.NewGuid(), Guid.NewGuid() }; + + var nodes = HierarchyParser.Read(End(wrote), "Model", guids: guids); + + var first = nodes[2]; + var linked = nodes[4]; + Assert.True(first.IsElement); + Assert.False(linked.IsElement); + Assert.True(linked.IsLinkPlacement); + Assert.True(linked.Parent!.IsLinkRoot); + Assert.Same(first, linked.Element); + Assert.NotSame(first.Parent, linked.Parent); + Assert.Equal([first, linked], nodes[0].Children.SelectMany(g => g.Children)); + } + + [Fact] + public void Read_SeveralElementsRepeatedUnderOneGroup_MarkOnlyThatGroupAsLinkRoot() + { + var wrote = Begin(1, 2); + Group(wrote, 2); + LeafWithX(wrote, 1); + LeafWithX(wrote, 2); + Group(wrote, 2); + LeafWithX(wrote, 1); + LeafWithX(wrote, 2); + var guids = new[] { Guid.NewGuid(), Guid.NewGuid() }; + + var nodes = HierarchyParser.Read(End(wrote), "Model", guids: guids); + + var second = nodes[4]; + Assert.Equal(2, second.Children.Count); + Assert.All(second.Children, child => Assert.True(child.IsLinkPlacement)); + Assert.Same(second, Assert.Single(nodes, node => node.IsLinkRoot)); + } + [Fact] public void Read_H1_ExpandsBackReferencedSubtreeInPreorder() { @@ -514,6 +557,14 @@ internal static void Leaf(LcGraphWriter w, int attributeCount, Action attributes, int k = 1) {