From 8b3da271924dedddbe3508ad867a28b26fc6ffed Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 09:48:43 +0300 Subject: [PATCH 1/5] feat(scene): keep linked Revit placements and split them into models HierarchyParser no longer throws for a repeated element under another parent: the node is kept, marked NwcNode.IsLinkPlacement, and points at the first placement. NwcSceneReader starts a new SceneModel for each linked placement, uses the placement as the model root, preserves its geometry and SourceId, and gives its descendants the link model id. Update docs and the old throw-based tests; add parser and scene regressions with SceneDocument.Validate(). --- CHANGELOG.md | 1 + docs/format-notes.md | 2 +- docs/getting-started.md | 7 +- docs/public-api.md | 2 +- docs/scene.md | 4 +- src/NwcIO.Scene/NwcSceneReader.Geometry.cs | 1 + src/NwcIO.Scene/NwcSceneReader.cs | 71 ++++++++++++++----- src/NwcIO/Internal/Parsing/HierarchyParser.cs | 7 +- src/NwcIO/Model/NwcNode.cs | 7 ++ src/NwcIO/NwcDocument.cs | 4 +- .../NwcIO.Scene.Tests/NwcSceneReaderTests.cs | 63 +++++++++++++++- tests/NwcIO.Tests/ElementIdentityTests.cs | 39 +++++++--- tests/NwcIO.Tests/HierarchyParserTests.cs | 30 ++++++++ 13 files changed, 198 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df8cb15..48fdfd6 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` converts saved viewpoints to `SceneViewpoint`s (camera position, target, up, field of view in radians, near/far in metres and projection), and writes Revit level elevations in metres. - `NwcIO.Scene` diagnostics for document content the conversion leaves out: `xrefs-skipped` (Warning, with the number of external references, for example the models of a `.nwf` file), `selection-sets-skipped`, `timeliner-skipped` and `clash-tests-skipped` (Warning, each only when the document has that content), and `properties-skipped` (Info, the number of property values left out for a reason other than an unknown unit). A document with none of this content gets none of them. diff --git a/docs/format-notes.md b/docs/format-notes.md index 6814272..b670394 100644 --- a/docs/format-notes.md +++ b/docs/format-notes.md @@ -58,7 +58,7 @@ Once inflated, streams serve dedicated roles identified by their signature prefi - **Classes**: - `53` group: `[str name][ptr 52 username][i32 flags][i32 X][i32 Y][Y x attribute ptr][i32 c][c x child ptr]`. Children are class 22 or 53 and are never null. - `22` leaf: the same layout without `c` and children. - - `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 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 5faca74..9b4ac44 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 d9edcb8..8001c80 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, triangles other than the single strip the reader rebuilds, out-of-range vertex counts or coordinates, records or nodes without a name/class, and viewpoint names the reader would rename. Normals, materials and mesh names are not stored. | | `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, assigned by heuristics elsewhere), whether to build the scene tree (`BuildSceneTree`), catalog retention. | diff --git a/docs/scene.md b/docs/scene.md index afbf7b9..107abec 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`, with the placement as the model root and 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. | @@ -87,7 +87,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 file holds them. Saved viewpoints are written when their camera is finite and the document unit is known; otherwise they are reported with `viewpoints-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.Scene/NwcSceneReader.Geometry.cs b/src/NwcIO.Scene/NwcSceneReader.Geometry.cs index 7d8154f..e509f67 100644 --- a/src/NwcIO.Scene/NwcSceneReader.Geometry.cs +++ b/src/NwcIO.Scene/NwcSceneReader.Geometry.cs @@ -66,6 +66,7 @@ private static HashSet AddGeometry(NwcDocument document, SceneDocument } placed.Add(node.Element ?? node); + placed.Add(node); } if (unplaced > 0) diff --git a/src/NwcIO.Scene/NwcSceneReader.cs b/src/NwcIO.Scene/NwcSceneReader.cs index ed26c44..ba8e81d 100644 --- a/src/NwcIO.Scene/NwcSceneReader.cs +++ b/src/NwcIO.Scene/NwcSceneReader.cs @@ -24,7 +24,7 @@ public static partial class NwcSceneReader /// 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 +41,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); @@ -108,7 +108,6 @@ 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; @@ -117,7 +116,7 @@ public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options 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, scene); if (document.RootNode is null) { throw new ArgumentException( @@ -125,7 +124,7 @@ public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options nameof(assembly)); } - var result = ConvertInto(scene, document, key, document.FileInfo.SourcePath, options, modelId: i + 1); + var result = ConvertInto(scene, document, key, document.FileInfo.SourcePath, options, modelId: scene.Models.Count + 1); diagnostics.AddRange(result.Diagnostics.Select(d => new SceneDiagnostic( d.Severity, d.Code, @@ -157,7 +156,7 @@ public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options }; } - private static string ModelKey(NwcDocument document, int index, NwcSceneOptions? options, HashSet used) + private static string ModelKey(NwcDocument document, int index, NwcSceneOptions? options, SceneDocument scene) { string candidate = options?.ModelKey is { Length: > 0 } key && index == 0 ? key @@ -167,6 +166,12 @@ private static string ModelKey(NwcDocument document, int index, NwcSceneOptions? candidate = $"Model_{index + 1}"; } + return UniqueModelKey(scene, candidate); + } + + private static string UniqueModelKey(SceneDocument scene, string candidate) + { + var used = new HashSet(scene.Models.Select(m => m.Key), StringComparer.Ordinal); string unique = candidate; int suffix = 2; while (!used.Add(unique)) @@ -258,11 +263,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)>(); + pending.Push((root, null, 0, null, 0, "", "", modelId)); while (pending.TryPop(out var item)) { - var (node, parent, depth, levelId, elementDepth, atDepth2, atDepth4) = item; + var (node, parent, depth, levelId, elementDepth, atDepth2, atDepth4, nodeModelId) = item; atDepth2 = depth == 2 ? node.Name : atDepth2; atDepth4 = depth == 4 ? node.Name : atDepth4; @@ -273,8 +278,32 @@ private static NwcSceneResult ConvertInto( elementDepth = depth; } + if (node.IsLinkPlacement && parent is not null) + { + nodeModelId = scene.Models.Count + 1; + string linkKey = UniqueModelKey(scene, + string.IsNullOrWhiteSpace(node.Name) ? $"Link_{nodeModelId}" : node.Name); + 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; + } + SceneNodeKind kind; - if (parent is null) + if (node.IsLinkPlacement) + { + kind = SceneNodeKind.Model; + } + else if (parent is null) { kind = SceneNodeKind.Model; } @@ -286,7 +315,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 @@ -312,16 +341,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; } @@ -336,18 +368,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, @@ -356,7 +389,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)); } } diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs index d7e2c75..210975e 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,10 @@ 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; } parent.Children.Add(occurrence); diff --git a/src/NwcIO/Model/NwcNode.cs b/src/NwcIO/Model/NwcNode.cs index 2823557..c37e61a 100644 --- a/src/NwcIO/Model/NwcNode.cs +++ b/src/NwcIO/Model/NwcNode.cs @@ -44,6 +44,13 @@ 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; } + /// 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 ecb704e..7fcdfbc 100644 --- a/src/NwcIO/NwcDocument.cs +++ b/src/NwcIO/NwcDocument.cs @@ -114,7 +114,7 @@ private NwcDocument( /// Opens and parses a Navisworks file from disk. /// The file does not exist. /// The file is not an LcUStream container, or its DbCache directory names model segments that break the format. - /// 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)) @@ -130,7 +130,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, or its DbCache directory names model segments that break the format. - /// 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 084fa47..f509ec4 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); } @@ -664,6 +664,67 @@ 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_FileWithSavedViews_SkipsThemWithAWarning() { 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..1ec3ea3 100644 --- a/tests/NwcIO.Tests/HierarchyParserTests.cs +++ b/tests/NwcIO.Tests/HierarchyParserTests.cs @@ -6,6 +6,28 @@ 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.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_H1_ExpandsBackReferencedSubtreeInPreorder() { @@ -514,6 +536,14 @@ internal static void Leaf(LcGraphWriter w, int attributeCount, Action attributes, int k = 1) { From 3bb95127c4d981719dc4776e7d49eefe7055001d Mon Sep 17 00:00:00 2001 From: sim Date: Mon, 16 Nov 2026 12:53:19 +0300 Subject: [PATCH 2/5] fix(scene): allocate model keys once and keep link subtrees together Share one key set and suffix map per conversion, cap linked models, and create one model per top-level link placement so repeat elements inside a linked subtree stay in that model. --- src/NwcIO.Scene/NwcSceneReader.cs | 77 ++++++++++++++----- .../NwcIO.Scene.Tests/NwcSceneReaderTests.cs | 38 +++++++++ 2 files changed, 96 insertions(+), 19 deletions(-) diff --git a/src/NwcIO.Scene/NwcSceneReader.cs b/src/NwcIO.Scene/NwcSceneReader.cs index ba8e81d..f380eea 100644 --- a/src/NwcIO.Scene/NwcSceneReader.cs +++ b/src/NwcIO.Scene/NwcSceneReader.cs @@ -19,6 +19,8 @@ public static partial class NwcSceneReader private static readonly string Producer = "NwcIO.Scene " + typeof(NwcSceneReader).Assembly.GetCustomAttribute()!.InformationalVersion.Split('+')[0]; + private const int MaxLinkModels = 100_000; + /// Reads the model file at with and converts it. /// The model file. /// Conversion options; null uses the defaults. @@ -112,11 +114,13 @@ public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options 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, scene); + string key = ModelKey(document, i, options, usedKeys, nextSuffix); if (document.RootNode is null) { throw new ArgumentException( @@ -124,7 +128,7 @@ public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options nameof(assembly)); } - var result = ConvertInto(scene, document, key, document.FileInfo.SourcePath, options, modelId: scene.Models.Count + 1); + var result = ConvertInto(scene, document, key, document.FileInfo.SourcePath, options, modelId: scene.Models.Count + 1, usedKeys, nextSuffix); diagnostics.AddRange(result.Diagnostics.Select(d => new SceneDiagnostic( d.Severity, d.Code, @@ -156,7 +160,12 @@ public static NwcSceneResult Read(NwcAssembly assembly, NwcSceneOptions? options }; } - private static string ModelKey(NwcDocument document, int index, NwcSceneOptions? options, SceneDocument scene) + 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 @@ -166,25 +175,36 @@ private static string ModelKey(NwcDocument document, int index, NwcSceneOptions? candidate = $"Model_{index + 1}"; } - return UniqueModelKey(scene, candidate); + return UniqueModelKey(candidate, used, nextSuffix); } - private static string UniqueModelKey(SceneDocument scene, string candidate) + private static string UniqueModelKey( + string candidate, + HashSet used, + Dictionary nextSuffix) { - var used = new HashSet(scene.Models.Select(m => m.Key), StringComparer.Ordinal); - string unique = candidate; - int suffix = 2; - while (!used.Add(unique)) + 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( @@ -193,10 +213,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, @@ -263,11 +286,12 @@ 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, int ModelId)>(); - pending.Push((root, null, 0, null, 0, "", "", modelId)); + 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)); + int linkModels = 0; while (pending.TryPop(out var item)) { - var (node, parent, depth, levelId, elementDepth, atDepth2, atDepth4, nodeModelId) = item; + var (node, parent, depth, levelId, elementDepth, atDepth2, atDepth4, nodeModelId, linkModelId) = item; atDepth2 = depth == 2 ? node.Name : atDepth2; atDepth4 = depth == 4 ? node.Name : atDepth4; @@ -278,11 +302,22 @@ private static NwcSceneResult ConvertInto( elementDepth = depth; } - if (node.IsLinkPlacement && parent is not null) + bool isLinkRoot = false; + if (node.IsLinkPlacement && parent is not null && linkModelId is null) { + if (++linkModels > MaxLinkModels) + { + throw new InvalidDataException( + $"The scene would need more than {MaxLinkModels} linked models."); + } + nodeModelId = scene.Models.Count + 1; - string linkKey = UniqueModelKey(scene, - string.IsNullOrWhiteSpace(node.Name) ? $"Link_{nodeModelId}" : node.Name); + string linkKey = UniqueModelKey( + string.IsNullOrWhiteSpace(node.Name) ? $"Link_{nodeModelId}" : node.Name, + usedKeys, + nextSuffix); + linkModelId = nodeModelId; + isLinkRoot = true; scene.Models.Add(new SceneModel { Id = nodeModelId, @@ -297,9 +332,13 @@ private static NwcSceneResult ConvertInto( }); levelId = null; } + else if (linkModelId is int enclosingLink) + { + nodeModelId = enclosingLink; + } SceneNodeKind kind; - if (node.IsLinkPlacement) + if (isLinkRoot) { kind = SceneNodeKind.Model; } @@ -389,7 +428,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, nodeModelId)); + pending.Push((node.Children[i], node, depth + 1, levelId, elementDepth, atDepth2, atDepth4, nodeModelId, linkModelId)); } } diff --git a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs index f509ec4..95fec2b 100644 --- a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs +++ b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs @@ -725,6 +725,44 @@ static NwcMesh Mesh(int id, double x, NwcNode node) } } + [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_FileWithSavedViews_SkipsThemWithAWarning() { From 982ef33feca23ffc8c65b4d1327355517c9eb391 Mon Sep 17 00:00:00 2001 From: sim Date: Mon, 16 Nov 2026 15:37:36 +0300 Subject: [PATCH 3/5] fix(scene): mark one root for a shared linked subtree HierarchyParser now marks the highest group below a linking element (or the element itself) as IsLinkRoot; NwcSceneReader creates one model for that root and reuses it for every repeated element inside. Cover a shared subtree with three elements and a single linked group. --- src/NwcIO.Scene/NwcSceneReader.cs | 2 +- src/NwcIO/Internal/Parsing/HierarchyParser.cs | 16 +++++++++ src/NwcIO/Model/NwcNode.cs | 3 ++ .../NwcIO.Scene.Tests/NwcSceneReaderTests.cs | 35 +++++++++++++++++++ tests/NwcIO.Tests/HierarchyParserTests.cs | 1 + 5 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/NwcIO.Scene/NwcSceneReader.cs b/src/NwcIO.Scene/NwcSceneReader.cs index f380eea..cb47d0c 100644 --- a/src/NwcIO.Scene/NwcSceneReader.cs +++ b/src/NwcIO.Scene/NwcSceneReader.cs @@ -303,7 +303,7 @@ private static NwcSceneResult ConvertInto( } bool isLinkRoot = false; - if (node.IsLinkPlacement && parent is not null && linkModelId is null) + if ((node.IsLinkRoot || node.IsLinkPlacement) && parent is not null && linkModelId is null) { if (++linkModels > MaxLinkModels) { diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs index 210975e..5464c45 100644 --- a/src/NwcIO/Internal/Parsing/HierarchyParser.cs +++ b/src/NwcIO/Internal/Parsing/HierarchyParser.cs @@ -179,6 +179,22 @@ private static List Expand(Node[] top, string rootName, long total, boo // 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/Model/NwcNode.cs b/src/NwcIO/Model/NwcNode.cs index c37e61a..c994bac 100644 --- a/src/NwcIO/Model/NwcNode.cs +++ b/src/NwcIO/Model/NwcNode.cs @@ -51,6 +51,9 @@ public sealed class NwcNode /// 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/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs index 95fec2b..3946d5c 100644 --- a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs +++ b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs @@ -725,6 +725,41 @@ static NwcMesh Mesh(int id, double x, NwcNode node) } } + [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_LinkedSubtreesWithTheSameName_GetOneModelPerRoot() { diff --git a/tests/NwcIO.Tests/HierarchyParserTests.cs b/tests/NwcIO.Tests/HierarchyParserTests.cs index 1ec3ea3..fc39b91 100644 --- a/tests/NwcIO.Tests/HierarchyParserTests.cs +++ b/tests/NwcIO.Tests/HierarchyParserTests.cs @@ -23,6 +23,7 @@ public void Read_DuplicateElementUnderDifferentParents_KeepsBothAsLinkedPlacemen 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)); From e14f31b1c89eb413a3a443d35d69b9a9d718bc4e Mon Sep 17 00:00:00 2001 From: sim Date: Mon, 16 Nov 2026 22:44:45 +0300 Subject: [PATCH 4/5] fix(scene): count a linked placement's own geometry, cap the model total and document the shared-subtree model root --- docs/scene.md | 2 +- src/NwcIO.Scene/NwcSceneReader.Geometry.cs | 22 +++++++- src/NwcIO.Scene/NwcSceneReader.cs | 10 ++-- .../NwcIO.Scene.Tests/NwcSceneReaderTests.cs | 52 +++++++++++++++++++ tests/NwcIO.Tests/HierarchyParserTests.cs | 20 +++++++ 5 files changed, 98 insertions(+), 8 deletions(-) diff --git a/docs/scene.md b/docs/scene.md index 107abec..aaf00ad 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 is a linked placement: it becomes its own `SceneModel`, with the placement as the model root and the same `SourceId` in that model. | +| 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. | diff --git a/src/NwcIO.Scene/NwcSceneReader.Geometry.cs b/src/NwcIO.Scene/NwcSceneReader.Geometry.cs index e509f67..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,8 +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(node); + placed.Add(Owner(node)); } if (unplaced > 0) diff --git a/src/NwcIO.Scene/NwcSceneReader.cs b/src/NwcIO.Scene/NwcSceneReader.cs index cb47d0c..c6eb997 100644 --- a/src/NwcIO.Scene/NwcSceneReader.cs +++ b/src/NwcIO.Scene/NwcSceneReader.cs @@ -19,7 +19,7 @@ public static partial class NwcSceneReader private static readonly string Producer = "NwcIO.Scene " + typeof(NwcSceneReader).Assembly.GetCustomAttribute()!.InformationalVersion.Split('+')[0]; - private const int MaxLinkModels = 100_000; + 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. @@ -64,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); @@ -90,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); @@ -288,7 +290,6 @@ 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, int ModelId, int? LinkModelId)>(); pending.Push((root, null, 0, null, 0, "", "", modelId, null)); - int linkModels = 0; while (pending.TryPop(out var item)) { var (node, parent, depth, levelId, elementDepth, atDepth2, atDepth4, nodeModelId, linkModelId) = item; @@ -305,10 +306,9 @@ private static NwcSceneResult ConvertInto( bool isLinkRoot = false; if ((node.IsLinkRoot || node.IsLinkPlacement) && parent is not null && linkModelId is null) { - if (++linkModels > MaxLinkModels) + if (scene.Models.Count >= MaxModels) { - throw new InvalidDataException( - $"The scene would need more than {MaxLinkModels} linked models."); + throw new InvalidDataException($"The scene would need more than {MaxModels} models."); } nodeModelId = scene.Models.Count + 1; diff --git a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs index 3946d5c..fb4a781 100644 --- a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs +++ b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs @@ -760,6 +760,58 @@ public void Read_SharedLinkedSubtree_BecomesOneModel() 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() { diff --git a/tests/NwcIO.Tests/HierarchyParserTests.cs b/tests/NwcIO.Tests/HierarchyParserTests.cs index fc39b91..da62925 100644 --- a/tests/NwcIO.Tests/HierarchyParserTests.cs +++ b/tests/NwcIO.Tests/HierarchyParserTests.cs @@ -29,6 +29,26 @@ public void Read_DuplicateElementUnderDifferentParents_KeepsBothAsLinkedPlacemen 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() { From 17f7f86a836f8160a57220841b4dae1ffbcb5b41 Mon Sep 17 00:00:00 2001 From: sim Date: Mon, 16 Nov 2026 22:45:05 +0300 Subject: [PATCH 5/5] docs: linked Revit placements are read, not rejected --- README.md | 4 ++-- src/NwcIO.Cli/Program.cs | 4 ++-- src/NwcIO/Internal/Parsing/ModelGraphReader.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 3d47926..7416ec0 100644 --- a/README.md +++ b/README.md @@ -154,13 +154,13 @@ The documentation site with API references and guides is at Perform 3D raycast test: "originX,originY,originZ,dirX,dirY,dirZ" @@ -83,7 +83,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/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.