diff --git a/CHANGELOG.md b/CHANGELOG.md index 178f765..d3a1358 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte - Read IFC string properties and class-96 point geometry in Navisworks model files. The scene adapter preserves point geometry (#291). - Read the scene tree of NWD files that store lights in the partition trailer. +- Open mixed IFC/DWG NWD files with named materials, shared assets, 64-bit properties and CAD text geometry. Preserve CAD annotation text, bounds and placement in the read model. ## [0.18.0] - 2026-11-23 diff --git a/docs/format-notes.md b/docs/format-notes.md index 6954344..b877457 100644 --- a/docs/format-notes.md +++ b/docs/format-notes.md @@ -64,9 +64,10 @@ Once inflated, streams serve dedicated roles identified by their signature prefi - `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 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`): `[str]` (empty in every file seen), a class-53 body whose name is the partition's source file name, then a trailer. Class 32 nodes are the top-level children of a `.nwd`; class 53 nodes are the top-level children of a `.nwc`. The cache's separate `LcOpNwdPartition` stream starts directly with a class-32 pointer and omits the children's count and slots. Its trailer starts with the light count and light objects, followed by source metadata. Its grammar is `[i32 2][i32 n] n x ptr27 3 x f64 [i32][str loader plugin][i32 format version][i32][i32] 6 x f64 [i32][str][i32][str source path] 3 x f64 4 x f64 [i32][i32]`. The last four doubles describe a plan box. - - `27` partition light: `[i32 1][i32 selector (0 or 1) or new ptr185][13 x f64]`. The class-185 asset uses the same layout as material JSON. Lights are read and skipped. + - `27` partition light: `[i32 1][i32 selector (0 or 1), new ptr185 or shared asset index][13 x f64]`. The class-185 asset uses the same layout as material JSON. Lights are read and skipped. - `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. +- **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,6,7,10,11` `f64`, `5,15` `i64` (Unix seconds and signed integer, respectively), `2,3` `i32`, `4` and `9` string (type 9 was never seen; it is read as a string), `8` class-52 pointer, `12,13` three or two `f64` coordinates; `31` material; `40` translation; `41` translation and quaternion (`x -> R(q)x + t`); `39` 3x3 column-major matrix and translation; `79` hyperlinks; `200` wraps an inline or shared class-185 material asset (§2.4). +- **Class 31 material**: `[str name][15 x f64]`. The DWG variant is `[str name][ptr 52 username][i32 zero][14 x f64]`. Its username can be a new object or a back-reference. - **Shared subtrees**: a child pointer may back-reference an earlier node, so the hierarchy is a directed acyclic graph. A node reached through several parents appears once per path when the tree is expanded. - **Preorder index (`seq`)**: walk from the implicit root in stored order, counting groups, with a shared subtree walked again at every place it occurs. The root has index 0. Every fragment's `seq` indexes this expanded sequence and lands on a leaf; `seq` never decreases along the fragments stream, and a leaf owns one contiguous run of fragments. @@ -79,12 +80,12 @@ ZTOC := [int32 k] [k x int32 compressed length of ZSTREAM i] zero pad to 8 HIERARCHY HEADER := [int32 k >= 1] [k x int32 n_i] n_i = number of roots in ZSTREAM i ZSTREAM i := ROOT{n_i} zero pad to 8 ids from 100 per stream, no implicit root ROOT := a new object (never null, never a back-reference) of class 86, 79, 66 or 70; nested objects are class 52 -66 := [str name = null] [ptr 52 key, internal "LcRevitId"] [i32 flags = 0x01000000 or 0x00020000] PAD8 [i64 value in 1..2^31-1] +66 := [str name = null] [ptr 52 key] [i32 flags] PAD8 [i64 value] 70 := [str value] [ptr 52 key] [i32 flags] LINK := the n-th null attribute slot of a hierarchy node, in byte order, takes the n-th root of ZSTREAM 0 ‖ ZSTREAM 1 ‖ ... ``` -The roots are the tabs a node uses once (element, parameter, type, material and room tabs) and its element id; tabs shared by two or more nodes stay in the hierarchy. A class-66 root becomes a one-property tab named by its key (`LcRevitId`). The per-node order the exporter writes (`86* 79? 66?`, the 66 last) is not enforced. +The roots are the tabs a node uses once (element, parameter, type, material and room tabs) and its element id; tabs shared by two or more nodes stay in the hierarchy. A class-66 root becomes a one-property tab named by its key. Revit IDs use flags `0x01000000` or `0x00020000` and values in `1..2^31-1`. DWG handles (`LcOpDwgEntityAttrib`) accept flags `0`, `0x02000000` and `0x03000000` as well and retain their 64-bit value. Handles already accepted under the legacy flags and range keep their existing type-2 representation. The per-node order the exporter writes (`86* 79? 66?`, the 66 last) is not enforced. ### 2.2.2 Lenient fallback scene tree @@ -113,9 +114,9 @@ The nesting is therefore independent of the exporter UI language for the marker - `14` pose: `[3 x f64 t]`, a translation (identity rotation, scale 1). The Revit NWC exporter writes it for unrotated poses. - `15` pose: `[3 x f64 t][4 x f64 q]`, `q = (x, y, z, w)` a unit quaternion. - `16` pose with scale: class 15 plus `[f64 s]`. The scale is a uniform factor and can be negative. - - `55` appearance: `[i32 flags][ptr 54]`, plus a material-asset slot when `flags & 32`. The slot is null, a class-185 object pointer, or a single shared index (`2..99`) into `LcOpSharedNodes`. The shared stream starts with a count followed by indexed pointers. An appearance with flags `0x71` has one trailing zero word in a Navisworks 2027 file saved after editing the diffuse image. + - `55` appearance: `[i32 flags][ptr 54]`, plus a material-asset slot when `flags & 32`. The slot is null, a class-185 object pointer, or a single shared index (2 or higher) into `LcOpSharedNodes`. The shared stream starts with a count followed by zero-based indexed pointers to class-185 assets or class-102 fonts. A class-102 font stores `[str name][f64][4 x i32]`. A valid new class-185 pointer takes precedence over a shared index with the same lead word. An appearance with flags `0x71` has one trailing zero word in a Navisworks 2027 file saved after editing the diffuse image. - `185` material asset: `[str JSON][str metadata][i32 count]`, then `count` items `[str name][i32 embedded][str path]`; an embedded item adds `[str name][i64 length][payload padded to 4]`. For the Generic diffuse image, `userassets` identifies the root key in `materials`. Its enabled `properties.colors.generic_diffuse.connections` identifies the `UnifiedBitmap` entry. `properties.uris.unifiedbitmap_Bitmap.values` supplies the path. The reader looks up that path in the XRef table and prefers the matching record's `RemappedPath` when present. Thumbnail URIs and unrelated bitmap nodes are ignored. - - `54` material: 14 `f32`: ambient 0–2, diffuse 3–5, specular 6–8 (always 0), emissive 9–11 (always 0), shininess 12 (Revit Shininess / 128), transparency 13 (Revit Transparency / 100, values below 0.1 stored as 0). Channels are quantised to bytes. `31` (hierarchy) repeats the fields as `f64` and names the material (null for rooms). + - `54` material: 14 `f32`: ambient 0–2, diffuse 3–5, specular 6–8 (always 0), emissive 9–11 (always 0), shininess 12 (Revit Shininess / 128), transparency 13 (Revit Transparency / 100, values below 0.1 stored as 0). Channels are quantised to bytes. `31` (hierarchy) uses `f64` fields and names the material (§2.2). - `93` geometry reference: `[6 x f32 bbox][3 x f64 c][f32][i32 key][i32 rec]`. `rec` is the 1-based index of a geometry record (§2.5). The box equals the bounding box of the record's positions, and `c` is the offset of those positions: for a posed fragment it is the pose translation in the partition's frame, and it places a fragment without a pose. - **Placement**: the fragment pose is the full world transform of the record's positions: `world = s·R(q)·v + t`, with `s = 1` for classes 14 and 15 and `R(q)` the identity for class 14. `R(q)` is the usual rotation matrix of the normalised quaternion. No unit conversion is applied. - **Mirroring**: a pose with `s < 0` mirrors the geometry, so triangle winding must be reversed to keep faces outward in world space. Local vertices and indices are not changed. @@ -151,7 +152,7 @@ UVBODY := [p1][fc][fc x f32] TOKENS(p1, fc/2)? (raw; tokens iff fc/2 != p ``` - **Colour palette**: entries are `[A=0xFF][B][G][R]` (a little-endian `uint32` `0xRRGGBBAA`). Evidence: a level's line colour equals its type's colour parameter (a Revit colour int, red in the low byte) in 218 of 218 level lines that are not black; the 95 whose colour tells the orders apart all match this order. A line record can carry several colours, per vertex. -- **Class**: `94` triangles, `95` lines, `96` points. Class 94 always has a normal slot; classes 95 and 96 never have a UV or normal slot. The colour slot is optional (`.nwd` files saved by Navisworks 2026 have triangle records with one and line records without one): a triangle record's colours are read for length and dropped, and a line record without colours falls back to its material colour. Object ids run 100, 101, then 102, 103 over the slots present. +- **Class**: `94` triangles, `95` lines, `96` points, `103` text. Class 94 always has a normal slot; classes 95 and 96 never have a UV or normal slot. The colour slot is optional (`.nwd` files saved by Navisworks 2026 have triangle records with one and line records without one): a triangle record's colours are read for length and dropped, and a line record without colours falls back to its material colour. Object ids run 100, 101, then 102, 103 over the slots present. - **`p1` is the render-vertex count**, not the position count. `p2/3` positions are stored; `VMAP` maps each render vertex to a position and is the identity when absent. Quantised positions (negative `p1`) are not supported. - **PACKED(count, w)**: bit `j` of the stream is bit `31 - j%32` of little-endian word `j/32`; value `k` occupies bits `k*w` to `k*w+w-1`, most significant first. - **TOKENS(count, fresh)**: one byte code for every map. State: `out = []`, `next = 0`; read lead bytes until `count` values exist. @@ -169,8 +170,10 @@ UVBODY := [p1][fc][fc x f32] TOKENS(p1, fc/2)? (raw; tokens iff fc/2 != p - **Normals** (class 94): a palette entry is three two's-complement values of width `B`, divided by `2^(B-1)-1` and normalised; a zero vector means no normal. `B` is not stored in the record: it is the width under which every record of the file parses (16 for `.nwc`, 8 for `.nwd`). Render vertex `r` takes `palette[NIdx[r]]`, or an axis vector for an axis code (`D0` +X, `D1` -X, `D2` +Y, `D3` -Y, `D4` +Z, `D5` -Z). - **Triangles** (class 94): corners are `0..p1-1` when `S = 0`, otherwise `TOKENS(S, p1)`. They are split by `L` into consecutive strips; in each strip, triangle `i` is `(c[i], c[i+1], c[i+2])` for even `i` and `(c[i+1], c[i], c[i+2])` for odd `i`. Parity restarts in every strip. The triangle count is the sum of `L-2`. Front faces are counter-clockwise. - **Polylines** (class 95): render vertices `0..p1-1` are split by `L` into open polylines; the segment count is the sum of `L-1`. There is no implicit closing segment. -- **Points** (class 96): each render vertex is one point. A zero int follows the attribute slots and precedes the pad to 8. +- **Points** (class 96): each render vertex is one point. An `i32` flag of 0 or 1 follows the attribute slots and precedes the pad to 8. - **UVBODY**: the raw form stores interleaved `f32` U/V pairs. The quantised form stores `[U0 bits][V0 bits][U1 bits][V1 bits]…` using `PACKED`. The widths are `bu = w & 0xFF` and `bv = (w >> 8) & 0xFF`. A nonzero-width code `q` represents `min + q/(2^bits - 1) × (max - min)`; width zero takes that axis's minimum. Both widths may be zero for a constant pair. The token stream maps each of the `p1` render vertices to a stored pair, independently of the position map. U/V use the lower-left origin, as confirmed by converting a synthetic OBJ with asymmetric coordinates in Navisworks. +- **Text** (class 103): `[100][103][str text][6 x f32][6 x f32 bounds (min then max)][i32 style index][pad8]`. The reader preserves the text, style index, bounds and fragment placement. The glyph triangles counted by the fragment are absent from the geometry record. + - **Writer records**: `NwcWriter` emits its own simplified record, `[id][94][0][60][p1][p2][p2 x f32 xyz]`, followed by the trailer `["NWCI"][indexCount][indexCount x i32][Id i32][nameLength][UTF-8 name][pad4]`. The fallback mesh parser (§2.5) restores the exact triangle indices, `Id` and `Name` from the trailer; records without it keep the rebuilt strip and the synthesized `Mesh_{index}` identity. The trailer is writer-specific: it is not part of the documented Navisworks grammar. ### 2.7 DB Cache Directory (`DbCache` / `LcOpDBCache`) diff --git a/docs/public-api.md b/docs/public-api.md index ef1c3fc..ece5fd6 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -20,7 +20,7 @@ The supported surface is the `NwcIO` and `NwcIO.Model.*` namespaces listed here | `NwcNode` | Scene graph tree node representing layers, categories, composite elements, and geometry instances with optional transformations and properties. For Navisworks model files read through their DbCache directory (the strict path), `Meshes` lists every mesh placed on a leaf and `Mesh` the first, ids are depth-first preorder indices, `Transform` is null; `IsElement` marks Revit element nodes, `ElementGuid` is their export GUID from `LcOpGuidStore`, `IfcGlobalId` is the GlobalId the Revit IFC export gives the element: its valid `IFC_GUID` parameter, else its export GUID in the IFC base-64 form (the rule of `RvtIO.Scene`), and `Element` points every node inside an element (and the second node of a sibling pair that repeats one element) to its element node; properties include the tabs stored in `LcOaPartitionProps`; other files leave `Meshes` empty and `Mesh` null. | | `NwcPropertyRecord` | Property record (`Class`, `Name`, `Value`, `ValueType`, `Tag`, `FirstInt`; typed `IntValue`, `DoubleValue`, `ReferenceId`, `ReferenceTag`, `ReferenceClass`). On node properties of the strict path, `Class` is the property tab name (category, for example `Element`), `Name` the property name and `FirstInt` the key object id. Records scanned from property streams (`NwcDocument.PropertyRecords`, and node properties of other files) keep their internal class names. `TabInternalName` and `InternalName` are the internal names of the tab and the key on strict-path node properties, null on scanned records. | | `NwcPropertyTab` | One property tab of a strict-path node (`NwcNode.PropertyTabs`, in stored slot order): display `Name`, `InternalName`, `Properties`. A tab object shared by several nodes is one instance. | -| `NwcMesh` | Geometry with vertices, triangle indices, `Normals` aligned with vertices, and `LineIndices` for polylines. For `IsPointSet` meshes, each vertex is a point, with optional `PointColors` and no triangle or line indices. JSON mesh summaries include `pointCount` for these meshes. Meshes also carry a world-space transform, bounding box, and material. Model files hold one mesh per placed fragment; `Id` is the fragment index. Meshes of fragments that share a geometry record share their `Vertices`, `Indices`, `Normals`, `LineIndices`, `LineColors` and `PointColors` arrays; do not mutate them. `GeometryIndex` (the geometry record; −1 outside model files) and `LineColors` (per vertex, line meshes of model files). | +| `NwcMesh` | Geometry with vertices, triangle indices, `Normals` aligned with vertices, and `LineIndices` for polylines. For `IsPointSet` meshes, each vertex is a point, with optional `PointColors` and no triangle or line indices. JSON mesh summaries include `pointCount` for these meshes. CAD text meshes carry `Text`, `TextStyleIndex`, bounds and a placement. Their vertex and index lists are empty. JSON mesh summaries include `text` and `textStyleIndex`. Meshes also carry a world-space transform, bounding box, and material. Model files hold one mesh per placed fragment; `Id` is the fragment index. Meshes of fragments that share a geometry record share their `Vertices`, `Indices`, `Normals`, `LineIndices`, `LineColors` and `PointColors` arrays; do not mutate them. `GeometryIndex` (the geometry record; −1 outside model files) and `LineColors` (per vertex, line meshes of model files). | | `NwcMaterial` | Colour and PBR material. On the strict path, `Name` comes from the nearest class-31 material on the mesh's leaf or an ancestor (`Default` when absent or empty), `Color` comes from the fragment's diffuse appearance with alpha `1 - transparency`, and `DiffuseTexture` comes from its Generic diffuse map. Each colour channel is rounded to a byte (halves away from zero). `Roughness` and `Metallic` keep their defaults. `NwcDocument.Materials` lists distinct name, RGBA and texture combinations in order of first use. With `BuildSceneTree = false`, appearances with a diffuse image still supply a material named `Default`. Elsewhere names come from material references in property records and the colour from a `revit_Color` record that follows the definition. A material without that record gets a neutral grey and `IsInferred = true`. Meshes without a material share one neutral `Default Material` per document with `IsInferred = true`. | | `NwcTransform` | Parsed pose/transform records with quaternion rotation, uniform `Scale` (negative for a mirrored placement) and affine 4×4 matrix conversion. Model files hold one transform per fragment, with the same `Id` as its mesh. | | `NwcFileInfo` | Source path, loader plugin, export timestamp from partition header, format version, text encoding, and chunk marker from section headers. | diff --git a/docs/scene.md b/docs/scene.md index e8de8b6..c9355d7 100644 --- a/docs/scene.md +++ b/docs/scene.md @@ -56,7 +56,7 @@ A value is written as text under its key by the stored value type: | Value type | Text | | --- | --- | | 1 (number) | The number, invariant culture, six significant digits. | -| 2, 4, 8, 9 (integer, string, other text types) | The stored text unchanged. | +| 2, 4, 8, 9, 15 (integer, string, other text types) | The stored text unchanged. | | 3 (boolean) | `0` for a stored 0, otherwise `1`. | | 6 (length) | Feet converted to millimetres, six significant digits, suffix ` mm`. | | 10 (area) | Square feet converted to square metres, suffix ` m²`. | @@ -73,6 +73,7 @@ A property with no text, a non-finite number, numeric text that does not parse, | --- | --- | --- | | `no-source-id` | Info | Leaf nodes outside any Revit element have no `SourceId` (one aggregated entry with the count). | | `empty-mesh` | Info | A mesh has no triangles, line segments or points. The entry includes the element's GUID when available. | +| `text-not-rendered` | Info | CAD text annotations are retained in the source document. Their glyphs do not appear in scene geometry. One entry gives the number of affected placements. | | `unit-unknown` | Warning | The length unit is unknown (the file does not name it and `LengthUnit` is not set, or `LengthUnit` is `Unknown`): geometry, grid lines and length, area, volume and angle values are left out. | | `line-colour-mixed` | Warning | Per geometry record: line segments join vertices of different colours and are drawn with the material colour. | | `line-colours-capped` | Warning | Per geometry record: the record has more than 64 line colours; segments of the further colours are drawn with the material colour. | diff --git a/src/NwcIO.Scene/NwcSceneReader.Geometry.cs b/src/NwcIO.Scene/NwcSceneReader.Geometry.cs index d5e39a9..89468b8 100644 --- a/src/NwcIO.Scene/NwcSceneReader.Geometry.cs +++ b/src/NwcIO.Scene/NwcSceneReader.Geometry.cs @@ -36,6 +36,7 @@ private static HashSet AddGeometry(NwcDocument document, SceneDocument var geometries = new Dictionary>(); // by GeometryIndex, else by the mesh var materials = new Dictionary(ReferenceEqualityComparer.Instance); int unplaced = 0; + int textAnnotations = 0; foreach (var mesh in document.Meshes) { if (mesh.Node is not { } node || !ids.TryGetValue(node, out long elementId)) @@ -44,6 +45,12 @@ private static HashSet AddGeometry(NwcDocument document, SceneDocument continue; } + if (mesh.Text is not null) + { + textAnnotations++; + continue; + } + object key = mesh.GeometryIndex >= 0 ? mesh.GeometryIndex : mesh; if (!geometries.TryGetValue(key, out var groups)) { @@ -93,6 +100,12 @@ private static HashSet AddGeometry(NwcDocument document, SceneDocument $"{unplaced} meshes have no node in the scene tree (for example, the file was not read through its DbCache directory); they are not in the scene.")); } + if (textAnnotations > 0) + { + diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "text-not-rendered", + $"{textAnnotations} CAD text annotations were read; the scene contains no geometry for them.")); + } + return placed; } diff --git a/src/NwcIO.Scene/NwcSceneReader.Properties.cs b/src/NwcIO.Scene/NwcSceneReader.Properties.cs index b9ac836..8e93f49 100644 --- a/src/NwcIO.Scene/NwcSceneReader.Properties.cs +++ b/src/NwcIO.Scene/NwcSceneReader.Properties.cs @@ -82,7 +82,7 @@ private static List PropertySetIds(NwcNode node, SceneDocument scene, Dicti double? metres = unit.GetMetresPerUnit(); return record.ValueType switch { - 2 or 4 or 8 or 9 => value, + 2 or 4 or 8 or 9 or 15 => value, 3 => value == "0" ? "0" : "1", 1 => Number(value, 1, ""), 6 when metres is double m => Number(value, m * 1000.0, " mm"), diff --git a/src/NwcIO/Internal/Json/JsonExporter.cs b/src/NwcIO/Internal/Json/JsonExporter.cs index 4dbe6f8..bdfbe44 100644 --- a/src/NwcIO/Internal/Json/JsonExporter.cs +++ b/src/NwcIO/Internal/Json/JsonExporter.cs @@ -177,6 +177,15 @@ private static async ValueTask WriteDocument( writer.WriteNumber("pointCount", mesh.Vertices.Count); } + if (mesh.Text is { } text) + { + writer.WriteString("text", text); + if (mesh.TextStyleIndex is int style) + { + writer.WriteNumber("textStyleIndex", style); + } + } + if (mesh.Material is not null) { writer.WriteString("material", mesh.Material.Name); diff --git a/src/NwcIO/Internal/Parsing/FragmentParser.cs b/src/NwcIO/Internal/Parsing/FragmentParser.cs index 4faab43..4069efe 100644 --- a/src/NwcIO/Internal/Parsing/FragmentParser.cs +++ b/src/NwcIO/Internal/Parsing/FragmentParser.cs @@ -39,7 +39,7 @@ internal static class FragmentParser private static ReadOnlySpan GeometryClasses => [93]; - public static Fragment[] Read(byte[] data, byte[]? sharedNodes = null, bool readTextures = false) + public static Fragment[] Read(byte[] data, SharedNodeTable? sharedNodes = null, bool readTextures = false) { bool paddedCount = data.Length >= 16 && BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4)) == 0 && BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(8)) == 100 && BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(12)) == 13; @@ -57,11 +57,10 @@ private sealed class Parser private readonly LcObjectReader _reader; private readonly Func _readBody; - private readonly byte[]? _sharedNodes; + private readonly SharedNodeTable? _sharedNodes; private readonly bool _readTextures; - private string?[]? _sharedTextures; - public Parser(LcObjectReader reader, byte[]? sharedNodes, bool readTextures) + public Parser(LcObjectReader reader, SharedNodeTable? sharedNodes, bool readTextures) { _reader = reader; _readBody = ReadBody; @@ -142,14 +141,7 @@ private FragmentLook ReadAppearance() var look = (FragmentLook)_reader.ReadPointer(MaterialClasses, _readBody, allowNull: false)!; if ((flags & 32) == 0) return look; - string? texturePath; - if (_sharedNodes is not null && _reader.TryReadSharedIndex(out int index)) - { - _sharedTextures ??= ReadSharedTextures(_sharedNodes, _readTextures); - if (index >= _sharedTextures.Length) throw _reader.Fail("appearance shared index is outside LcOpSharedNodes"); - texturePath = _sharedTextures[index]; - } - else + if (_sharedNodes?.TryReadMaterial(_reader, out string? texturePath) != true) { texturePath = _reader.ReadPointer(ExtraClasses, _readBody) as string; } @@ -162,18 +154,6 @@ private FragmentLook ReadAppearance() return look with { DiffuseTexturePath = texturePath }; } - private static string?[] ReadSharedTextures(byte[] data, bool readTextures) - { - var reader = new LcObjectReader(data, "LcOpSharedNodes"); - var textures = new string?[reader.ReadCount(8)]; - for (int i = 0; i < textures.Length; i++) - { - textures[i] = reader.ReadPointer(ExtraClasses, _ => HierarchyParser.ReadMaterialJson(reader, readTextures)) as string; - } - reader.ReadEnd(); - return textures; - } - // Class 54: 14 x f32: ambient 0-2, diffuse 3-5, specular 6-8, emissive 9-11, shininess 12, transparency 13. private FragmentLook ReadMaterial() { diff --git a/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs b/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs index bf35a94..1095ec5 100644 --- a/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs +++ b/src/NwcIO/Internal/Parsing/GeometryRecordParser.cs @@ -1,5 +1,7 @@ using System.Buffers.Binary; using System.Numerics; +using System.Text; +using System.Text.Unicode; using NwcIO.Model; namespace NwcIO.Internal.Parsing; @@ -9,6 +11,8 @@ internal sealed class GeometryRecord { public required bool IsLines { get; init; } public bool IsPoints { get; init; } + public string? Text { get; init; } + public int? TextStyleIndex { get; init; } /// Render vertices: render vertex r sits at position VMap[r]. public required Vector3d[] Vertices { get; init; } @@ -60,9 +64,14 @@ public static GeometryRecord Parse(ReadOnlySpan record, int normalBits) Expect(record, ref pos, 100, "record id is not 100"); int at = pos; int cls = ReadInt32(record, ref pos); + if (cls == 103) + { + return ReadText(record, pos); + } + if (cls is not (94 or 95 or 96)) { - throw Fail($"class {cls} is not 94, 95 or 96", at); + throw Fail($"class {cls} is not 94, 95, 96 or 103", at); } bool lines = cls == 95; @@ -256,7 +265,10 @@ public static GeometryRecord Parse(ReadOnlySpan record, int normalBits) if (cls == 96) { - Expect(record, ref pos, 0, "point record terminator is not zero"); + if (ReadInt32(record, ref pos) is not (0 or 1)) + { + throw Fail("point record flag is neither 0 nor 1", pos - 4); + } CheckEnd(record, ref pos); return new GeometryRecord { @@ -386,6 +398,58 @@ public static GeometryRecord Parse(ReadOnlySpan record, int normalBits) }; } + private static GeometryRecord ReadText(ReadOnlySpan record, int pos) + { + int lengthOffset = pos; + int length = ReadInt32(record, ref pos); + if (length < 0) + { + throw Fail("text byte length is negative", lengthOffset); + } + + int start = pos; + Skip(record, ref pos, length, "text passes the end"); + var bytes = record[start..pos]; + if (!Utf8.IsValid(bytes)) + { + throw Fail("text is not valid UTF-8", start); + } + + Pad(record, ref pos, 4); + for (int i = 0; i < 6; i++) + { + ReadTextNumber(record, ref pos); + } + + var min = new Vector3d(ReadTextNumber(record, ref pos), ReadTextNumber(record, ref pos), ReadTextNumber(record, ref pos)); + var max = new Vector3d(ReadTextNumber(record, ref pos), ReadTextNumber(record, ref pos), ReadTextNumber(record, ref pos)); + var bounds = new BoundingBox3d(min, max); + if (bounds.IsEmpty) + { + throw Fail("text bounding box is inverted", pos - 24); + } + + int style = ReadInt32(record, ref pos); + CheckEnd(record, ref pos); + return new GeometryRecord + { + IsLines = false, + Text = Encoding.UTF8.GetString(bytes), + TextStyleIndex = style, + Vertices = [], + Indices = [], + LineIndices = [], + Normals = null, + Bounds = bounds, + }; + } + + private static float ReadTextNumber(ReadOnlySpan record, ref int pos) + { + float value = BitConverter.Int32BitsToSingle(ReadInt32(record, ref pos)); + return float.IsFinite(value) ? value : throw Fail("text geometry value is not finite", pos - 4); + } + private static void CheckEnd(ReadOnlySpan record, ref int pos) { Pad(record, ref pos, 8); diff --git a/src/NwcIO/Internal/Parsing/HierarchyParser.cs b/src/NwcIO/Internal/Parsing/HierarchyParser.cs index 9f586c2..2719d0d 100644 --- a/src/NwcIO/Internal/Parsing/HierarchyParser.cs +++ b/src/NwcIO/Internal/Parsing/HierarchyParser.cs @@ -52,11 +52,12 @@ public static IReadOnlyList Read( bool includeProperties = true, IReadOnlyList? guids = null, Func?>? partitionProps = null, - int maxExpandedPropertyReferences = DefaultMaxExpandedPropertyReferences) + int maxExpandedPropertyReferences = DefaultMaxExpandedPropertyReferences, + SharedNodeTable? sharedNodes = null) { guids ??= []; var (top, total) = new Parser(new LcObjectReader(data, Segment), guids.Count, partitionProps ?? (() => null), - maxExpandedPropertyReferences).ReadStream(); + maxExpandedPropertyReferences, sharedNodes).ReadStream(); return Expand(top, rootName, total, includeProperties, guids); } @@ -243,6 +244,7 @@ private sealed class Parser private readonly LcObjectReader _reader; private readonly int _guidCount; private readonly int _maxExpandedPropertyReferences; + private readonly SharedNodeTable? _sharedNodes; // Null in a parser of one LcOaPartitionProps stream, which holds roots and no nodes. private readonly Func?>? _partitionProps; @@ -252,11 +254,12 @@ private sealed class Parser private PartitionRoots? _roots; public Parser(LcObjectReader reader, int guidCount, Func?>? partitionProps, - int maxExpandedPropertyReferences = DefaultMaxExpandedPropertyReferences) + int maxExpandedPropertyReferences = DefaultMaxExpandedPropertyReferences, SharedNodeTable? sharedNodes = null) { _reader = reader; _guidCount = guidCount; _maxExpandedPropertyReferences = maxExpandedPropertyReferences; + _sharedNodes = sharedNodes; _partitionProps = partitionProps; _readBody = ReadBody; } @@ -429,7 +432,7 @@ private object ReadPartitionLight() { _reader.ReadInt32(); } - else + else if (_sharedNodes?.TryReadMaterial(_reader, out _) != true) { _reader.ReadPointer(ExtraClasses, _readBody, allowNull: false, allowBackReference: false); } @@ -503,6 +506,7 @@ private NwcPropertyTab ReadPropertyTab() { var key = ReadUsername(); int type = _reader.ReadInt32(); + long? wideInteger = type == 15 ? _reader.ReadInt64() : null; string? value = type switch { 0 => null, @@ -513,6 +517,7 @@ private NwcPropertyTab ReadPropertyTab() 8 => ReadUsername().Display, 12 => string.Create(CultureInfo.InvariantCulture, $"({_reader.ReadDouble()}, {_reader.ReadDouble()}, {_reader.ReadDouble()})"), 13 => string.Create(CultureInfo.InvariantCulture, $"({_reader.ReadDouble()}, {_reader.ReadDouble()})"), + 15 => wideInteger?.ToString(CultureInfo.InvariantCulture), _ => throw _reader.Fail($"property value type {type} is unknown"), }; records.Add(new NwcPropertyRecord @@ -523,6 +528,7 @@ private NwcPropertyTab ReadPropertyTab() Class = tab, ValueType = type, Value = value, + IntValue = wideInteger, TabInternalName = username.Internal, InternalName = key.Internal, }); @@ -542,18 +548,22 @@ private NwcPropertyTab ReadElementId() var key = ReadUsername(); int flags = _reader.ReadInt32(); - if (flags is not (0x01000000 or 0x00020000)) + bool dwgHandle = key.Internal == "LcOpDwgEntityAttrib"; + bool legacyFlags = flags is 0x01000000 or 0x00020000; + if (!legacyFlags && !(dwgHandle && flags is (0 or 0x02000000 or 0x03000000))) { throw _reader.Fail($"class-66 flags {flags:X8} are not 01000000 or 00020000"); } long value = _reader.ReadInt64(); - if (value is < 1 or > int.MaxValue) + bool fitsLegacyRange = value is >= 1 and <= int.MaxValue; + if (!dwgHandle && !fitsLegacyRange) { throw _reader.Fail($"class-66 value {value} is outside 1..{int.MaxValue}"); } - return SingleProperty(key, 2, value.ToString(CultureInfo.InvariantCulture)); + bool wideHandle = dwgHandle && !(legacyFlags && fitsLegacyRange); + return SingleProperty(key, wideHandle ? 15 : 2, value.ToString(CultureInfo.InvariantCulture), wideHandle ? value : null); } // Class 70 stores a string value in the name field, followed by its key and flags. @@ -565,7 +575,7 @@ private NwcPropertyTab ReadStringProperty() return SingleProperty(key, 4, value); } - private static NwcPropertyTab SingleProperty(Username key, int valueType, string? value) + private static NwcPropertyTab SingleProperty(Username key, int valueType, string? value, long? intValue = null) { string name = key.Display ?? ""; var record = new NwcPropertyRecord @@ -576,19 +586,30 @@ private static NwcPropertyTab SingleProperty(Username key, int valueType, string Class = name, ValueType = valueType, Value = value, + IntValue = intValue, TabInternalName = key.Internal, InternalName = key.Internal, }; return new NwcPropertyTab { Name = name, InternalName = key.Internal, Properties = [record] }; } - // Class 31: [str name][15 x f64]; the doubles are dropped. + // The DWG form inserts a username and a zero word before its fourteen doubles. private Material ReadMaterial() { var material = new Material(_reader.ReadString()); - for (int i = 0; i < 15; i++) + if (_reader.NextIsPointer(52)) { - _reader.ReadDouble(); + ReadUsername(); + if (_reader.ReadInt32() != 0) + { + throw _reader.Fail("class-31 material marker is not 0"); + } + + SkipDoubles(14); + } + else + { + SkipDoubles(15); } return material; @@ -766,13 +787,17 @@ private List ReadHyperlinks() return list; } - // Class 200: [str name][i32 X][i32 Y][ptr extra], the extra a class 185 in every file that has class 200. + // Class 200: [str name][i32 X][i32 Y] followed by an inline or shared class-185 asset. private object ReadExtra() { _reader.ReadString(); _reader.ReadInt32(); _reader.ReadInt32(); - _reader.ReadPointer(ExtraClasses, _readBody, allowNull: false); + if (_sharedNodes?.TryReadMaterial(_reader, out _) != true) + { + _reader.ReadPointer(ExtraClasses, _readBody, allowNull: false); + } + return Dropped; } } diff --git a/src/NwcIO/Internal/Parsing/LcObjectReader.cs b/src/NwcIO/Internal/Parsing/LcObjectReader.cs index aa3bac5..4c679f5 100644 --- a/src/NwcIO/Internal/Parsing/LcObjectReader.cs +++ b/src/NwcIO/Internal/Parsing/LcObjectReader.cs @@ -36,18 +36,32 @@ public LcObjectReader(byte[] data, string segment) public int PeekInt32() => BinaryPrimitives.TryReadInt32LittleEndian(_data.AsSpan(Position), out int value) ? value : throw Fail("i32 passes the end of the data"); - public int ReadInt32() => BinaryPrimitives.ReadInt32LittleEndian(Take(4, "i32")); - - public bool TryReadSharedIndex(out int index) + public bool NextIsPointer(int classId) { - if (BinaryPrimitives.TryReadInt32LittleEndian(_data.AsSpan(Position), out index) && index is >= 2 and < FirstId) + if (_data.Length - Position < 8) + { + return false; + } + + var span = _data.AsSpan(Position); + int lead = BinaryPrimitives.ReadInt32LittleEndian(span); + int next = BinaryPrimitives.ReadInt32LittleEndian(span[4..]); + if (lead == Next) { - Position += 4; - return true; + return next == classId; } - return false; + + if (lead != 1 || next < FirstId || next >= Next) + { + return false; + } + + var reference = _objects[next - FirstId]; + return reference.Body is not null && reference.ClassId == classId; } + public int ReadInt32() => BinaryPrimitives.ReadInt32LittleEndian(Take(4, "i32")); + public float ReadSingle() => BinaryPrimitives.ReadSingleLittleEndian(Take(4, "f32")); public double ReadDouble() diff --git a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs index 8fe5503..15cbc45 100644 --- a/src/NwcIO/Internal/Parsing/ModelGraphReader.cs +++ b/src/NwcIO/Internal/Parsing/ModelGraphReader.cs @@ -130,13 +130,18 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR Guid[] guids = segments.GuidStore is not null && (options.ReadGuids || (options.BuildSceneTree && segments.Hierarchy is not null)) ? ReadGuidStore(await segments.GuidStore.GetDataAsync().ConfigureAwait(false)) : []; + bool readGeometry = (options.ReadMeshes || options.ReadTransforms) && (segments.Toc is not null || segments.Fragments is not null); + bool readTextures = options.ReadMeshes && options.ReadMaterials; + var sharedNodes = segments.SharedNodes is not null && ((options.BuildSceneTree && segments.Hierarchy is not null) || readGeometry) + ? new SharedNodeTable(await segments.SharedNodes.GetDataAsync().ConfigureAwait(false), readTextures) + : null; IReadOnlyList? preorder = null; if (options.BuildSceneTree) { preorder = segments.Hierarchy is null ? [new NwcNode { Id = 0, Name = rootName, Class = "Model", Tag = 0 }] : await ReadHierarchy(segments.Hierarchy, rootName, options.ReadPropertyRecords, guids, segments.PartitionProps, - options.MaxExpandedPropertyReferences).ConfigureAwait(false); + options.MaxExpandedPropertyReferences, sharedNodes).ConfigureAwait(false); } var meshes = new List(); @@ -144,7 +149,7 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR var materials = new List(); var materialsByKey = new Dictionary<(string, byte, byte, byte, byte, NwcXRef?), NwcMaterial>(); var references = MaterialTextureParser.Index(xRefs); - if ((options.ReadMeshes || options.ReadTransforms) && (segments.Toc is not null || segments.Fragments is not null)) + if (readGeometry) { if (segments.Toc is null) { @@ -152,9 +157,8 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR } var records = await GeometrySegmentReader.ReadAsync(segments.GeometryChunks, segments.Toc, cancellationToken).ConfigureAwait(false); - byte[]? sharedNodes = segments.SharedNodes is null ? null : await segments.SharedNodes.GetDataAsync().ConfigureAwait(false); Fragment[] fragments = segments.Fragments is null ? [] : FragmentParser.Read(await segments.Fragments.GetDataAsync().ConfigureAwait(false), - sharedNodes, readTextures: options.ReadMeshes && options.ReadMaterials); + sharedNodes, readTextures); CheckLinks(fragments, records, preorder); object? elementKey = null; for (int k = 0; k < fragments.Length; k++) @@ -194,6 +198,8 @@ public static async ValueTask ReadAsync(ModelSegments segments, NwcR LineColors = record.LineColors, IsPointSet = record.IsPoints, PointColors = record.PointColors, + Text = record.Text, + TextStyleIndex = record.TextStyleIndex, GeometryIndex = fragment.Record - 1, BoundingBox = record.Bounds, Transform = transform, @@ -275,13 +281,13 @@ private static Guid[] ReadGuidStore(byte[] data) private static async ValueTask> ReadHierarchy( LcRawStream hierarchy, string rootName, bool includeProperties, Guid[] guids, - Func?>> partitionProps, int maxExpandedPropertyReferences) + Func?>> partitionProps, int maxExpandedPropertyReferences, SharedNodeTable? sharedNodes) { byte[] data = await hierarchy.GetDataAsync().ConfigureAwait(false); if (!hierarchy.RequiresAsyncRead) { return HierarchyParser.Read(data, rootName, includeProperties, guids, - () => partitionProps().GetSynchronousResult(), maxExpandedPropertyReferences); + () => partitionProps().GetSynchronousResult(), maxExpandedPropertyReferences, sharedNodes); } // The hierarchy always checks the roots on a successful parse. Defer validation failures to that same point. @@ -300,7 +306,7 @@ private static async ValueTask> ReadHierarchy( { failure?.Throw(); return roots; - }, maxExpandedPropertyReferences); + }, maxExpandedPropertyReferences, sharedNodes); } // The LcOaPartitionProps root streams, once the last stream, the table of contents [i32 k][k x i32 compressed length] zero-padded @@ -477,7 +483,8 @@ private static void CheckLinks(Fragment[] fragments, GeometryRecord[] records, I throw Link(k, "bounding box differs from the record's"); } - if (fragment.PrimitiveCount != record.PrimitiveCount) + // Text records carry the annotation and its bounds. Their glyph triangles are not in the record. + if (record.Text is null && fragment.PrimitiveCount != record.PrimitiveCount) { throw Link(k, "primitive count differs from the record's"); } diff --git a/src/NwcIO/Internal/Parsing/SharedNodeTable.cs b/src/NwcIO/Internal/Parsing/SharedNodeTable.cs new file mode 100644 index 0000000..9f2eec7 --- /dev/null +++ b/src/NwcIO/Internal/Parsing/SharedNodeTable.cs @@ -0,0 +1,75 @@ +using System.Buffers.Binary; + +namespace NwcIO.Internal.Parsing; + +/// Material and font objects referenced by index across model streams. +internal sealed class SharedNodeTable(byte[] data, bool readTextures) +{ + private sealed record Entry(int ClassId, string? Texture); + private Entry?[]? _entries; + private static ReadOnlySpan Classes => [102, 185]; + + public bool TryReadMaterial(LcObjectReader reader, out string? texture) + { + texture = null; + int index = reader.PeekInt32(); + if (index < 2 || reader.NextIsPointer(185)) + { + return false; + } + + // Small leads are reserved for shared indices. Larger ones can also be new object IDs. + if (index >= 100 && (!BinaryPrimitives.TryReadInt32LittleEndian(data, out int count) || index >= count)) + { + return false; + } + + reader.ReadInt32(); + _entries ??= ReadEntries(); + if (index >= _entries.Length) + { + throw reader.Fail($"material shared index {index} is outside LcOpSharedNodes"); + } + + var entry = _entries[index]; + if (entry is not null && entry.ClassId != 185) + { + throw reader.Fail($"material shared index {index} refers to class {entry.ClassId}"); + } + + texture = entry?.Texture; + return true; + } + + private Entry?[] ReadEntries() + { + var reader = new LcObjectReader(data, "LcOpSharedNodes"); + var entries = new Entry?[reader.ReadCount(4)]; + for (int i = 0; i < entries.Length; i++) + { + entries[i] = (Entry?)reader.ReadPointer(Classes, cls => cls == 185 + ? new Entry(cls, HierarchyParser.ReadMaterialJson(reader, readTextures) as string) + : ReadFont(reader)); + } + + reader.ReadEnd(); + return entries; + } + + // Class 102 stores the font name, one aligned double and four 32-bit fields. + private static Entry ReadFont(LcObjectReader reader) + { + reader.ReadString(); + if (!double.IsFinite(reader.ReadDouble())) + { + throw reader.Fail("class-102 font value is not finite"); + } + + for (int i = 0; i < 4; i++) + { + reader.ReadInt32(); + } + + return new Entry(102, null); + } +} diff --git a/src/NwcIO/Model/NwcMesh.cs b/src/NwcIO/Model/NwcMesh.cs index 5cf92f8..e48c88f 100644 --- a/src/NwcIO/Model/NwcMesh.cs +++ b/src/NwcIO/Model/NwcMesh.cs @@ -3,7 +3,7 @@ namespace NwcIO.Model; /// -/// Triangle, polyline or point geometry extracted from Navisworks geometry streams. +/// Triangle, polyline, point or text geometry extracted from Navisworks geometry streams. /// public sealed class NwcMesh { @@ -47,6 +47,12 @@ public sealed class NwcMesh /// One colour per point in , when stored. public IReadOnlyList? PointColors { get; init; } + /// Text of a CAD annotation. A text record has bounds and a placement but no mesh primitives. + public string? Text { get; init; } + + /// File-local style index stored by a text record. + public int? TextStyleIndex { get; init; } + /// /// 0-based index of the geometry record this mesh was read from; -1 for meshes not read from a model file. /// @@ -106,7 +112,19 @@ internal BoundingBox3d GetWorldBoundingBox(Func } } - var worldVerts = getVertices is null ? GetWorldVertices() : getVertices(this); + IReadOnlyList worldVerts; + if (Text is not null && BoundingBox is { IsEmpty: false } textBounds) + { + var (a, b) = (textBounds.Min, textBounds.Max); + worldVerts = TransformVertices( + [a, new(b.X, a.Y, a.Z), new(a.X, b.Y, a.Z), new(a.X, a.Y, b.Z), + new(a.X, b.Y, b.Z), new(b.X, a.Y, b.Z), new(b.X, b.Y, a.Z), b], + cancellationToken); + } + else + { + worldVerts = getVertices is null ? GetWorldVertices() : getVertices(this); + } if (worldVerts.Count == 0) { _cachedWorldBounds = BoundingBox3d.Empty; @@ -139,26 +157,29 @@ internal BoundingBox3d GetWorldBoundingBox(Func /// public IReadOnlyList GetWorldVertices() => TransformVertices(default); - internal IReadOnlyList TransformVertices(CancellationToken cancellationToken) + internal IReadOnlyList TransformVertices(CancellationToken cancellationToken) => + TransformVertices(Vertices, cancellationToken); + + private IReadOnlyList TransformVertices(IReadOnlyList vertices, CancellationToken cancellationToken) { if (Transform is null) { - return Vertices; + return vertices; } double[] m = Transform.ToMatrix4x4(); - var world = new Vector3d[Vertices.Count]; - for (int i = 0; i < Vertices.Count; i++) + var world = new Vector3d[vertices.Count]; + for (int i = 0; i < vertices.Count; i++) { if ((i & 255) == 0) cancellationToken.ThrowIfCancellationRequested(); - var v = Vertices[i]; + var v = vertices[i]; double wx = v.X * m[0] + v.Y * m[4] + v.Z * m[8] + m[12]; double wy = v.X * m[1] + v.Y * m[5] + v.Z * m[9] + m[13]; double wz = v.X * m[2] + v.Y * m[6] + v.Z * m[10] + m[14]; if (!double.IsFinite(wx) || !double.IsFinite(wy) || !double.IsFinite(wz)) { - return Vertices; + return vertices; } world[i] = new Vector3d(wx, wy, wz); diff --git a/src/NwcIO/Model/NwcPropertyRecord.cs b/src/NwcIO/Model/NwcPropertyRecord.cs index 92a6075..07fb544 100644 --- a/src/NwcIO/Model/NwcPropertyRecord.cs +++ b/src/NwcIO/Model/NwcPropertyRecord.cs @@ -15,13 +15,13 @@ public sealed class NwcPropertyRecord public required string Class { get; init; } - /// Value type marker stored in the record: 0/2/3 int, 1/6/7/10/11 double, 4/9 string, 5 DateTime, 8 reference, 12 Point3D, 13 Point2D. + /// Value type marker stored in the record: 0/2/3 int, 1/6/7/10/11 double, 4/9 string, 5 DateTime, 8 reference, 12 Point3D, 13 Point2D, 15 int64. public int ValueType { get; init; } /// String value when is a known text type; otherwise null. public string? Value { get; init; } - /// Typed integer value for types 0, 2, 3 and 5; null otherwise. + /// Typed integer value for types 0, 2, 3, 5 and 15; null otherwise. public long? IntValue { get; init; } /// Typed floating-point value for types 1, 6, 7, 10 and 11; null otherwise. diff --git a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs index 5753b2d..0db6ed8 100644 --- a/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs +++ b/tests/NwcIO.Scene.Tests/NwcSceneReaderTests.cs @@ -399,10 +399,12 @@ public void Read_RotatedInstance_KeepsTheRowVectorAxes() Assert.Null(result.Document.Geometries[0].Normals); // no stored normals } - [Fact] - public void Read_Class96Points_KeepsWorldPositions() + [Theory] + [InlineData(0)] + [InlineData(1)] + public void Read_Class96Points_KeepsWorldPositions(int flag) { - var result = Scene(SyntheticNwcFile.PointSet(), new() { ModelKey = "points", LengthUnit = NwcLengthUnit.Meters }); + var result = Scene(SyntheticNwcFile.PointSet(flag), new() { ModelKey = "points", LengthUnit = NwcLengthUnit.Meters }); Assert.DoesNotContain(result.Diagnostics, d => d.Code == "empty-mesh"); var geometry = Assert.Single(result.Document.Geometries); @@ -414,6 +416,16 @@ public void Read_Class96Points_KeepsWorldPositions() Assert.Equal([new Vector3d(10, 0, 0), new(11, 2, 3)], geometry.Vertices.Select(transform.Apply)); } + [Fact] + public void Read_TextAnnotation_ReportsThatItHasNoSceneGeometry() + { + var result = Scene(SyntheticNwcFile.TextAnnotation(), new() { ModelKey = "text", LengthUnit = NwcLengthUnit.Meters }); + Assert.Empty(result.Document.Geometries); + Assert.Empty(result.Document.Instances); + Assert.Single(result.Diagnostics, d => d.Code == "text-not-rendered"); + Assert.DoesNotContain(result.Diagnostics, d => d.Code == "empty-mesh"); + } + [Fact] public void Read_EmptyMesh_HasNoGeometryAndIsReported() { diff --git a/tests/NwcIO.Tests/Fixtures/SyntheticNwcFile.cs b/tests/NwcIO.Tests/Fixtures/SyntheticNwcFile.cs index c33bca0..7ac8336 100644 --- a/tests/NwcIO.Tests/Fixtures/SyntheticNwcFile.cs +++ b/tests/NwcIO.Tests/Fixtures/SyntheticNwcFile.cs @@ -137,14 +137,23 @@ void PropsSegment() return [.. file]; } - public static byte[] PointSet() + public static byte[] PointSet(int flag = 0) { var pointRecord = new LcGraphWriter().Int(100).Int(96).Int(101).Int(60).Int(2).Int(6) - .Float(0).Float(0).Float(0).Float(1).Float(2).Float(3).Int(0).Int(0).Int(0).Int(0).ToArray(); + .Float(0).Float(0).Float(0).Float(1).Float(2).Float(3).Int(0).Int(0).Int(0).Int(flag).ToArray(); byte[] fragments = SyntheticFragments.Build(new Frag(2, new(10, 0, 0), 1, 2, 2, Rec: 1, MaxY: 2, MaxZ: 3)); return Build(FormatVectors.H1, fragments, [pointRecord], [pointRecord.Length]); } + public static byte[] TextAnnotation() + { + var text = new LcGraphWriter().Int(100).Int(103).Str("Étage 1") + .Float(0).Float(0).Float(0).Float(1).Float(1).Float(0) + .Float(0).Float(0).Float(0).Float(1).Float(2).Float(3).Int(7).ToArray(); + byte[] fragments = SyntheticFragments.Build(new Frag(2, new(10, 0, 0), -2, 9, 27, Rec: 1, MaxY: 2, MaxZ: 3)); + return Build(FormatVectors.H1, fragments, [text], [text.Length]); + } + private static byte[] Zlib(byte[] data) { using var output = new MemoryStream(); diff --git a/tests/NwcIO.Tests/GeometryRecordParserTests.cs b/tests/NwcIO.Tests/GeometryRecordParserTests.cs index c248a12..61676c4 100644 --- a/tests/NwcIO.Tests/GeometryRecordParserTests.cs +++ b/tests/NwcIO.Tests/GeometryRecordParserTests.cs @@ -244,7 +244,7 @@ public void Parse_R5EightBitPalette_DecodesDiagonalNormal() [InlineData("R1", 92, "C0", "lead byte is undefined")] // undefined NTOK lead [InlineData("R1", 112, "01000040", "unused packed bit is set")] // unused packed bit [InlineData("R1", 76, "67000000", "slot id is out of order")] // N id 103: id order - [InlineData("R1", 4, "61000000", "class 97 is not 94, 95 or 96")] // unknown class 97 + [InlineData("R1", 4, "61000000", "class 97 is not 94, 95, 96 or 103")] // unknown class 97 [InlineData("R1", -1, "0000000000000000", "record does not end at its TOC length")] // -1 = append: end != TOC length [InlineData("R2", 122, "01", "pad byte is not zero")] // non-zero pad4 [InlineData("R2", 84, "D5", "lead byte is undefined")] // axis code outside N diff --git a/tests/NwcIO.Tests/HierarchyParserTests.cs b/tests/NwcIO.Tests/HierarchyParserTests.cs index 63c0656..30709e6 100644 --- a/tests/NwcIO.Tests/HierarchyParserTests.cs +++ b/tests/NwcIO.Tests/HierarchyParserTests.cs @@ -134,6 +134,89 @@ public void Read_ValueType9_IsAString() Assert.Equal((9, "ID-9"), (leaf.Properties[0].ValueType, leaf.Properties[0].Value)); } + [Theory] + [InlineData(0x02000000, 9_007_199_254_740_993L, 15, "9007199254740993")] + [InlineData(0x01000000, 9_007_199_254_740_993L, 15, "9007199254740993")] + [InlineData(0x01000000, 47L, 2, "47")] + public void Read_64BitPropertyAndDwgHandle_PreservesTheirValues(int flags, long handle, int handleType, string handleText) + { + const long value = 9_007_199_254_740_993; + var hierarchy = Begin(roots: [1]); + Group(hierarchy, 1); + Leaf(hierarchy, 2, w => + { + w.New(86); + w.Str("T"); + Username(w, "T", "lcT"); + w.Int(0).Int(1); + Username(w, "K", "lcK"); + w.Int(15).Long(-value); + w.Null(); + }); + var props = new LcGraphWriter(); + props.New(66); + props.Str(null); + Username(props, "Handle", "LcOpDwgEntityAttrib"); + props.Int(flags).Long(handle); + var leaf = HierarchyParser.Read(End(hierarchy), "Model", partitionProps: () => [props.ToArray()])[2]; + + Assert.Equal([(15, "-9007199254740993", (long?)-value), (handleType, handleText, handleType == 15 ? (long?)handle : null)], + leaf.Properties.Select(p => (p.ValueType, p.Value, p.IntValue))); + } + + [Theory] + [InlineData(0)] + [InlineData(4)] + public void Read_DwgMaterialUsernameBackReference_ConsumesMarkerAndKeepsNextAttribute(int markerOffset) + { + var w = Begin(); + Group(w, 2); + int materialKey = 0; + Leaf(w, 1, leaf => + { + leaf.New(31); + leaf.Str("Grey"); + materialKey = Username(leaf, "Material", "LcOaMaterial"); + leaf.Int(0); + Doubles(leaf, 14); + }); + string expectedName = ""; + Leaf(w, 2, leaf => + { + leaf.New(31); + expectedName = leaf.ToArray(padTo8: false).Length % 8 == markerOffset ? "Blue" : "Green"; + leaf.Str(expectedName).Ref(materialKey); + Assert.Equal(markerOffset, leaf.ToArray(padTo8: false).Length % 8); + leaf.Int(0); + Doubles(leaf, 14); + PropertyTab(leaf, 1); + }); + + var nodes = HierarchyParser.Read(End(w), "Model"); + Assert.Equal("Grey", nodes[2].MaterialName); + Assert.Equal(expectedName, nodes[3].MaterialName); + Assert.Single(nodes[3].Properties); + } + + [Fact] + public void Read_ExtraWithSharedMaterial_KeepsFollowingProperty() + { + var shared = new LcGraphWriter().Int(3).Null().Null(); + shared.New(185); + shared.Str(null).Str(null).Int(0); + byte[] hierarchy = GroupWithLeaf(2, w => + { + w.New(200); + w.Str(null).Int(0).Int(0).Int(2); + PropertyTab(w, 1); + }); + var table = new SharedNodeTable(shared.ToArray(), readTextures: false); + + var nodes = HierarchyParser.Read(hierarchy, "Model", sharedNodes: table); + + Assert.Single(nodes[2].Properties); + } + [Fact] public void Read_ValueType5_IsDateTimeFromUnixSeconds() { diff --git a/tests/NwcIO.Tests/ModelGraphReaderTests.cs b/tests/NwcIO.Tests/ModelGraphReaderTests.cs index 9a4f715..e286c0a 100644 --- a/tests/NwcIO.Tests/ModelGraphReaderTests.cs +++ b/tests/NwcIO.Tests/ModelGraphReaderTests.cs @@ -34,11 +34,12 @@ public void Open_F1File_LinksFragmentsToLeavesAndPoses() } [Theory] - [InlineData(true)] - [InlineData(false)] - public void Open_PointRecord_KeepsPointsAndPlacement(bool tree) + [InlineData(true, 0)] + [InlineData(false, 0)] + [InlineData(true, 1)] + public void Open_PointRecord_KeepsPointsAndPlacement(bool tree, int flag) { - byte[] file = SyntheticNwcFile.PointSet(); + byte[] file = SyntheticNwcFile.PointSet(flag); var doc = NwcDocument.Open(new MemoryStream(file), new NwcReaderOptions { BuildSceneTree = tree }); @@ -56,6 +57,25 @@ public void Open_PointRecord_KeepsPointsAndPlacement(bool tree) Assert.Equal(0, output.Length); } + [Fact] + public void Open_TextRecord_PreservesContentAndPlacedBounds() + { + var doc = NwcDocument.Open(new MemoryStream(SyntheticNwcFile.TextAnnotation())); + + var mesh = Assert.Single(doc.Meshes); + Assert.Same(mesh, Assert.Single(mesh.Node!.Meshes)); + Assert.Equal("Étage 1", mesh.Text); + Assert.Equal(7, mesh.TextStyleIndex); + Assert.Empty(mesh.GetWorldVertices()); + Assert.Empty(mesh.Indices); + Assert.Empty(mesh.LineIndices); + Assert.Equal(new BoundingBox3d(new(8, -4, -6), new(10, 0, 0)), mesh.GetWorldBoundingBox()); + using var json = JsonDocument.Parse(doc.ToJson(new NwcJsonExportOptions { IncludeMeshes = true })); + var exported = json.RootElement.GetProperty("meshes")[0]; + Assert.Equal("Étage 1", exported.GetProperty("text").GetString()); + Assert.Equal(7, exported.GetProperty("textStyleIndex").GetInt32()); + } + [Fact] public void Open_TranslationOnlyPose_PlacesMeshAtTheTranslation() { diff --git a/tests/NwcIO.Tests/TextureExportTests.cs b/tests/NwcIO.Tests/TextureExportTests.cs index 4ec16c4..a3e4fbf 100644 --- a/tests/NwcIO.Tests/TextureExportTests.cs +++ b/tests/NwcIO.Tests/TextureExportTests.cs @@ -19,9 +19,10 @@ public class TextureExportTests """; [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task OpenAndExport_ReadsUvAndRemappedDiffuseTexture(bool sharedAppearance) + [InlineData(null)] + [InlineData(2)] + [InlineData(100)] + public async Task OpenAndExport_ReadsUvAndRemappedDiffuseTexture(int? sharedIndex) { var extra = new List<(string, byte[])> { @@ -31,16 +32,18 @@ public async Task OpenAndExport_ReadsUvAndRemappedDiffuseTexture(bool sharedAppe """)), }; var look = new Look(1, 1, 1, 0, 0, MaterialJson: Appearance); - if (sharedAppearance) + if (sharedIndex is { } index) { - var shared = new LcGraphWriter().Int(3); - for (int i = 0; i < 3; i++) + var shared = new LcGraphWriter().Int(index + 1); + shared.New(102); + shared.Str("Example").Double(1).Int(0).Int(0).Int(0).Int(0); + for (int i = 1; i <= index; i++) { shared.New(185); - shared.Str(i == 2 ? Appearance : null).Str(null).Int(0); + shared.Str(i == index ? Appearance : null).Str(null).Int(0); } extra.Add(("LcOpSharedNodes", shared.ToArray())); - look = look with { MaterialJson = null, SharedMaterial = 2, EditedMaterial = true }; + look = look with { MaterialJson = null, SharedMaterial = index, EditedMaterial = true }; } var fragments = SyntheticFragments.Build(new Frag(2, Vector3d.Zero, 1, 2, 4, Rec: 1, Look: look),