diff --git a/docs/public-api.md b/docs/public-api.md
index 860f4d0..3cead15 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -69,7 +69,7 @@ offset or line number. A warning never contains text from the file. Warnings are
| Type | Use |
| --- | --- |
-| `Db1Document` | A model database (`.db1`, `xslib.db1` and their `.bak` copies). `Version` (`d.dd`), `ModelGuid`, `IdMap` (entries in file order, or null), `IdMapField65` and `IdMapField73` (raw numbers, null when the id map is not read), `Payload` (the whole unpacked file; offsets refer to it). `ReadTextSections()` and `ReadTables()` read on request and build new lists on each call. |
+| `Db1Document` | A model database (`.db1`, `xslib.db1` and their `.bak` copies). `Version` (`d.dd`), `ModelGuid`, `IdMap` (entries in file order, or null), `IdMapField65` and `IdMapField73` (raw numbers, null when the id map is not read), `Payload` (the whole unpacked file; offsets refer to it). `ReadTextSections()` and `ReadTables()` read on request and build new lists on each call. `ReadModel()` decodes a connected, read-only object model graph () of parts, assemblies, bolts, welds and attributes. |
| `IdMapEntry` | `Sequence`, `Id` (GUID) and `Value` (raw, meaning not known). |
| `TextSection` | A section of 54-byte text rows: `Offset`, `RowCount`, `Chains` (in the file order of their heads) and `OrphanRowIds` (rows that belong to no chain, reported instead of dropped). The links of all rows are checked, orphans included: a link to a missing id, a cycle or two rows linking to one row is an error. |
| `TextChain` | One text: `HeadId`, `HeadTag` and `HeadField13` (raw), `RowIds` (chain order), `Text` (the bytes as stored, not decoded). `IsSaveStamp` is true when the text starts with `Save:`; `SavedAt` is its date and time, or null. `RevealSaveText()` returns the revealed bytes of a save stamp: fields separated by `;`. Fields after the date and time can hold names of people or machines; do not log them. |
@@ -80,8 +80,8 @@ offset or line number. A warning never contains text from the file. Warnings are
| Type | Use |
| --- | --- |
-| `TableSection` | A section of fixed-size rows, from `Db1Document.ReadTables()` or `DbvDocument.Sections`. `Ordinal`, `Offset`, `End`, `Key` (raw, `.db1` only, else null), `RowSize`, `Descriptors` (raw), `RowsOffset` and `Rows`. Sections have no names; tell them apart by `Ordinal` and `RowSize`. `Rows` is a view over the data: a row is built when it is read. |
-| `TableRow` | `Offset` (of the marker byte), `Marker`, `Body` (`RowSize` raw bytes), `A` and `B` (the two numbers after the body: signed 32-bit in `.db1` files, unsigned in DBV@ files). |
+| `TableSection` | A section of fixed-size rows, from `Db1Document.ReadTables()` or `DbvDocument.Sections`. `Ordinal`, `Offset`, `End`, `Key` (raw, `.db1` only, else null), `RowSize`, `Descriptors` (raw), `RowsOffset` and `Rows`. Sections have no names; tell them apart by `Ordinal` and `RowSize`. `Rows` is a view over the data: a row is built when it is read. Typed bulk decoders (`AsObjects()`, `AsParts()`, `AsPoints()`, etc.) decode all rows into typed record structs. |
+| `TableRow` | `Offset` (of the marker byte), `Marker`, `Body` (`RowSize` raw bytes), `A` and `B` (the two numbers after the body: signed 32-bit in `.db1` files, unsigned in DBV@ files). Typed decoders (`AsObject()`, `AsPart()`, `AsPoint()`, etc.) decode the row body into typed record structs. |
| `DbvDocument` | A DBV@ file: `Name`, `Prologue`, `ListHeader`, `GuidRecords`, `B`, `C`, `L1`, `L2`, `T`, `C9Records`, `Sections` and `Payload`. The numbers are raw; their names are positions, not meanings. |
| `DbvGuidRecord` | `Value` (raw), `Index` (1-based, checked against the position) and `Id`. |
| `DbvC9Record` | A record that starts with `C9 C0 CE DB`: four raw numbers `R0` to `R3`. |
@@ -90,6 +90,50 @@ The walk of a model database starts at its first table section and must end exac
without a key after one with a key, a gap or bytes after the last section is an error. The bytes before the first
section, other than the header and the id map, are not interpreted; read them from `Payload`.
+## Decoded table rows
+
+Typed record structs decoded from the row bodies of the most common model database table sections:
+
+| Type | Table Key | Size | Contents |
+| --- | --- | --- | --- |
+| `ObjectRow` | 1 | 72 | `Id`, `ParentId` (`kuuluu`), `AssemblyId`, `Guid` (128-bit RFC 4122), `Type`, `Subtype`, `ExternalType`, `Mask1`, `Mask2`, `ObjFlag`, `OwnerId`, `PrivilegeId`. |
+| `AssemblyRow` | 2 | 92 | `Id`, `Type`, `Class`, `MainPartId` (`dum`), `Lot`, `Name`, `Flags`, `MainPartByUser`. |
+| `CoordsysRow` | 3 | 40 | `Id`, `AttrId`, origin coordinates `X`, `Y`, `Z`, `Length`. |
+| `PartRow` | 10 | 64 | `Id`, `PartAttrId`, `PositioningAttrId`, `StartPointId` (`p1`), `EndPointId` (`p2`), `GeometryTreeRootId`, `CoordsysAttrId`, `Reserved`, local coordinate system `CoordsysX`, `CoordsysY`, `CoordsysZ`, `Length`. |
+| `PointRow` | 13 | 32 | `Id`, `Visibility`, 3D coordinates `X`, `Y`, `Z` in millimeters. |
+| `RelationRow` | 16 | 60 | `Id`, `Type`, `Id1`, `Id2`, `Guid` (string), `Flags`. |
+| `WeldingRow` | 20 | 24 | `Id`, `CommonAttrId`, `Seam1Id`, `Seam2Id`, `CompoundSeam1Id`, `CompoundSeam2Id`. |
+| `NumAttrRow` | 38 | 24 | `Id`, `AttrId`, `FatherId`, `OwnerId`, `Flags`, `NameId`. |
+| `StrAttrRow` | 39 | 24 | `Id`, `AttrId`, `FatherId`, `OwnerId`, `Flags`, `NameId`. |
+| `PartAttrRow` | 44 | 372 | `Id`, `ObjType`, `FormType`, `ObjClass`, `AssStartNo`, `Flags`, `NPoints`, `PartFlags`, `Prefix`, `Name`, `Profile`, `ParameterStringId`, `AssemblyPosition`, `AssemblyName`, `Material`, `Finish`, `AssemblyType`, `PourPhase`. |
+| `NumAttrAttrRow` | 48 | 44 | `Id`, `Type`, `Value` (double), `Name`, `PrivilegeId`. |
+| `StrAttrAttrRow` | 49 | 120 | `Id`, `Type`, `Name`, `Value` (string), `ValueId`, `PrivilegeId`. |
+| `StringPoolRow` | 50 | 45 | `Id`, `NextId`, `HashId`, `RefCount`, `Text`. |
+| `PartNumberingRow` | 94 | 68 | `Id`, `SeriesId`, `StartNumber`, `FPos`, `MultiFPos`, `Prefix`. |
+| `AssemblyNumberingRow` | 95 | 76 | `Id`, `SeriesId`, `StartNumber`, `FPos`, `FamilyFPos`, `QualifierFPos`, `MultiFPos`, `Prefix`. |
+| `ObjectNumberingRow` | 105 | 12 | `Id`, `NumberId`, `NumberingGroup`. |
+| `BoltRow` | 107 | 24 | `Id`, `BoltAttrId`, `PositioningAttrId`, `FirstPointId` (`p1`), `SecondPointId` (`p2`), `PolygonId`. |
+| `ObjectModificationRow` | 132 | 20 | `ModificationId`, `Id`, `ModType`, `DependencyId`, `ModTime`. |
+| `BoltHoleRow` | 140 | 48 | `BoltId`, `No`, `PartId`, `PointZ`, `Length`, `LongHoleDir`, `LongHoleType`, `ShorteningLength`. |
+| `ObjectPhaseRow` | 141 | 8 | `ObjectId`, `PhaseNumber`. |
+| `BoltHolePointsRow` | 142 | 60 | `BoltId`, intermediate coordinates `IntPoint1X`, `IntPoint1Y`, `IntPoint1Z`, `IntPoint2X`, `IntPoint2Y`, `IntPoint2Z`, `NumHoles`. |
+
+## Object model: parts, assemblies, bolts and welds
+
+High-level connected object model produced by `Db1Document.ReadModel()`:
+
+| Type | Use |
+| --- | --- |
+| `TeklaModel` | Decoded object graph: `Document`, `ModelGuid`, `Assemblies`, `Parts`, `Bolts`, `Welds`, `Objects`. Fast lookup methods: `FindObject(id/guid)`, `FindPart(id)`, `FindAssembly(id)`, `FindBolt(id)`, `FindWeld(id)`. |
+| `ModelObject` | Base entity: `Id`, `Guid` (RFC 4122), `Type`, `Subtype`, `Phase`, `ParentId`, `AssemblyId`, `StringAttributes`, `NumericAttributes`, `GetStringAttribute(name)`, `GetNumericAttribute(name)`. |
+| `ModelAssembly` | Assembly / cast unit: `Name`, `Prefix`, `StartNumber`, `PositionNumber`, `AssemblyType`, `Class`, `MainPart`, `Secondaries`, `Parts`, `Bolts`, `Welds`. |
+| `ModelPart` | Structural part: `Name`, `Profile` (resolved with parameter strings), `Material`, `Prefix`, `StartNumber`, `PositionNumber`, `Class`, `Finish`, `Assembly`, `IsMainPart`, `StartPoint`, `EndPoint`, `Length`, `CoordinateSystem`, `Bolts`, `Welds`. |
+| `ModelBolt` | Bolt group: `FirstPoint`, `SecondPoint`, `ConnectedParts`, `Holes`, `Positions`, `Assembly`. |
+| `ModelWeld` | Structural weld: `CommonAttrId`, `Parent`, `Assembly`, `ConnectedParts`. |
+| `ModelPoint` | 3D coordinate point in millimeters: `Id`, `X`, `Y`, `Z`. |
+| `ModelCoordsys` | Local coordinate system origin and scale: `Id`, `X`, `Y`, `Z`, `Length`. |
+| `ModelBoltHole` | Bolt hole penetration: `No`, `PartId`, `Part`, `PointZ`, `Length`, `LongHoleDir`, `LongHoleType`, `ShorteningLength`. |
+
## Files next to the model
| Type | Use |
diff --git a/src/TdbIO/Db1Document.Tables.cs b/src/TdbIO/Db1Document.Tables.cs
index a81ee1a..4776d8f 100644
--- a/src/TdbIO/Db1Document.Tables.cs
+++ b/src/TdbIO/Db1Document.Tables.cs
@@ -12,4 +12,8 @@ public sealed partial class Db1Document
/// or bytes are left after the last section. The message names the section and the offset.
public IReadOnlyList ReadTables() =>
SectionWalker.Walk(Payload, SectionWalker.FindFirstSection(Payload.Span), 0, SectionMode.Db1, null);
+
+ /// Decodes the table sections into a connected, read-only object model of parts, assemblies, bolts, welds and attributes.
+ /// A new representing the decoded model object graph.
+ public TeklaModel ReadModel() => ModelBuilder.Build(this);
}
diff --git a/src/TdbIO/Internal/Bytes.cs b/src/TdbIO/Internal/Bytes.cs
index 1bc77c2..0de7ada 100644
--- a/src/TdbIO/Internal/Bytes.cs
+++ b/src/TdbIO/Internal/Bytes.cs
@@ -1,4 +1,5 @@
using System.Buffers.Binary;
+using System.Text;
namespace TdbIO.Internal;
@@ -37,4 +38,40 @@ public static uint U32BE(ReadOnlySpan d, long at)
Need(at, 4, d.Length, "u32");
return BinaryPrimitives.ReadUInt32BigEndian(d[(int)at..]);
}
+
+ public static double F64(ReadOnlySpan d, long at)
+ {
+ Need(at, 8, d.Length, "f64");
+ return BinaryPrimitives.ReadDoubleLittleEndian(d[(int)at..]);
+ }
+
+ public static float F32(ReadOnlySpan d, long at)
+ {
+ Need(at, 4, d.Length, "f32");
+ return BinaryPrimitives.ReadSingleLittleEndian(d[(int)at..]);
+ }
+
+ public static Guid Guid(ReadOnlySpan d, long at)
+ {
+ Need(at, 16, d.Length, "guid");
+ return new Guid(d.Slice((int)at, 16), bigEndian: true);
+ }
+
+ private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
+
+ public static string AsciiString(ReadOnlySpan d, long at, int length)
+ {
+ Need(at, length, d.Length, "string");
+ var span = d.Slice((int)at, length);
+ int nul = span.IndexOf((byte)0);
+ if (nul >= 0) span = span[..nul];
+ try
+ {
+ return StrictUtf8.GetString(span);
+ }
+ catch (DecoderFallbackException e)
+ {
+ throw FormatError.At("invalid UTF-8 string", at + Math.Max(0, e.Index), e);
+ }
+ }
}
diff --git a/src/TdbIO/Internal/ModelBuilder.cs b/src/TdbIO/Internal/ModelBuilder.cs
new file mode 100644
index 0000000..c59fe0a
--- /dev/null
+++ b/src/TdbIO/Internal/ModelBuilder.cs
@@ -0,0 +1,546 @@
+using System.Text;
+
+namespace TdbIO.Internal;
+
+internal static class ModelBuilder
+{
+ private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
+
+ public static TeklaModel Build(Db1Document doc)
+ {
+ ArgumentNullException.ThrowIfNull(doc);
+ return BuildFromSections(doc, doc.ReadTables());
+ }
+
+ internal static TeklaModel BuildFromSections(Db1Document doc, IReadOnlyList sections)
+ {
+ ArgumentNullException.ThrowIfNull(doc);
+ ArgumentNullException.ThrowIfNull(sections);
+
+ // 1. Decoded active row collections (Marker == 0x0C excluded)
+ var objRows = GetActiveRows(FindSection(sections, ObjectRow.TableKey, ObjectRow.ExpectedRowSize), ObjectRow.ExpectedRowSize, r => r.AsObject());
+ var assRows = GetActiveRows(FindSection(sections, AssemblyRow.TableKey, AssemblyRow.ExpectedRowSize), AssemblyRow.ExpectedRowSize, r => r.AsAssembly());
+ var partRows = GetActiveRows(FindSection(sections, PartRow.TableKey, PartRow.ExpectedRowSize), PartRow.ExpectedRowSize, r => r.AsPart());
+ var boltRows = GetActiveRows(FindSection(sections, BoltRow.TableKey, BoltRow.ExpectedRowSize), BoltRow.ExpectedRowSize, r => r.AsBolt());
+ var weldRows = GetActiveRows(FindSection(sections, WeldingRow.TableKey, WeldingRow.ExpectedRowSize), WeldingRow.ExpectedRowSize, r => r.AsWelding());
+ var ptRows = GetActiveRows(FindSection(sections, PointRow.TableKey, PointRow.ExpectedRowSize), PointRow.ExpectedRowSize, r => r.AsPoint());
+ var csysRows = GetActiveRows(FindSection(sections, CoordsysRow.TableKey, CoordsysRow.ExpectedRowSize), CoordsysRow.ExpectedRowSize, r => r.AsCoordsys());
+ var paRows = GetActiveRows(FindSection(sections, PartAttrRow.TableKey, PartAttrRow.ExpectedRowSize), PartAttrRow.ExpectedRowSize, r => r.AsPartAttr());
+ var strPoolRows = GetActiveRows(FindSection(sections, StringPoolRow.TableKey, StringPoolRow.ExpectedRowSize), StringPoolRow.ExpectedRowSize, r => r.AsStringPool());
+ var numAttrRows = GetActiveRows(FindSection(sections, NumAttrRow.TableKey, NumAttrRow.ExpectedRowSize), NumAttrRow.ExpectedRowSize, r => r.AsNumAttr());
+ var strAttrRows = GetActiveRows(FindSection(sections, StrAttrRow.TableKey, StrAttrRow.ExpectedRowSize), StrAttrRow.ExpectedRowSize, r => r.AsStrAttr());
+ var numDefRows = GetActiveRows(FindSection(sections, NumAttrAttrRow.TableKey, NumAttrAttrRow.ExpectedRowSize), NumAttrAttrRow.ExpectedRowSize, r => r.AsNumAttrAttr());
+ var strDefRows = GetActiveRows(FindSection(sections, StrAttrAttrRow.TableKey, StrAttrAttrRow.ExpectedRowSize), StrAttrAttrRow.ExpectedRowSize, r => r.AsStrAttrAttr());
+ var phaseRows = GetActiveRows(FindSection(sections, ObjectPhaseRow.TableKey, ObjectPhaseRow.ExpectedRowSize), ObjectPhaseRow.ExpectedRowSize, r => r.AsObjectPhase());
+ var partNumRows = GetActiveRows(FindSection(sections, PartNumberingRow.TableKey, PartNumberingRow.ExpectedRowSize), PartNumberingRow.ExpectedRowSize, r => r.AsPartNumbering());
+ var assNumRows = GetActiveRows(FindSection(sections, AssemblyNumberingRow.TableKey, AssemblyNumberingRow.ExpectedRowSize), AssemblyNumberingRow.ExpectedRowSize, r => r.AsAssemblyNumbering());
+ var objNumRows = GetActiveRows(FindSection(sections, ObjectNumberingRow.TableKey, ObjectNumberingRow.ExpectedRowSize), ObjectNumberingRow.ExpectedRowSize, r => r.AsObjectNumbering());
+ var holeRows = GetActiveRows(FindSection(sections, BoltHoleRow.TableKey, BoltHoleRow.ExpectedRowSize), BoltHoleRow.ExpectedRowSize, r => r.AsBoltHole());
+ var boltPtRows = GetActiveRows(FindSection(sections, BoltHolePointsRow.TableKey, BoltHolePointsRow.ExpectedRowSize), BoltHolePointsRow.ExpectedRowSize, r => r.AsBoltHolePoints());
+
+ // 2. Primary lookups
+ var objects = new Dictionary(objRows.Count);
+ foreach (var o in objRows) objects[o.Id] = o;
+
+ // Follow string-pool NextId chain with cycle and missing-link detection
+ var chunksById = new Dictionary(strPoolRows.Count);
+ var childChunkIds = new HashSet();
+ foreach (var sp in strPoolRows)
+ {
+ chunksById[sp.Id] = sp;
+ if (sp.NextId > 0) childChunkIds.Add(sp.NextId);
+ }
+
+ var stringPool = new Dictionary(strPoolRows.Count);
+ var rawBuffer = new List(128);
+ var visitedInCurrentChain = new HashSet();
+ var allVisitedInAnyChain = new HashSet();
+
+ void TraverseChain(StringPoolRow head)
+ {
+ if (allVisitedInAnyChain.Contains(head.Id) && stringPool.ContainsKey(head.Id))
+ return;
+
+ rawBuffer.Clear();
+ visitedInCurrentChain.Clear();
+
+ int currId = head.Id;
+ while (currId > 0)
+ {
+ if (!visitedInCurrentChain.Add(currId))
+ throw FormatError.At($"Cycle detected in string pool chain at id {currId}", 0);
+
+ allVisitedInAnyChain.Add(currId);
+
+ if (!chunksById.TryGetValue(currId, out var chunk))
+ throw FormatError.At($"Missing string pool chunk link {currId}", 0);
+
+ ReadOnlySpan chunkBytes = chunk.RawBytes.Span;
+ if (chunkBytes.IsEmpty && !string.IsNullOrEmpty(chunk.Text))
+ {
+ rawBuffer.AddRange(Encoding.UTF8.GetBytes(chunk.Text));
+ }
+ else if (!chunkBytes.IsEmpty)
+ {
+ int nul = chunkBytes.IndexOf((byte)0);
+ rawBuffer.AddRange(nul >= 0 ? chunkBytes[..nul] : chunkBytes);
+ }
+
+ currId = chunk.NextId;
+ }
+
+ try
+ {
+ stringPool[head.Id] = StrictUtf8.GetString(rawBuffer.ToArray());
+ }
+ catch (DecoderFallbackException e)
+ {
+ throw FormatError.At("Invalid UTF-8 sequence in string pool chain", 0, e);
+ }
+ }
+
+ // Pass 1: Traverse all actual chain heads (chunks not referenced as NextId by any chunk)
+ foreach (var sp in strPoolRows)
+ {
+ if (!childChunkIds.Contains(sp.Id))
+ TraverseChain(sp);
+ }
+
+ // Pass 2: Traverse any remaining unvisited chunks (e.g. to detect orphaned cycles)
+ foreach (var sp in strPoolRows)
+ {
+ if (!allVisitedInAnyChain.Contains(sp.Id))
+ TraverseChain(sp);
+ }
+
+ var points = new Dictionary(ptRows.Count);
+ foreach (var pt in ptRows) points[pt.Id] = new ModelPoint(pt.Id, pt.X, pt.Y, pt.Z);
+
+ var coords = new Dictionary(csysRows.Count);
+ foreach (var cs in csysRows) coords[cs.Id] = new ModelCoordsys(cs.Id, cs.X, cs.Y, cs.Z, cs.Length);
+
+ var partAttrs = new Dictionary(paRows.Count);
+ foreach (var pa in paRows) partAttrs[pa.Id] = pa;
+
+ var phases = new Dictionary(phaseRows.Count);
+ foreach (var ph in phaseRows) phases[ph.ObjectId] = ph.PhaseNumber;
+
+ var partNumbering = new Dictionary(partNumRows.Count);
+ foreach (var pn in partNumRows) partNumbering[pn.Id] = pn;
+
+ var assNumbering = new Dictionary(assNumRows.Count);
+ foreach (var an in assNumRows) assNumbering[an.Id] = an;
+
+ var objNumberIds = new Dictionary(objNumRows.Count);
+ foreach (var on in objNumRows) objNumberIds[on.Id] = on.NumberId;
+
+ // 3. User & System Attributes
+ var numDefs = new Dictionary(numDefRows.Count);
+ foreach (var nd in numDefRows)
+ if (!string.IsNullOrEmpty(nd.Name))
+ numDefs[nd.Id] = (nd.Name, nd.Value);
+
+ var strDefs = new Dictionary(strDefRows.Count);
+ foreach (var sd in strDefRows)
+ {
+ if (string.IsNullOrEmpty(sd.Name)) continue;
+ string val = !string.IsNullOrEmpty(sd.Value)
+ ? sd.Value
+ : (sd.ValueId > 0 && stringPool.TryGetValue(sd.ValueId, out var spVal) ? spVal : string.Empty);
+ strDefs[sd.Id] = (sd.Name, val);
+ }
+
+ var numAttrsByObj = new Dictionary>();
+ foreach (var na in numAttrRows)
+ {
+ if (numDefs.TryGetValue(na.AttrId, out var def))
+ {
+ if (!numAttrsByObj.TryGetValue(na.FatherId, out var dict))
+ numAttrsByObj[na.FatherId] = dict = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ dict[def.Name] = def.Value;
+ }
+ }
+
+ var strAttrsByObj = new Dictionary>();
+ foreach (var sa in strAttrRows)
+ {
+ if (strDefs.TryGetValue(sa.AttrId, out var def))
+ {
+ if (!strAttrsByObj.TryGetValue(sa.FatherId, out var dict))
+ strAttrsByObj[sa.FatherId] = dict = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ dict[def.Name] = def.Value;
+ }
+ }
+
+ // 4. Build Assemblies
+ var assemblies = new List(assRows.Count);
+ var assembliesById = new Dictionary(assRows.Count);
+ foreach (var a in assRows)
+ {
+ var obj = objects.GetValueOrDefault(a.Id);
+ int phase = phases.GetValueOrDefault(a.Id);
+ int anId = objNumberIds.TryGetValue(a.Id, out int mappedAnId) ? mappedAnId : a.Id;
+ assNumbering.TryGetValue(anId, out var an);
+ var numAttrs = numAttrsByObj.GetValueOrDefault(a.Id);
+ var strAttrs = strAttrsByObj.GetValueOrDefault(a.Id);
+
+ var assembly = new ModelAssembly(
+ a.Id,
+ obj.Guid,
+ obj.Type,
+ obj.Subtype,
+ phase,
+ obj.ParentId > 0 ? obj.ParentId : null,
+ a.Name,
+ an.Prefix ?? string.Empty,
+ an.StartNumber,
+ an.FPos,
+ a.Type,
+ a.Class,
+ strAttrs,
+ numAttrs);
+
+ assemblies.Add(assembly);
+ assembliesById[a.Id] = assembly;
+ }
+
+ // 5. Build Parts
+ var parts = new List(partRows.Count);
+ var partsById = new Dictionary(partRows.Count);
+ foreach (var p in partRows)
+ {
+ var obj = objects.GetValueOrDefault(p.Id);
+ int phase = phases.GetValueOrDefault(p.Id);
+ partAttrs.TryGetValue(p.PartAttrId, out var pa);
+ int pnId = objNumberIds.TryGetValue(p.Id, out int mappedPnId) ? mappedPnId : p.Id;
+ partNumbering.TryGetValue(pnId, out var pn);
+
+ string name = pa.Name ?? string.Empty;
+ string rawProf = pa.Profile ?? string.Empty;
+ string paramStr = pa.ParameterStringId > 0 && stringPool.TryGetValue(pa.ParameterStringId, out var sp) ? sp : string.Empty;
+ string profile = string.IsNullOrEmpty(rawProf) ? paramStr : rawProf + paramStr;
+ string material = pa.Material ?? string.Empty;
+ string prefix = !string.IsNullOrEmpty(pn.Prefix) ? pn.Prefix : (pa.Prefix ?? string.Empty);
+ int startNo = pn.StartNumber;
+ int posNo = pn.FPos;
+ int @class = pa.ObjClass;
+ string finish = pa.Finish ?? string.Empty;
+
+ var startPt = points.TryGetValue(p.StartPointId, out var pt1) ? pt1 : (ModelPoint?)null;
+ var endPt = points.TryGetValue(p.EndPointId, out var pt2) ? pt2 : (ModelPoint?)null;
+ var csys = coords.TryGetValue(p.CoordsysAttrId, out var cs) ? cs : (ModelCoordsys?)null;
+
+ var numAttrs = numAttrsByObj.GetValueOrDefault(p.Id);
+ var strAttrs = strAttrsByObj.GetValueOrDefault(p.Id);
+
+ int? assId = obj.AssemblyId > 0 ? obj.AssemblyId : null;
+
+ var part = new ModelPart(
+ p.Id,
+ obj.Guid,
+ obj.Type,
+ obj.Subtype,
+ phase,
+ obj.ParentId > 0 ? obj.ParentId : null,
+ assId,
+ name,
+ profile,
+ material,
+ prefix,
+ startNo,
+ posNo,
+ @class,
+ finish,
+ startPt,
+ endPt,
+ p.Length,
+ csys,
+ strAttrs,
+ numAttrs);
+
+ parts.Add(part);
+ partsById[p.Id] = part;
+ }
+
+ // 6. Build Bolts and Bolt Holes
+ var holesByBolt = new Dictionary>();
+ foreach (var h in holeRows)
+ {
+ if (!holesByBolt.TryGetValue(h.BoltId, out var list))
+ holesByBolt[h.BoltId] = list = new List();
+
+ var connectedPart = partsById.GetValueOrDefault(h.PartId);
+ list.Add(new ModelBoltHole(
+ h.No,
+ h.PartId,
+ connectedPart,
+ h.PointZ,
+ h.Length,
+ h.LongHoleDir,
+ h.LongHoleType,
+ h.ShorteningLength));
+ }
+
+ var patternPtsByBolt = new Dictionary>();
+ foreach (var bp in boltPtRows)
+ {
+ if (!patternPtsByBolt.TryGetValue(bp.BoltId, out var list))
+ patternPtsByBolt[bp.BoltId] = list = new List();
+ list.Add(new ModelPoint(0, bp.IntPoint1X, bp.IntPoint1Y, bp.IntPoint1Z));
+ list.Add(new ModelPoint(0, bp.IntPoint2X, bp.IntPoint2Y, bp.IntPoint2Z));
+ }
+
+ var bolts = new List(boltRows.Count);
+ var boltsById = new Dictionary(boltRows.Count);
+ foreach (var b in boltRows)
+ {
+ var obj = objects.GetValueOrDefault(b.Id);
+ int phase = phases.GetValueOrDefault(b.Id);
+ var pt1 = points.TryGetValue(b.FirstPointId, out var p1) ? p1 : (ModelPoint?)null;
+ var pt2 = points.TryGetValue(b.SecondPointId, out var p2) ? p2 : (ModelPoint?)null;
+ var holes = holesByBolt.GetValueOrDefault(b.Id) ?? (IReadOnlyList)Array.Empty();
+ var positions = patternPtsByBolt.GetValueOrDefault(b.Id) ?? (IReadOnlyList)Array.Empty();
+ var numAttrs = numAttrsByObj.GetValueOrDefault(b.Id);
+ var strAttrs = strAttrsByObj.GetValueOrDefault(b.Id);
+
+ var bolt = new ModelBolt(
+ b.Id,
+ obj.Guid,
+ obj.Type,
+ obj.Subtype,
+ phase,
+ obj.ParentId > 0 ? obj.ParentId : null,
+ obj.AssemblyId > 0 ? obj.AssemblyId : null,
+ pt1,
+ pt2,
+ holes,
+ positions,
+ strAttrs,
+ numAttrs);
+
+ var connectedParts = new List();
+ foreach (var h in holes)
+ {
+ if (h.Part != null && !connectedParts.Contains(h.Part))
+ connectedParts.Add(h.Part);
+ }
+ bolt.ConnectedParts = connectedParts;
+
+ bolts.Add(bolt);
+ boltsById[b.Id] = bolt;
+ }
+
+ // 7. Build Welds
+ var welds = new List(weldRows.Count);
+ var weldsById = new Dictionary(weldRows.Count);
+ foreach (var w in weldRows)
+ {
+ var obj = objects.GetValueOrDefault(w.Id);
+ int phase = phases.GetValueOrDefault(w.Id);
+ var numAttrs = numAttrsByObj.GetValueOrDefault(w.Id);
+ var strAttrs = strAttrsByObj.GetValueOrDefault(w.Id);
+
+ var weld = new ModelWeld(
+ w.Id,
+ obj.Guid,
+ obj.Type,
+ obj.Subtype,
+ phase,
+ obj.ParentId > 0 ? obj.ParentId : null,
+ obj.AssemblyId > 0 ? obj.AssemblyId : null,
+ w.CommonAttrId,
+ strAttrs,
+ numAttrs);
+
+ welds.Add(weld);
+ weldsById[w.Id] = weld;
+ }
+
+ // 8. Link Assemblies, Parts, Bolts and Welds
+ var partsByAssembly = new Dictionary>();
+ foreach (var part in parts)
+ {
+ if (part.AssemblyId.HasValue && assembliesById.TryGetValue(part.AssemblyId.Value, out var ass))
+ {
+ part.Assembly = ass;
+ if (!partsByAssembly.TryGetValue(ass.Id, out var assParts))
+ partsByAssembly[ass.Id] = assParts = new List();
+ assParts.Add(part);
+ }
+ }
+
+ foreach (var assRow in assRows)
+ {
+ if (assembliesById.TryGetValue(assRow.Id, out var ass))
+ {
+ var assParts = partsByAssembly.GetValueOrDefault(ass.Id) ?? new List();
+ ass.Parts = assParts;
+
+ ModelPart? main = null;
+ if (assRow.MainPartId > 0)
+ main = partsById.GetValueOrDefault(assRow.MainPartId);
+ ass.MainPart = main;
+
+ var secondaries = new List(assParts.Count);
+ foreach (var p in assParts)
+ {
+ if (p != main) secondaries.Add(p);
+ }
+ ass.Secondaries = secondaries;
+ }
+ }
+
+ var boltsByPart = new Dictionary>();
+ var boltsByAssembly = new Dictionary>();
+ foreach (var bolt in bolts)
+ {
+ if (bolt.AssemblyId.HasValue && assembliesById.TryGetValue(bolt.AssemblyId.Value, out var ass))
+ {
+ bolt.Assembly = ass;
+ if (!boltsByAssembly.TryGetValue(ass.Id, out var assBolts))
+ boltsByAssembly[ass.Id] = assBolts = new List();
+ assBolts.Add(bolt);
+ }
+
+ foreach (var cp in bolt.ConnectedParts)
+ {
+ if (!boltsByPart.TryGetValue(cp.Id, out var partBolts))
+ boltsByPart[cp.Id] = partBolts = new List();
+ if (!partBolts.Contains(bolt))
+ partBolts.Add(bolt);
+
+ if (cp.Assembly != null)
+ {
+ if (!boltsByAssembly.TryGetValue(cp.Assembly.Id, out var assBolts))
+ boltsByAssembly[cp.Assembly.Id] = assBolts = new List();
+ if (!assBolts.Contains(bolt))
+ assBolts.Add(bolt);
+ }
+ }
+ }
+
+ foreach (var part in parts)
+ part.Bolts = boltsByPart.GetValueOrDefault(part.Id) ?? (IReadOnlyList)Array.Empty();
+
+ foreach (var ass in assemblies)
+ ass.Bolts = boltsByAssembly.GetValueOrDefault(ass.Id) ?? (IReadOnlyList)Array.Empty();
+
+ // Generic objects (Table 1 rows that are not assembly, part, bolt, or weld)
+ var genericObjectsById = new Dictionary();
+ foreach (var o in objRows)
+ {
+ if (!assembliesById.ContainsKey(o.Id) &&
+ !partsById.ContainsKey(o.Id) &&
+ !boltsById.ContainsKey(o.Id) &&
+ !weldsById.ContainsKey(o.Id))
+ {
+ int phase = phases.GetValueOrDefault(o.Id);
+ var numAttrs = numAttrsByObj.GetValueOrDefault(o.Id);
+ var strAttrs = strAttrsByObj.GetValueOrDefault(o.Id);
+ var genObj = new ModelObject(
+ o.Id,
+ o.Guid,
+ o.Type,
+ o.Subtype,
+ phase,
+ o.ParentId > 0 ? o.ParentId : null,
+ o.AssemblyId > 0 ? o.AssemblyId : null,
+ strAttrs,
+ numAttrs);
+ genericObjectsById[o.Id] = genObj;
+ }
+ }
+
+ ModelObject? FindObject(int id)
+ {
+ if (assembliesById.TryGetValue(id, out var a)) return a;
+ if (partsById.TryGetValue(id, out var p)) return p;
+ if (boltsById.TryGetValue(id, out var b)) return b;
+ if (weldsById.TryGetValue(id, out var w)) return w;
+ if (genericObjectsById.TryGetValue(id, out var g)) return g;
+ return null;
+ }
+
+ // Link welds
+ var weldsByPart = new Dictionary>();
+ var weldsByAssembly = new Dictionary>();
+ foreach (var weld in welds)
+ {
+ if (weld.AssemblyId.HasValue && assembliesById.TryGetValue(weld.AssemblyId.Value, out var ass))
+ {
+ weld.Assembly = ass;
+ if (!weldsByAssembly.TryGetValue(ass.Id, out var assWelds))
+ weldsByAssembly[ass.Id] = assWelds = new List();
+ assWelds.Add(weld);
+ }
+
+ // Resolve weld parent from complete object index (including generic connections/components)
+ if (weld.ParentId.HasValue)
+ {
+ var parent = FindObject(weld.ParentId.Value);
+ if (parent != null)
+ {
+ weld.Parent = parent;
+ if (weld.Assembly == null)
+ {
+ if (parent is ModelAssembly parentAss)
+ weld.Assembly = parentAss;
+ else if (parent is ModelPart parentPart)
+ weld.Assembly = parentPart.Assembly;
+ else if (parent.AssemblyId.HasValue && assembliesById.TryGetValue(parent.AssemblyId.Value, out var objAss))
+ weld.Assembly = objAss;
+ }
+ }
+ }
+
+ if (weld.Assembly != null)
+ {
+ if (!weldsByAssembly.TryGetValue(weld.Assembly.Id, out var assWelds))
+ weldsByAssembly[weld.Assembly.Id] = assWelds = new List();
+ if (!assWelds.Contains(weld))
+ assWelds.Add(weld);
+ }
+ }
+
+ foreach (var part in parts)
+ part.Welds = weldsByPart.GetValueOrDefault(part.Id) ?? (IReadOnlyList)Array.Empty();
+
+ foreach (var ass in assemblies)
+ ass.Welds = weldsByAssembly.GetValueOrDefault(ass.Id) ?? (IReadOnlyList)Array.Empty();
+
+ // 9. All objects list
+ var allObjects = new List(assemblies.Count + parts.Count + bolts.Count + welds.Count + genericObjectsById.Count);
+ allObjects.AddRange(assemblies);
+ allObjects.AddRange(parts);
+ allObjects.AddRange(bolts);
+ allObjects.AddRange(welds);
+ allObjects.AddRange(genericObjectsById.Values);
+
+ return new TeklaModel(doc, doc.ModelGuid, assemblies, parts, bolts, welds, allObjects);
+ }
+
+ private static List GetActiveRows(TableSection? section, int expectedSize, Func decode)
+ {
+ if (section == null || section.RowSize != expectedSize)
+ return [];
+ var list = new List(section.Rows.Count);
+ for (int i = 0; i < section.Rows.Count; i++)
+ {
+ var row = section.Rows[i];
+ if (row.Marker == 0x0C) continue;
+ list.Add(decode(row));
+ }
+ return list;
+ }
+
+ private static TableSection? FindSection(IReadOnlyList sections, int key, int rowSize)
+ {
+ for (int i = 0; i < sections.Count; i++)
+ {
+ var s = sections[i];
+ if (s.Key == key && s.RowSize == rowSize)
+ return s;
+ }
+ return null;
+ }
+}
diff --git a/src/TdbIO/ModelRows.cs b/src/TdbIO/ModelRows.cs
new file mode 100644
index 0000000..4f31451
--- /dev/null
+++ b/src/TdbIO/ModelRows.cs
@@ -0,0 +1,824 @@
+using TdbIO.Internal;
+
+namespace TdbIO;
+
+/// Decoded row of table 1 (object, size 72): object hierarchy, GUID, type, and status flags.
+/// The unique object identifier (primary key).
+/// The parent object identifier (kuuluu).
+/// The assembly identifier the object belongs to.
+/// The 128-bit RFC 4122 GUID of the object.
+/// The object type code (e.g. 1 for part, 2 for assembly).
+/// The object subtype code.
+/// The external type GUID.
+/// The first mask word.
+/// The second mask word.
+/// The object status flags.
+/// The owner identifier.
+/// The privilege or access control identifier.
+public readonly record struct ObjectRow(
+ int Id,
+ int ParentId,
+ int AssemblyId,
+ Guid Guid,
+ int Type,
+ int Subtype,
+ Guid ExternalType,
+ int Mask1,
+ int Mask2,
+ int ObjFlag,
+ int OwnerId,
+ int PrivilegeId)
+{
+ /// The expected row body size in bytes: 72.
+ public const int ExpectedRowSize = 72;
+
+ /// The table key in model database sections: 1.
+ public const int TableKey = 1;
+
+ /// Decodes a row body into an .
+ public static ObjectRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.Guid(body, 12),
+ Bytes.I32(body, 28),
+ Bytes.I32(body, 32),
+ Bytes.Guid(body, 36),
+ Bytes.I32(body, 52),
+ Bytes.I32(body, 56),
+ Bytes.I32(body, 60),
+ Bytes.I32(body, 64),
+ Bytes.I32(body, 68));
+ }
+
+ /// Decodes the body of into an .
+ public static ObjectRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 2 (assembly, size 92): assembly definition and main part reference.
+/// The assembly identifier (primary key).
+/// The assembly type code.
+/// The assembly class code.
+/// The identifier of the main part (dum).
+/// The lot/tracking number.
+/// The assembly name (e.g. "BEAM", "COLUMN", "SLAB").
+/// Assembly flags.
+/// Whether the main part was set explicitly by the user.
+public readonly record struct AssemblyRow(
+ int Id,
+ int Type,
+ int Class,
+ int MainPartId,
+ int Lot,
+ string Name,
+ int Flags,
+ int MainPartByUser)
+{
+ /// The expected row body size in bytes: 92.
+ public const int ExpectedRowSize = 92;
+
+ /// The table key in model database sections: 2.
+ public const int TableKey = 2;
+
+ /// Decodes a row body into an .
+ public static AssemblyRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.AsciiString(body, 20, 64),
+ Bytes.I32(body, 84),
+ Bytes.I32(body, 88));
+ }
+
+ /// Decodes the body of into an .
+ public static AssemblyRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 3 (coordsys, size 40): coordinate system origin and length.
+/// The coordinate system identifier (primary key).
+/// The coordinate system attribute identifier.
+/// Origin X coordinate.
+/// Origin Y coordinate.
+/// Origin Z coordinate.
+/// Coordinate system length or scale factor.
+public readonly record struct CoordsysRow(int Id, int AttrId, double X, double Y, double Z, double Length)
+{
+ /// The expected row body size in bytes: 40.
+ public const int ExpectedRowSize = 40;
+
+ /// The table key in model database sections: 3.
+ public const int TableKey = 3;
+
+ /// Decodes a row body into a .
+ public static CoordsysRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.F64(body, 8),
+ Bytes.F64(body, 16),
+ Bytes.F64(body, 24),
+ Bytes.F64(body, 32));
+ }
+
+ /// Decodes the body of into a .
+ public static CoordsysRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 10 (part, size 64): part reference points and local coordinate system.
+/// The part identifier (primary key).
+/// The attribute identifier in table 44 (part_attr).
+/// The positioning attribute identifier.
+/// The start point identifier in table 13 (point).
+/// The end point identifier in table 13 (point).
+/// The geometry tree root node identifier.
+/// The coordinate system attribute identifier.
+/// Reserved integer field.
+/// Local coordinate system origin X.
+/// Local coordinate system origin Y.
+/// Local coordinate system origin Z.
+/// Length of the part.
+public readonly record struct PartRow(
+ int Id,
+ int PartAttrId,
+ int PositioningAttrId,
+ int StartPointId,
+ int EndPointId,
+ int GeometryTreeRootId,
+ int CoordsysAttrId,
+ int Reserved,
+ double CoordsysX,
+ double CoordsysY,
+ double CoordsysZ,
+ double Length)
+{
+ /// The expected row body size in bytes: 64.
+ public const int ExpectedRowSize = 64;
+
+ /// The table key in model database sections: 10.
+ public const int TableKey = 10;
+
+ /// Decodes a row body into a .
+ public static PartRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.I32(body, 20),
+ Bytes.I32(body, 24),
+ Bytes.I32(body, 28),
+ Bytes.F64(body, 32),
+ Bytes.F64(body, 40),
+ Bytes.F64(body, 48),
+ Bytes.F64(body, 56));
+ }
+
+ /// Decodes the body of into a .
+ public static PartRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 13 (point, size 32): 3D coordinates and visibility.
+/// The point identifier (primary key).
+/// Point visibility flags.
+/// 3D X coordinate in millimeters.
+/// 3D Y coordinate in millimeters.
+/// 3D Z coordinate in millimeters.
+public readonly record struct PointRow(int Id, int Visibility, double X, double Y, double Z)
+{
+ /// The expected row body size in bytes: 32.
+ public const int ExpectedRowSize = 32;
+
+ /// The table key in model database sections: 13.
+ public const int TableKey = 13;
+
+ /// Decodes a row body into a .
+ public static PointRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.F64(body, 8),
+ Bytes.F64(body, 16),
+ Bytes.F64(body, 24));
+ }
+
+ /// Decodes the body of into a .
+ public static PointRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 16 (relation, size 60): relationship between two objects.
+/// The relation identifier (primary key).
+/// The relation type code.
+/// The first related object identifier.
+/// The second related object identifier.
+/// The relation GUID string.
+/// Relation flags.
+public readonly record struct RelationRow(int Id, int Type, int Id1, int Id2, string Guid, int Flags)
+{
+ /// The expected row body size in bytes: 60.
+ public const int ExpectedRowSize = 60;
+
+ /// The table key in model database sections: 16.
+ public const int TableKey = 16;
+
+ /// Decodes a row body into a .
+ public static RelationRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.AsciiString(body, 16, 40),
+ Bytes.I32(body, 56));
+ }
+
+ /// Decodes the body of into a .
+ public static RelationRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 20 (welding, size 24): weld connection and seam references.
+/// The weld identifier (primary key).
+/// Identifier of common weld attributes in table 98 (welding_common_attr).
+/// Identifier of seam 1 in table 46 (welding_attr).
+/// Identifier of seam 2 in table 46 (welding_attr).
+/// Compound seam 1 identifier.
+/// Compound seam 2 identifier.
+public readonly record struct WeldingRow(int Id, int CommonAttrId, int Seam1Id, int Seam2Id, int CompoundSeam1Id, int CompoundSeam2Id)
+{
+ /// The expected row body size in bytes: 24.
+ public const int ExpectedRowSize = 24;
+
+ /// The table key in model database sections: 20.
+ public const int TableKey = 20;
+
+ /// Decodes a row body into a .
+ public static WeldingRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.I32(body, 20));
+ }
+
+ /// Decodes the body of into a .
+ public static WeldingRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 38 (numattr, size 24): numeric attribute association.
+/// The numeric attribute row identifier (primary key).
+/// Identifier of the attribute value in table 48 (numattr_attr).
+/// Identifier of the object owning the attribute.
+/// Attribute owner identifier.
+/// Attribute flags.
+/// Identifier of the attribute name.
+public readonly record struct NumAttrRow(int Id, int AttrId, int FatherId, int OwnerId, int Flags, int NameId)
+{
+ /// The expected row body size in bytes: 24.
+ public const int ExpectedRowSize = 24;
+
+ /// The table key in model database sections: 38.
+ public const int TableKey = 38;
+
+ /// Decodes a row body into a .
+ public static NumAttrRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.I32(body, 20));
+ }
+
+ /// Decodes the body of into a .
+ public static NumAttrRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 39 (strattr, size 24): string attribute association.
+/// The string attribute row identifier (primary key).
+/// Identifier of the attribute value in table 49 (strattr_attr).
+/// Identifier of the object owning the attribute.
+/// Attribute owner identifier.
+/// Attribute flags.
+/// Identifier of the attribute name.
+public readonly record struct StrAttrRow(int Id, int AttrId, int FatherId, int OwnerId, int Flags, int NameId)
+{
+ /// The expected row body size in bytes: 24.
+ public const int ExpectedRowSize = 24;
+
+ /// The table key in model database sections: 39.
+ public const int TableKey = 39;
+
+ /// Decodes a row body into a .
+ public static StrAttrRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.I32(body, 20));
+ }
+
+ /// Decodes the body of into a .
+ public static StrAttrRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 44 (part_attr, size 372): part profile, material, finish, and classification.
+/// The part attribute identifier (primary key).
+/// Object type code.
+/// Form type code.
+/// Part class number (color/display class).
+/// Assembly start number.
+/// Attribute flags.
+/// Number of points.
+/// Additional part flags.
+/// Part numbering prefix / group.
+/// Part name (e.g. "BEAM", "COLUMN", "PLATE").
+/// Part profile name (e.g. "IPE300", "HEA200", "PL10*100").
+/// Identifier in the string table for parameter strings.
+/// Assembly position prefix.
+/// Assembly name.
+/// Material grade (e.g. "S235JR", "S355J2").
+/// Part surface finish.
+/// Assembly type code.
+/// Pour phase number.
+public readonly record struct PartAttrRow(
+ int Id,
+ int ObjType,
+ int FormType,
+ int ObjClass,
+ int AssStartNo,
+ int Flags,
+ int NPoints,
+ int PartFlags,
+ string Prefix,
+ string Name,
+ string Profile,
+ int ParameterStringId,
+ string AssemblyPosition,
+ string AssemblyName,
+ string Material,
+ string Finish,
+ int AssemblyType,
+ int PourPhase)
+{
+ /// The expected row body size in bytes: 372.
+ public const int ExpectedRowSize = 372;
+
+ /// The table key in model database sections: 44.
+ public const int TableKey = 44;
+
+ /// Decodes a row body into a .
+ public static PartAttrRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.I32(body, 20),
+ Bytes.I32(body, 24),
+ Bytes.I32(body, 28),
+ Bytes.AsciiString(body, 32, 22),
+ Bytes.AsciiString(body, 54, 62),
+ Bytes.AsciiString(body, 116, 62),
+ Bytes.I32(body, 180),
+ Bytes.AsciiString(body, 184, 22),
+ Bytes.AsciiString(body, 206, 62),
+ Bytes.AsciiString(body, 268, 32),
+ Bytes.AsciiString(body, 300, 62),
+ Bytes.I32(body, 364),
+ Bytes.I32(body, 368));
+ }
+
+ /// Decodes the body of into a .
+ public static PartAttrRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 48 (numattr_attr, size 44): numeric attribute definition and value.
+/// The attribute value identifier (primary key).
+/// Value type code.
+/// The numeric attribute value.
+/// The attribute name.
+/// Access privilege identifier.
+public readonly record struct NumAttrAttrRow(int Id, int Type, double Value, string Name, int PrivilegeId)
+{
+ /// The expected row body size in bytes: 44.
+ public const int ExpectedRowSize = 44;
+
+ /// The table key in model database sections: 48.
+ public const int TableKey = 48;
+
+ /// Decodes a row body into a .
+ public static NumAttrAttrRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.F64(body, 8),
+ Bytes.AsciiString(body, 16, 21),
+ Bytes.I32(body, 40));
+ }
+
+ /// Decodes the body of into a .
+ public static NumAttrAttrRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 49 (strattr_attr, size 120): string attribute definition and value.
+/// The attribute value identifier (primary key).
+/// Value type code.
+/// The attribute name.
+/// The string attribute value.
+/// Extended value identifier.
+/// Access privilege identifier.
+public readonly record struct StrAttrAttrRow(int Id, int Type, string Name, string Value, int ValueId, int PrivilegeId)
+{
+ /// The expected row body size in bytes: 120.
+ public const int ExpectedRowSize = 120;
+
+ /// The table key in model database sections: 49.
+ public const int TableKey = 49;
+
+ /// Decodes a row body into a .
+ public static StrAttrAttrRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.AsciiString(body, 8, 21),
+ Bytes.AsciiString(body, 29, 81),
+ Bytes.I32(body, 112),
+ Bytes.I32(body, 116));
+ }
+
+ /// Decodes the body of into a .
+ public static StrAttrAttrRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 50 (string, size 45): string pool chunk.
+/// The string chunk identifier (primary key).
+/// Identifier of the next chunk in a chained string, or negative if terminating.
+/// Hash code of the string.
+/// Reference count.
+/// The text content of this chunk.
+/// The raw bytes of this chunk (up to 29 bytes).
+public readonly record struct StringPoolRow(int Id, int NextId, int HashId, int RefCount, string Text, ReadOnlyMemory RawBytes = default)
+{
+ /// The expected row body size in bytes: 45.
+ public const int ExpectedRowSize = 45;
+
+ /// The table key in model database sections: 50.
+ public const int TableKey = 50;
+
+ /// Decodes a row body into a .
+ public static StringPoolRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ int id = Bytes.I32(body, 0);
+ int nextId = Bytes.I32(body, 4);
+ int hashId = Bytes.I32(body, 8);
+ int refCount = Bytes.I32(body, 12);
+ var rawChunk = body.Slice(16, 29).ToArray();
+ string text;
+ try
+ {
+ text = Bytes.AsciiString(body, 16, 29);
+ }
+ catch (InvalidDataException)
+ {
+ // A chunk in a chained string may split multi-byte UTF-8 sequences.
+ // ModelBuilder reconstructs the full string across all chunks.
+ text = string.Empty;
+ }
+ return new(id, nextId, hashId, refCount, text, rawChunk);
+ }
+
+ /// Decodes the body of into a .
+ public static StringPoolRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 94 (part_numbering, size 68): part numbering series and mark prefix.
+/// The numbering identifier (primary key).
+/// Numbering series identifier.
+/// Start number of the numbering series.
+/// Fabrication position number.
+/// Multi-position number.
+/// Part mark prefix string.
+public readonly record struct PartNumberingRow(int Id, int SeriesId, int StartNumber, int FPos, int MultiFPos, string Prefix)
+{
+ /// The expected row body size in bytes: 68.
+ public const int ExpectedRowSize = 68;
+
+ /// The table key in model database sections: 94.
+ public const int TableKey = 94;
+
+ /// Decodes a row body into a .
+ public static PartNumberingRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.AsciiString(body, 20, 48));
+ }
+
+ /// Decodes the body of into a .
+ public static PartNumberingRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 95 (assembly_numbering, size 76): assembly numbering series and mark prefix.
+/// The numbering identifier (primary key).
+/// Numbering series identifier.
+/// Start number of the numbering series.
+/// Assembly position number.
+/// Family position number.
+/// Qualifier position number.
+/// Multi-position number.
+/// Assembly mark prefix string.
+public readonly record struct AssemblyNumberingRow(
+ int Id,
+ int SeriesId,
+ int StartNumber,
+ int FPos,
+ int FamilyFPos,
+ int QualifierFPos,
+ int MultiFPos,
+ string Prefix)
+{
+ /// The expected row body size in bytes: 76.
+ public const int ExpectedRowSize = 76;
+
+ /// The table key in model database sections: 95.
+ public const int TableKey = 95;
+
+ /// Decodes a row body into an .
+ public static AssemblyNumberingRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.I32(body, 20),
+ Bytes.I32(body, 24),
+ Bytes.AsciiString(body, 28, 48));
+ }
+
+ /// Decodes the body of into an .
+ public static AssemblyNumberingRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 105 (object_numbering, size 12): object numbering association.
+/// The object identifier (primary key).
+/// Numbering entry identifier.
+/// Numbering group code.
+public readonly record struct ObjectNumberingRow(int Id, int NumberId, int NumberingGroup)
+{
+ /// The expected row body size in bytes: 12.
+ public const int ExpectedRowSize = 12;
+
+ /// The table key in model database sections: 105.
+ public const int TableKey = 105;
+
+ /// Decodes a row body into an .
+ public static ObjectNumberingRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8));
+ }
+
+ /// Decodes the body of into an .
+ public static ObjectNumberingRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 107 (bolt, size 24): bolt group definition and reference points.
+/// The bolt object identifier (primary key).
+/// Identifier in table 108 (bolt_attr).
+/// Positioning attribute identifier.
+/// First reference point identifier in table 13 (point).
+/// Second reference point identifier in table 13 (point).
+/// Polygon shape identifier.
+public readonly record struct BoltRow(int Id, int BoltAttrId, int PositioningAttrId, int FirstPointId, int SecondPointId, int PolygonId)
+{
+ /// The expected row body size in bytes: 24.
+ public const int ExpectedRowSize = 24;
+
+ /// The table key in model database sections: 107.
+ public const int TableKey = 107;
+
+ /// Decodes a row body into a .
+ public static BoltRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16),
+ Bytes.I32(body, 20));
+ }
+
+ /// Decodes the body of into a .
+ public static BoltRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 132 (object_modification, size 20): object modification timestamp and dependency.
+/// The modification event identifier (primary key).
+/// The object identifier that was modified.
+/// The modification type code.
+/// The dependency object identifier.
+/// The modification timestamp identifier.
+public readonly record struct ObjectModificationRow(int ModificationId, int Id, int ModType, int DependencyId, int ModTime)
+{
+ /// The expected row body size in bytes: 20.
+ public const int ExpectedRowSize = 20;
+
+ /// The table key in model database sections: 132.
+ public const int TableKey = 132;
+
+ /// Decodes a row body into an .
+ public static ObjectModificationRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.I32(body, 12),
+ Bytes.I32(body, 16));
+ }
+
+ /// Decodes the body of into an .
+ public static ObjectModificationRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 140 (bolt_hole, size 48): bolt hole through a connected part.
+/// The bolt group identifier.
+/// The hole index in the bolt group.
+/// The part identifier through which this hole passes.
+/// The Z offset of the hole along the bolt axis.
+/// The grip length of the hole in this part.
+/// Slotted hole direction.
+/// Slotted hole type.
+/// Hole shortening length.
+public readonly record struct BoltHoleRow(
+ int BoltId,
+ int No,
+ int PartId,
+ double PointZ,
+ double Length,
+ int LongHoleDir,
+ int LongHoleType,
+ double ShorteningLength)
+{
+ /// The expected row body size in bytes: 48.
+ public const int ExpectedRowSize = 48;
+
+ /// The table key in model database sections: 140.
+ public const int TableKey = 140;
+
+ /// Decodes a row body into a .
+ public static BoltHoleRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4),
+ Bytes.I32(body, 8),
+ Bytes.F64(body, 16),
+ Bytes.F64(body, 24),
+ Bytes.I32(body, 32),
+ Bytes.I32(body, 36),
+ Bytes.F64(body, 40));
+ }
+
+ /// Decodes the body of into a .
+ public static BoltHoleRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 141 (object_phase, size 8): project phase assignment.
+/// The object identifier.
+/// The phase number.
+public readonly record struct ObjectPhaseRow(int ObjectId, int PhaseNumber)
+{
+ /// The expected row body size in bytes: 8.
+ public const int ExpectedRowSize = 8;
+
+ /// The table key in model database sections: 141.
+ public const int TableKey = 141;
+
+ /// Decodes a row body into an .
+ public static ObjectPhaseRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.I32(body, 4));
+ }
+
+ /// Decodes the body of into an .
+ public static ObjectPhaseRow Decode(TableRow row) => Decode(row.Body.Span);
+}
+
+/// Decoded row of table 142 (bolt_hole_points, size 60): intermediate bolt pattern coordinates.
+/// The bolt group identifier.
+/// First intermediate coordinate X.
+/// First intermediate coordinate Y.
+/// First intermediate coordinate Z.
+/// Second intermediate coordinate X.
+/// Second intermediate coordinate Y.
+/// Second intermediate coordinate Z.
+/// Number of holes in the pattern.
+public readonly record struct BoltHolePointsRow(
+ int BoltId,
+ double IntPoint1X,
+ double IntPoint1Y,
+ double IntPoint1Z,
+ double IntPoint2X,
+ double IntPoint2Y,
+ double IntPoint2Z,
+ int NumHoles)
+{
+ /// The expected row body size in bytes: 60.
+ public const int ExpectedRowSize = 60;
+
+ /// The table key in model database sections: 142.
+ public const int TableKey = 142;
+
+ /// Decodes a row body into a .
+ public static BoltHolePointsRow Decode(ReadOnlySpan body)
+ {
+ if (body.Length < ExpectedRowSize)
+ throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body));
+ return new(
+ Bytes.I32(body, 0),
+ Bytes.F64(body, 8),
+ Bytes.F64(body, 16),
+ Bytes.F64(body, 24),
+ Bytes.F64(body, 32),
+ Bytes.F64(body, 40),
+ Bytes.F64(body, 48),
+ Bytes.I32(body, 56));
+ }
+
+ /// Decodes the body of into a .
+ public static BoltHolePointsRow Decode(TableRow row) => Decode(row.Body.Span);
+}
diff --git a/src/TdbIO/TableRow.cs b/src/TdbIO/TableRow.cs
index 580a1d0..7a33522 100644
--- a/src/TdbIO/TableRow.cs
+++ b/src/TdbIO/TableRow.cs
@@ -10,4 +10,68 @@ namespace TdbIO;
/// The first number after the body: a signed 32-bit value in .db1 files, an unsigned one in DBV@
/// files.
/// The second number after the body, read like .
-public readonly record struct TableRow(long Offset, byte Marker, ReadOnlyMemory Body, long A, long B);
+public readonly record struct TableRow(long Offset, byte Marker, ReadOnlyMemory Body, long A, long B)
+{
+ /// Decodes the row body as an (table 1, size 72).
+ public ObjectRow AsObject() => ObjectRow.Decode(this);
+
+ /// Decodes the row body as an (table 2, size 92).
+ public AssemblyRow AsAssembly() => AssemblyRow.Decode(this);
+
+ /// Decodes the row body as a (table 3, size 40).
+ public CoordsysRow AsCoordsys() => CoordsysRow.Decode(this);
+
+ /// Decodes the row body as a (table 10, size 64).
+ public PartRow AsPart() => PartRow.Decode(this);
+
+ /// Decodes the row body as a (table 13, size 32).
+ public PointRow AsPoint() => PointRow.Decode(this);
+
+ /// Decodes the row body as a (table 16, size 60).
+ public RelationRow AsRelation() => RelationRow.Decode(this);
+
+ /// Decodes the row body as a (table 20, size 24).
+ public WeldingRow AsWelding() => WeldingRow.Decode(this);
+
+ /// Decodes the row body as a (table 38, size 24).
+ public NumAttrRow AsNumAttr() => NumAttrRow.Decode(this);
+
+ /// Decodes the row body as a (table 39, size 24).
+ public StrAttrRow AsStrAttr() => StrAttrRow.Decode(this);
+
+ /// Decodes the row body as a (table 44, size 372).
+ public PartAttrRow AsPartAttr() => PartAttrRow.Decode(this);
+
+ /// Decodes the row body as a (table 48, size 44).
+ public NumAttrAttrRow AsNumAttrAttr() => NumAttrAttrRow.Decode(this);
+
+ /// Decodes the row body as a (table 49, size 120).
+ public StrAttrAttrRow AsStrAttrAttr() => StrAttrAttrRow.Decode(this);
+
+ /// Decodes the row body as a (table 50, size 45).
+ public StringPoolRow AsStringPool() => StringPoolRow.Decode(this);
+
+ /// Decodes the row body as a (table 94, size 68).
+ public PartNumberingRow AsPartNumbering() => PartNumberingRow.Decode(this);
+
+ /// Decodes the row body as an (table 95, size 76).
+ public AssemblyNumberingRow AsAssemblyNumbering() => AssemblyNumberingRow.Decode(this);
+
+ /// Decodes the row body as an (table 105, size 12).
+ public ObjectNumberingRow AsObjectNumbering() => ObjectNumberingRow.Decode(this);
+
+ /// Decodes the row body as a (table 107, size 24).
+ public BoltRow AsBolt() => BoltRow.Decode(this);
+
+ /// Decodes the row body as an (table 132, size 20).
+ public ObjectModificationRow AsObjectModification() => ObjectModificationRow.Decode(this);
+
+ /// Decodes the row body as a (table 140, size 48).
+ public BoltHoleRow AsBoltHole() => BoltHoleRow.Decode(this);
+
+ /// Decodes the row body as an (table 141, size 8).
+ public ObjectPhaseRow AsObjectPhase() => ObjectPhaseRow.Decode(this);
+
+ /// Decodes the row body as a (table 142, size 60).
+ public BoltHolePointsRow AsBoltHolePoints() => BoltHolePointsRow.Decode(this);
+}
diff --git a/src/TdbIO/TableSection.cs b/src/TdbIO/TableSection.cs
index 4cc1f3a..66d548b 100644
--- a/src/TdbIO/TableSection.cs
+++ b/src/TdbIO/TableSection.cs
@@ -44,4 +44,77 @@ internal TableSection(int ordinal, long offset, long end, int? key, int rowSize,
/// The rows in file order. The list is a view over the data: each row is built when it is read.
public IReadOnlyList Rows { get; }
+
+ private IReadOnlyList DecodeRows(int expectedSize, Func decode)
+ {
+ if (RowSize != expectedSize)
+ throw new InvalidOperationException($"Section row size {RowSize} does not match expected size {expectedSize} for {typeof(T).Name}.");
+ var list = new T[Rows.Count];
+ for (int i = 0; i < Rows.Count; i++)
+ list[i] = decode(Rows[i]);
+ return list;
+ }
+
+ /// Decodes all rows of this section as (size 72).
+ public IReadOnlyList AsObjects() => DecodeRows(ObjectRow.ExpectedRowSize, r => r.AsObject());
+
+ /// Decodes all rows of this section as (size 92).
+ public IReadOnlyList AsAssemblies() => DecodeRows(AssemblyRow.ExpectedRowSize, r => r.AsAssembly());
+
+ /// Decodes all rows of this section as (size 40).
+ public IReadOnlyList AsCoordsys() => DecodeRows(CoordsysRow.ExpectedRowSize, r => r.AsCoordsys());
+
+ /// Decodes all rows of this section as (size 64).
+ public IReadOnlyList AsParts() => DecodeRows(PartRow.ExpectedRowSize, r => r.AsPart());
+
+ /// Decodes all rows of this section as (size 32).
+ public IReadOnlyList AsPoints() => DecodeRows(PointRow.ExpectedRowSize, r => r.AsPoint());
+
+ /// Decodes all rows of this section as (size 60).
+ public IReadOnlyList AsRelations() => DecodeRows(RelationRow.ExpectedRowSize, r => r.AsRelation());
+
+ /// Decodes all rows of this section as (size 24).
+ public IReadOnlyList AsWeldings() => DecodeRows(WeldingRow.ExpectedRowSize, r => r.AsWelding());
+
+ /// Decodes all rows of this section as (size 24).
+ public IReadOnlyList AsNumAttrs() => DecodeRows(NumAttrRow.ExpectedRowSize, r => r.AsNumAttr());
+
+ /// Decodes all rows of this section as (size 24).
+ public IReadOnlyList AsStrAttrs() => DecodeRows(StrAttrRow.ExpectedRowSize, r => r.AsStrAttr());
+
+ /// Decodes all rows of this section as (size 372).
+ public IReadOnlyList AsPartAttrs() => DecodeRows(PartAttrRow.ExpectedRowSize, r => r.AsPartAttr());
+
+ /// Decodes all rows of this section as (size 44).
+ public IReadOnlyList AsNumAttrAttrs() => DecodeRows(NumAttrAttrRow.ExpectedRowSize, r => r.AsNumAttrAttr());
+
+ /// Decodes all rows of this section as (size 120).
+ public IReadOnlyList AsStrAttrAttrs() => DecodeRows(StrAttrAttrRow.ExpectedRowSize, r => r.AsStrAttrAttr());
+
+ /// Decodes all rows of this section as (size 45).
+ public IReadOnlyList AsStringPool() => DecodeRows(StringPoolRow.ExpectedRowSize, r => r.AsStringPool());
+
+ /// Decodes all rows of this section as (size 68).
+ public IReadOnlyList AsPartNumberings() => DecodeRows(PartNumberingRow.ExpectedRowSize, r => r.AsPartNumbering());
+
+ /// Decodes all rows of this section as (size 76).
+ public IReadOnlyList AsAssemblyNumberings() => DecodeRows(AssemblyNumberingRow.ExpectedRowSize, r => r.AsAssemblyNumbering());
+
+ /// Decodes all rows of this section as (size 12).
+ public IReadOnlyList AsObjectNumberings() => DecodeRows(ObjectNumberingRow.ExpectedRowSize, r => r.AsObjectNumbering());
+
+ /// Decodes all rows of this section as (size 24).
+ public IReadOnlyList AsBolts() => DecodeRows(BoltRow.ExpectedRowSize, r => r.AsBolt());
+
+ /// Decodes all rows of this section as (size 20).
+ public IReadOnlyList AsObjectModifications() => DecodeRows(ObjectModificationRow.ExpectedRowSize, r => r.AsObjectModification());
+
+ /// Decodes all rows of this section as (size 48).
+ public IReadOnlyList AsBoltHoles() => DecodeRows(BoltHoleRow.ExpectedRowSize, r => r.AsBoltHole());
+
+ /// Decodes all rows of this section as (size 8).
+ public IReadOnlyList AsObjectPhases() => DecodeRows(ObjectPhaseRow.ExpectedRowSize, r => r.AsObjectPhase());
+
+ /// Decodes all rows of this section as (size 60).
+ public IReadOnlyList AsBoltHolePoints() => DecodeRows(BoltHolePointsRow.ExpectedRowSize, r => r.AsBoltHolePoints());
}
diff --git a/src/TdbIO/TeklaModel.cs b/src/TdbIO/TeklaModel.cs
new file mode 100644
index 0000000..0682c38
--- /dev/null
+++ b/src/TdbIO/TeklaModel.cs
@@ -0,0 +1,449 @@
+namespace TdbIO;
+
+/// Represents an in-memory, read-only object model decoded from a Tekla Structures model database (.db1).
+public sealed class TeklaModel
+{
+ private readonly Dictionary _objectsById;
+ private readonly Dictionary _objectsByGuid;
+ private readonly Dictionary _assembliesById;
+ private readonly Dictionary _partsById;
+ private readonly Dictionary _boltsById;
+ private readonly Dictionary _weldsById;
+
+ internal TeklaModel(
+ Db1Document document,
+ Guid modelGuid,
+ IReadOnlyList assemblies,
+ IReadOnlyList parts,
+ IReadOnlyList bolts,
+ IReadOnlyList welds,
+ IReadOnlyList objects)
+ {
+ Document = document ?? throw new ArgumentNullException(nameof(document));
+ ModelGuid = modelGuid;
+ Assemblies = assemblies ?? Array.Empty();
+ Parts = parts ?? Array.Empty();
+ Bolts = bolts ?? Array.Empty();
+ Welds = welds ?? Array.Empty();
+ Objects = objects ?? Array.Empty();
+
+ _objectsById = new(Objects.Count);
+ _objectsByGuid = new(Objects.Count);
+ foreach (var obj in Objects)
+ {
+ _objectsById[obj.Id] = obj;
+ if (obj.Guid != Guid.Empty)
+ _objectsByGuid[obj.Guid] = obj;
+ }
+
+ _assembliesById = new(Assemblies.Count);
+ foreach (var a in Assemblies) _assembliesById[a.Id] = a;
+
+ _partsById = new(Parts.Count);
+ foreach (var p in Parts) _partsById[p.Id] = p;
+
+ _boltsById = new(Bolts.Count);
+ foreach (var b in Bolts) _boltsById[b.Id] = b;
+
+ _weldsById = new(Welds.Count);
+ foreach (var w in Welds) _weldsById[w.Id] = w;
+ }
+
+ /// The source model database document.
+ public Db1Document Document { get; }
+
+ /// The unique model identifier (GUID).
+ public Guid ModelGuid { get; }
+
+ /// All assemblies in the model.
+ public IReadOnlyList Assemblies { get; }
+
+ /// All parts (beams, columns, plates, slabs, etc.) in the model.
+ public IReadOnlyList Parts { get; }
+
+ /// All bolt groups in the model.
+ public IReadOnlyList Bolts { get; }
+
+ /// All welds in the model.
+ public IReadOnlyList Welds { get; }
+
+ /// All model objects, including parts, assemblies, bolts, welds and connections.
+ public IReadOnlyList Objects { get; }
+
+ /// Finds any model object by its integer identifier, or returns null if not found.
+ public ModelObject? FindObject(int id) => _objectsById.GetValueOrDefault(id);
+
+ /// Finds any model object by its GUID, or returns null if not found.
+ public ModelObject? FindObject(Guid guid) => _objectsByGuid.GetValueOrDefault(guid);
+
+ /// Finds an assembly by its integer identifier, or returns null if not found.
+ public ModelAssembly? FindAssembly(int id) => _assembliesById.GetValueOrDefault(id);
+
+ /// Finds a part by its integer identifier, or returns null if not found.
+ public ModelPart? FindPart(int id) => _partsById.GetValueOrDefault(id);
+
+ /// Finds a bolt group by its integer identifier, or returns null if not found.
+ public ModelBolt? FindBolt(int id) => _boltsById.GetValueOrDefault(id);
+
+ /// Finds a weld by its integer identifier, or returns null if not found.
+ public ModelWeld? FindWeld(int id) => _weldsById.GetValueOrDefault(id);
+}
+
+/// Base class for all entities in a Tekla Structures model.
+public class ModelObject
+{
+ /// Initializes a new instance of .
+ public ModelObject(
+ int id,
+ Guid guid,
+ int type,
+ int subtype,
+ int phase,
+ int? parentId,
+ int? assemblyId,
+ IReadOnlyDictionary? stringAttributes = null,
+ IReadOnlyDictionary? numericAttributes = null)
+ {
+ Id = id;
+ Guid = guid;
+ Type = type;
+ Subtype = subtype;
+ Phase = phase;
+ ParentId = parentId;
+ AssemblyId = assemblyId;
+ StringAttributes = stringAttributes ?? new Dictionary();
+ NumericAttributes = numericAttributes ?? new Dictionary();
+ }
+
+ /// The unique integer identifier of the object (primary key in the database).
+ public int Id { get; }
+
+ /// The unique RFC 4122 GUID of the object.
+ public Guid Guid { get; }
+
+ /// The object type code (e.g. 1 for part, 2 for assembly, 3 for connection, 9 for bolt, 13 for weld).
+ public int Type { get; }
+
+ /// The object subtype code.
+ public int Subtype { get; }
+
+ /// The project phase number this object belongs to.
+ public int Phase { get; }
+
+ /// The parent object identifier, or null if none.
+ public int? ParentId { get; }
+
+ /// The identifier of the assembly this object belongs to, or null if none.
+ public int? AssemblyId { get; }
+
+ /// User-defined and system string attributes associated with this object.
+ public IReadOnlyDictionary StringAttributes { get; }
+
+ /// User-defined and system numeric attributes associated with this object.
+ public IReadOnlyDictionary NumericAttributes { get; }
+
+ /// Gets a string attribute value by name, or null if not set.
+ public string? GetStringAttribute(string name) =>
+ StringAttributes.TryGetValue(name, out var value) ? value : null;
+
+ /// Gets a numeric attribute value by name, or null if not set.
+ public double? GetNumericAttribute(string name) =>
+ NumericAttributes.TryGetValue(name, out var value) ? value : null;
+
+ ///
+ public override string ToString() => $"{GetType().Name} #{Id} ({Guid})";
+}
+
+/// Represents a fabricated assembly or precast unit composed of a main part and optional secondary parts.
+public sealed class ModelAssembly : ModelObject
+{
+ internal ModelAssembly(
+ int id,
+ Guid guid,
+ int type,
+ int subtype,
+ int phase,
+ int? parentId,
+ string name,
+ string prefix,
+ int startNumber,
+ int positionNumber,
+ int assemblyType,
+ int @class,
+ IReadOnlyDictionary? stringAttributes = null,
+ IReadOnlyDictionary? numericAttributes = null)
+ : base(id, guid, type, subtype, phase, parentId, id, stringAttributes, numericAttributes)
+ {
+ Name = name ?? string.Empty;
+ Prefix = prefix ?? string.Empty;
+ StartNumber = startNumber;
+ PositionNumber = positionNumber;
+ AssemblyType = assemblyType;
+ Class = @class;
+ Secondaries = Array.Empty();
+ Parts = Array.Empty();
+ Bolts = Array.Empty();
+ Welds = Array.Empty();
+ }
+
+ /// The assembly name (e.g. "BEAM", "COLUMN", "TRUSS").
+ public string Name { get; }
+
+ /// The assembly numbering prefix (e.g. "B", "C", "A").
+ public string Prefix { get; }
+
+ /// The start number for assembly numbering.
+ public int StartNumber { get; }
+
+ /// The assembly mark position number.
+ public int PositionNumber { get; }
+
+ /// The assembly type code.
+ public int AssemblyType { get; }
+
+ /// The assembly class code.
+ public int Class { get; }
+
+ /// The main part of the assembly, or null if not yet resolved.
+ public ModelPart? MainPart { get; internal set; }
+
+ /// The secondary parts attached to the assembly.
+ public IReadOnlyList Secondaries { get; internal set; }
+
+ /// All parts belonging to the assembly (main part and secondaries).
+ public IReadOnlyList Parts { get; internal set; }
+
+ /// All bolts belonging to or connecting parts of this assembly.
+ public IReadOnlyList Bolts { get; internal set; }
+
+ /// All welds belonging to or connecting parts of this assembly.
+ public IReadOnlyList Welds { get; internal set; }
+
+ ///
+ public override string ToString() => $"Assembly #{Id} '{Name}' Mark={Prefix}{PositionNumber} Parts={Parts.Count}";
+}
+
+/// Represents an individual structural part (steel beam, column, plate, concrete slab, wall, etc.).
+public sealed class ModelPart : ModelObject
+{
+ internal ModelPart(
+ int id,
+ Guid guid,
+ int type,
+ int subtype,
+ int phase,
+ int? parentId,
+ int? assemblyId,
+ string name,
+ string profile,
+ string material,
+ string prefix,
+ int startNumber,
+ int positionNumber,
+ int @class,
+ string finish,
+ ModelPoint? startPoint,
+ ModelPoint? endPoint,
+ double length,
+ ModelCoordsys? coordinateSystem,
+ IReadOnlyDictionary? stringAttributes = null,
+ IReadOnlyDictionary? numericAttributes = null)
+ : base(id, guid, type, subtype, phase, parentId, assemblyId, stringAttributes, numericAttributes)
+ {
+ Name = name ?? string.Empty;
+ Profile = profile ?? string.Empty;
+ Material = material ?? string.Empty;
+ Prefix = prefix ?? string.Empty;
+ StartNumber = startNumber;
+ PositionNumber = positionNumber;
+ Class = @class;
+ Finish = finish ?? string.Empty;
+ StartPoint = startPoint;
+ EndPoint = endPoint;
+ Length = length;
+ CoordinateSystem = coordinateSystem;
+ Bolts = Array.Empty();
+ Welds = Array.Empty();
+ }
+
+ /// The part name (e.g. "BEAM", "COLUMN", "PLATE").
+ public string Name { get; }
+
+ /// The resolved profile name (e.g. "HEA300", "IPE200", "PL10*150").
+ public string Profile { get; }
+
+ /// The material grade name (e.g. "S355J2", "S235JR", "C30/37").
+ public string Material { get; }
+
+ /// The part numbering prefix (e.g. "b", "p").
+ public string Prefix { get; }
+
+ /// The start number for part numbering.
+ public int StartNumber { get; }
+
+ /// The part mark position number.
+ public int PositionNumber { get; }
+
+ /// The part display class / color index.
+ public int Class { get; }
+
+ /// The surface finish description.
+ public string Finish { get; }
+
+ /// The parent assembly this part belongs to, or null if standalone.
+ public ModelAssembly? Assembly { get; internal set; }
+
+ /// Whether this part is the main part of its assembly.
+ public bool IsMainPart => Assembly?.MainPart == this;
+
+ /// The start point coordinate in model space.
+ public ModelPoint? StartPoint { get; }
+
+ /// The end point coordinate in model space.
+ public ModelPoint? EndPoint { get; }
+
+ /// The geometric length of the part.
+ public double Length { get; }
+
+ /// The local coordinate system origin and scale.
+ public ModelCoordsys? CoordinateSystem { get; }
+
+ /// All bolts connected to this part.
+ public IReadOnlyList Bolts { get; internal set; }
+
+ /// All welds connected to this part.
+ public IReadOnlyList Welds { get; internal set; }
+
+ ///
+ public override string ToString() => $"Part #{Id} '{Name}' {Profile} ({Material}) Mark={Prefix}{PositionNumber}";
+}
+
+/// Represents a bolt group connecting two or more parts.
+public sealed class ModelBolt : ModelObject
+{
+ internal ModelBolt(
+ int id,
+ Guid guid,
+ int type,
+ int subtype,
+ int phase,
+ int? parentId,
+ int? assemblyId,
+ ModelPoint? firstPoint,
+ ModelPoint? secondPoint,
+ IReadOnlyList holes,
+ IReadOnlyList positions,
+ IReadOnlyDictionary? stringAttributes = null,
+ IReadOnlyDictionary? numericAttributes = null)
+ : base(id, guid, type, subtype, phase, parentId, assemblyId, stringAttributes, numericAttributes)
+ {
+ FirstPoint = firstPoint;
+ SecondPoint = secondPoint;
+ Holes = holes ?? Array.Empty();
+ Positions = positions ?? Array.Empty();
+ ConnectedParts = Array.Empty();
+ }
+
+ /// The first reference point / origin of the bolt group.
+ public ModelPoint? FirstPoint { get; }
+
+ /// The second reference point / direction of the bolt group.
+ public ModelPoint? SecondPoint { get; }
+
+ /// The parts connected through the bolt holes.
+ public IReadOnlyList ConnectedParts { get; internal set; }
+
+ /// The individual holes penetrating the connected parts.
+ public IReadOnlyList Holes { get; }
+
+ /// The 3D coordinates of the bolt locations in the pattern.
+ public IReadOnlyList Positions { get; }
+
+ /// The assembly this bolt belongs to, or null if not set.
+ public ModelAssembly? Assembly { get; internal set; }
+
+ ///
+ public override string ToString() => $"Bolt #{Id} ({Guid}) Holes={Holes.Count} ConnectedParts={ConnectedParts.Count}";
+}
+
+/// Represents a structural weld connecting two or more parts.
+public sealed class ModelWeld : ModelObject
+{
+ internal ModelWeld(
+ int id,
+ Guid guid,
+ int type,
+ int subtype,
+ int phase,
+ int? parentId,
+ int? assemblyId,
+ int commonAttrId,
+ IReadOnlyDictionary? stringAttributes = null,
+ IReadOnlyDictionary? numericAttributes = null)
+ : base(id, guid, type, subtype, phase, parentId, assemblyId, stringAttributes, numericAttributes)
+ {
+ CommonAttrId = commonAttrId;
+ ConnectedParts = Array.Empty();
+ }
+
+ /// The identifier of the common weld attributes row.
+ public int CommonAttrId { get; }
+
+ /// The parent connection or component creating this weld, or null if none.
+ public ModelObject? Parent { get; internal set; }
+
+ /// The assembly this weld belongs to, or null if not set.
+ public ModelAssembly? Assembly { get; internal set; }
+
+ /// The parts joined by this weld.
+ public IReadOnlyList ConnectedParts { get; internal set; }
+
+ ///
+ public override string ToString() => $"Weld #{Id} ({Guid}) AttrId={CommonAttrId}";
+}
+
+/// A 3D coordinate point in model space.
+/// The point identifier.
+/// The X coordinate in millimeters.
+/// The Y coordinate in millimeters.
+/// The Z coordinate in millimeters.
+public readonly record struct ModelPoint(int Id, double X, double Y, double Z)
+{
+ ///
+ public override string ToString() => $"({X:F2}, {Y:F2}, {Z:F2})";
+}
+
+/// A coordinate system origin and scale.
+/// The coordinate system identifier.
+/// Origin X coordinate.
+/// Origin Y coordinate.
+/// Origin Z coordinate.
+/// Length or scale factor.
+public readonly record struct ModelCoordsys(int Id, double X, double Y, double Z, double Length)
+{
+ ///
+ public override string ToString() => $"Origin=({X:F2}, {Y:F2}, {Z:F2}), Length={Length:F2}";
+}
+
+/// A single hole in a connected part penetrated by a bolt group.
+/// The hole index in the group.
+/// The identifier of the penetrated part.
+/// The resolved penetrated part, or null if not found.
+/// The Z offset along the bolt axis.
+/// The grip length in this part.
+/// Slotted hole direction.
+/// Slotted hole type.
+/// Hole shortening length.
+public readonly record struct ModelBoltHole(
+ int No,
+ int PartId,
+ ModelPart? Part,
+ double PointZ,
+ double Length,
+ int LongHoleDir,
+ int LongHoleType,
+ double ShorteningLength)
+{
+ ///
+ public override string ToString() => $"Hole #{No} in Part #{PartId} Grip={Length:F1}";
+}
diff --git a/tests/TdbIO.Tests/ObjectModelTests.cs b/tests/TdbIO.Tests/ObjectModelTests.cs
new file mode 100644
index 0000000..c7e13a0
--- /dev/null
+++ b/tests/TdbIO.Tests/ObjectModelTests.cs
@@ -0,0 +1,871 @@
+using System.Buffers.Binary;
+using System.Text;
+using TdbIO.Internal;
+using Xunit;
+
+namespace TdbIO.Tests;
+
+public class ObjectModelTests
+{
+ private delegate void FillSpan(Span span);
+
+ private static TableRow MakeRow(int size, FillSpan fill)
+ {
+ var bytes = new byte[size];
+ fill(bytes);
+ return new TableRow(100, 4, bytes, 1, 2);
+ }
+
+ private static TableRow MakeRowWithMarker(int size, byte marker, FillSpan fill)
+ {
+ var bytes = new byte[size];
+ fill(bytes);
+ return new TableRow(100, marker, bytes, 1, 2);
+ }
+
+ private static TableSection MakeSection(int rowSize, int? key, params TableRow[] rows) =>
+ new(0, 0, 100, key, rowSize, [0, 0, 0], 20, rows);
+
+ [Fact]
+ public void ReadModelThrowsOnNull()
+ {
+ Assert.Throws(() => ModelBuilder.Build(null!));
+ }
+
+ [Fact]
+ public void ReadModelDecodesSyntheticModelCorrectly()
+ {
+ var partGuid = Guid.NewGuid();
+ var assGuid = Guid.NewGuid();
+ var boltGuid = Guid.NewGuid();
+ var weldGuid = Guid.NewGuid();
+ var secPartGuid = Guid.NewGuid();
+
+ // 1. Table 1 (object)
+ var objRow1 = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100); // Id = 100 (Assembly)
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 0); // ParentId
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); // AssemblyId
+ assGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 2); // Type = 2 (Assembly)
+ });
+ var objRow2 = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 101); // Id = 101 (Main Part)
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 0); // ParentId
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); // AssemblyId = 100
+ partGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 1); // Type = 1 (Part)
+ });
+ var objRow3 = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 102); // Id = 102 (Secondary Part)
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 0); // ParentId
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); // AssemblyId = 100
+ secPartGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 1); // Type = 1 (Part)
+ });
+ var objRow4 = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 103); // Id = 103 (Bolt)
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 100); // ParentId
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); // AssemblyId = 100
+ boltGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 9); // Type = 9 (Bolt)
+ });
+ var objRow5 = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 104); // Id = 104 (Weld)
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 100); // ParentId
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); // AssemblyId = 100
+ weldGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 13); // Type = 13 (Weld)
+ });
+ var objSec = MakeSection(ObjectRow.ExpectedRowSize, ObjectRow.TableKey, objRow1, objRow2, objRow3, objRow4, objRow5);
+
+ // 2. Table 2 (assembly)
+ var assRow = MakeRow(AssemblyRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 1); // Type
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 5); // Class
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 101); // MainPartId = 101
+ Encoding.UTF8.GetBytes("COLUMN\0").CopyTo(span[20..]);
+ });
+ var assSec = MakeSection(AssemblyRow.ExpectedRowSize, AssemblyRow.TableKey, assRow);
+
+ // 3. Table 13 (point)
+ var ptRow1 = MakeRow(PointRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 0.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[16..], 0.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 0.0);
+ });
+ var ptRow2 = MakeRow(PointRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 2);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 0.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[16..], 0.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 3000.0);
+ });
+ var ptRow3 = MakeRow(PointRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 3);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 100.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[16..], 50.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 500.0);
+ });
+ var ptSec = MakeSection(PointRow.ExpectedRowSize, PointRow.TableKey, ptRow1, ptRow2, ptRow3);
+
+ // 4. Table 3 (coordsys)
+ var csRow = MakeRow(CoordsysRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 10.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[16..], 20.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 30.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[32..], 1.0);
+ });
+ var csSec = MakeSection(CoordsysRow.ExpectedRowSize, CoordsysRow.TableKey, csRow);
+
+ // 5. Table 50 (stringpool)
+ var spRow1 = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ Encoding.UTF8.GetBytes("300\0").CopyTo(span[16..]);
+ });
+ var spRow2 = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 2);
+ Encoding.UTF8.GetBytes("Special Beam\0").CopyTo(span[16..]);
+ });
+ var spSec = MakeSection(StringPoolRow.ExpectedRowSize, StringPoolRow.TableKey, spRow1, spRow2);
+
+ // 6. Table 44 (partattr)
+ var paRow1 = MakeRow(PartAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 201);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 3); // Class
+ Encoding.UTF8.GetBytes("C\0").CopyTo(span[32..]);
+ Encoding.UTF8.GetBytes("COLUMN\0").CopyTo(span[54..]);
+ Encoding.UTF8.GetBytes("HEA\0").CopyTo(span[116..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[180..], 1); // ParameterStringId = 1 ("300") -> "HEA300"
+ Encoding.UTF8.GetBytes("S355JR\0").CopyTo(span[268..]);
+ Encoding.UTF8.GetBytes("GALVANIZED\0").CopyTo(span[300..]);
+ });
+ var paRow2 = MakeRow(PartAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 202);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 4); // Class
+ Encoding.UTF8.GetBytes("P\0").CopyTo(span[32..]);
+ Encoding.UTF8.GetBytes("PLATE\0").CopyTo(span[54..]);
+ Encoding.UTF8.GetBytes("PL10*200\0").CopyTo(span[116..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[180..], 0);
+ Encoding.UTF8.GetBytes("S235JR\0").CopyTo(span[268..]);
+ });
+ var paSec = MakeSection(PartAttrRow.ExpectedRowSize, PartAttrRow.TableKey, paRow1, paRow2);
+
+ // 7. Table 10 (part)
+ var partRow1 = MakeRow(PartRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 101); // Id = 101
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 201); // PartAttrId = 201
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 1); // StartPointId = 1
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 2); // EndPointId = 2
+ BinaryPrimitives.WriteInt32LittleEndian(span[24..], 10); // CoordsysAttrId = 10
+ BinaryPrimitives.WriteDoubleLittleEndian(span[56..], 3000.0); // Length
+ });
+ var partRow2 = MakeRow(PartRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 102); // Id = 102
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 202); // PartAttrId = 202
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 3);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[56..], 200.0);
+ });
+ var partSec = MakeSection(PartRow.ExpectedRowSize, PartRow.TableKey, partRow1, partRow2);
+
+ // 8. Numbering
+ var partNumRow = MakeRow(PartNumberingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 101);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 1); // StartNumber
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 5); // FPos = 5
+ Encoding.UTF8.GetBytes("C/\0").CopyTo(span[20..]);
+ });
+ var partNumSec = MakeSection(PartNumberingRow.ExpectedRowSize, PartNumberingRow.TableKey, partNumRow);
+
+ var assNumRow = MakeRow(AssemblyNumberingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 1); // StartNumber
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 10); // FPos = 10
+ Encoding.UTF8.GetBytes("A/\0").CopyTo(span[28..]);
+ });
+ var assNumSec = MakeSection(AssemblyNumberingRow.ExpectedRowSize, AssemblyNumberingRow.TableKey, assNumRow);
+
+ // 9. Table 141 (phase)
+ var phaseRow1 = MakeRow(ObjectPhaseRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2); // Phase = 2
+ });
+ var phaseRow2 = MakeRow(ObjectPhaseRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 101);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2);
+ });
+ var phaseSec = MakeSection(ObjectPhaseRow.ExpectedRowSize, ObjectPhaseRow.TableKey, phaseRow1, phaseRow2);
+
+ // 10. Table 107 (bolt) & Table 140 (hole)
+ var boltRow = MakeRow(BoltRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 103);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 3);
+ });
+ var boltSec = MakeSection(BoltRow.ExpectedRowSize, BoltRow.TableKey, boltRow);
+
+ var holeRow1 = MakeRow(BoltHoleRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 103); // BoltId = 103
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 1); // No = 1
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 101); // PartId = 101
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 15.0); // Length = 15
+ });
+ var holeRow2 = MakeRow(BoltHoleRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 103); // BoltId = 103
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2); // No = 2
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 102); // PartId = 102
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 10.0);
+ });
+ var holeSec = MakeSection(BoltHoleRow.ExpectedRowSize, BoltHoleRow.TableKey, holeRow1, holeRow2);
+
+ // 11. Table 20 (weld)
+ var weldRow = MakeRow(WeldingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 104);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 999); // CommonAttrId
+ });
+ var weldSec = MakeSection(WeldingRow.ExpectedRowSize, WeldingRow.TableKey, weldRow);
+
+ // 12. Attributes (Tables 38, 39, 48, 49)
+ var numDefRow = MakeRow(NumAttrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 501);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 42.5);
+ Encoding.UTF8.GetBytes("MY_WEIGHT\0").CopyTo(span[16..]);
+ });
+ var numDefSec = MakeSection(NumAttrAttrRow.ExpectedRowSize, NumAttrAttrRow.TableKey, numDefRow);
+
+ var numAttrRow = MakeRow(NumAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 501); // AttrId = 501
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 101); // FatherId = 101
+ });
+ var numAttrSec = MakeSection(NumAttrRow.ExpectedRowSize, NumAttrRow.TableKey, numAttrRow);
+
+ var strDefRow = MakeRow(StrAttrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 601);
+ Encoding.UTF8.GetBytes("USER_NOTE\0").CopyTo(span[8..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[112..], 2); // ValueId = 2 -> "Special Beam"
+ });
+ var strDefSec = MakeSection(StrAttrAttrRow.ExpectedRowSize, StrAttrAttrRow.TableKey, strDefRow);
+
+ var strAttrRow = MakeRow(StrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 601); // AttrId = 601
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 101); // FatherId = 101
+ });
+ var strAttrSec = MakeSection(StrAttrRow.ExpectedRowSize, StrAttrRow.TableKey, strAttrRow);
+
+ // Build a mock Db1Document
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+
+ // Feed sections directly through internal builder
+ var model = ModelBuilder.BuildFromSections(
+ doc,
+ [objSec, assSec, ptSec, csSec, spSec, paSec, partSec, partNumSec, assNumSec, phaseSec, boltSec, holeSec, weldSec, numDefSec, numAttrSec, strDefSec, strAttrSec]);
+
+ Assert.NotNull(model);
+ Assert.Equal(doc.ModelGuid, model.ModelGuid);
+ Assert.Same(doc, model.Document);
+
+ // Verify Assembly
+ Assert.Single(model.Assemblies);
+ var ass = model.Assemblies[0];
+ Assert.Equal(100, ass.Id);
+ Assert.Equal(assGuid, ass.Guid);
+ Assert.Equal("COLUMN", ass.Name);
+ Assert.Equal("A/", ass.Prefix);
+ Assert.Equal(1, ass.StartNumber);
+ Assert.Equal(10, ass.PositionNumber);
+ Assert.Equal(2, ass.Phase);
+ Assert.Equal("Assembly #100 'COLUMN' Mark=A/10 Parts=2", ass.ToString());
+
+ // Verify Parts & Hierarchy
+ Assert.Equal(2, model.Parts.Count);
+ var mainPart = model.Parts[0];
+ Assert.Equal(101, mainPart.Id);
+ Assert.Equal(partGuid, mainPart.Guid);
+ Assert.Equal("COLUMN", mainPart.Name);
+ Assert.Equal("HEA300", mainPart.Profile);
+ Assert.Equal("S355JR", mainPart.Material);
+ Assert.Equal("C/", mainPart.Prefix);
+ Assert.Equal(1, mainPart.StartNumber);
+ Assert.Equal(5, mainPart.PositionNumber);
+ Assert.Equal(3, mainPart.Class);
+ Assert.Equal("GALVANIZED", mainPart.Finish);
+ Assert.Equal(3000.0, mainPart.Length);
+ Assert.Equal(2, mainPart.Phase);
+ Assert.True(mainPart.IsMainPart);
+ Assert.Same(ass, mainPart.Assembly);
+ Assert.Same(mainPart, ass.MainPart);
+
+ var secPart = model.Parts[1];
+ Assert.Equal(102, secPart.Id);
+ Assert.Equal("PL10*200", secPart.Profile);
+ Assert.False(secPart.IsMainPart);
+ Assert.Same(ass, secPart.Assembly);
+
+ Assert.Equal(2, ass.Parts.Count);
+ Assert.Single(ass.Secondaries);
+ Assert.Same(secPart, ass.Secondaries[0]);
+
+ // Verify Geometry
+ Assert.NotNull(mainPart.StartPoint);
+ Assert.Equal(0.0, mainPart.StartPoint.Value.X);
+ Assert.Equal(0.0, mainPart.StartPoint.Value.Y);
+ Assert.Equal(0.0, mainPart.StartPoint.Value.Z);
+
+ Assert.NotNull(mainPart.EndPoint);
+ Assert.Equal(0.0, mainPart.EndPoint.Value.X);
+ Assert.Equal(0.0, mainPart.EndPoint.Value.Y);
+ Assert.Equal(3000.0, mainPart.EndPoint.Value.Z);
+
+ Assert.NotNull(mainPart.CoordinateSystem);
+ Assert.Equal(10.0, mainPart.CoordinateSystem.Value.X);
+ Assert.Equal(20.0, mainPart.CoordinateSystem.Value.Y);
+ Assert.Equal(30.0, mainPart.CoordinateSystem.Value.Z);
+
+ // Verify Attributes
+ Assert.Equal(42.5, mainPart.GetNumericAttribute("MY_WEIGHT"));
+ Assert.Equal("Special Beam", mainPart.GetStringAttribute("USER_NOTE"));
+ Assert.Null(mainPart.GetStringAttribute("NON_EXISTING"));
+
+ // Verify Bolts
+ Assert.Single(model.Bolts);
+ var bolt = model.Bolts[0];
+ Assert.Equal(103, bolt.Id);
+ Assert.Equal(boltGuid, bolt.Guid);
+ Assert.Equal(2, bolt.Holes.Count);
+ Assert.Equal(2, bolt.ConnectedParts.Count);
+ Assert.Contains(mainPart, bolt.ConnectedParts);
+ Assert.Contains(secPart, bolt.ConnectedParts);
+ Assert.Single(mainPart.Bolts);
+ Assert.Same(bolt, mainPart.Bolts[0]);
+ Assert.Single(secPart.Bolts);
+ Assert.Same(bolt, secPart.Bolts[0]);
+ Assert.Single(ass.Bolts);
+ Assert.Same(bolt, ass.Bolts[0]);
+
+ // Verify Welds
+ Assert.Single(model.Welds);
+ var weld = model.Welds[0];
+ Assert.Equal(104, weld.Id);
+ Assert.Equal(weldGuid, weld.Guid);
+ Assert.Equal(999, weld.CommonAttrId);
+ Assert.Same(ass, weld.Parent);
+ Assert.Same(ass, weld.Assembly);
+ Assert.Single(ass.Welds);
+ Assert.Same(weld, ass.Welds[0]);
+
+ // Verify Lookups
+ Assert.Same(mainPart, model.FindObject(101));
+ Assert.Same(mainPart, model.FindObject(partGuid));
+ Assert.Same(mainPart, model.FindPart(101));
+ Assert.Null(model.FindPart(9999));
+ Assert.Same(ass, model.FindAssembly(100));
+ Assert.Same(bolt, model.FindBolt(103));
+ Assert.Same(weld, model.FindWeld(104));
+ }
+
+ [SkippableFact]
+ public void RealModelsDecodeObjectModelCorrectly()
+ {
+ var files = TestFiles.FindAll(".db1", ".bak").Where(f => TdbFile.DetectKind(f) == TdbFileKind.Db1).ToList();
+ if (files.Count == 0) throw TestFiles.Missing("model database files");
+
+ foreach (string file in files)
+ {
+ var doc = (Db1Document)TdbFile.Open(file);
+ var model = doc.ReadModel();
+
+ Assert.NotNull(model);
+ Assert.Equal(doc.ModelGuid, model.ModelGuid);
+ Assert.Same(doc, model.Document);
+
+ // Objects
+ Assert.Equal(model.Objects.Count, model.Objects.Select(o => o.Id).Distinct().Count());
+ foreach (var obj in model.Objects)
+ {
+ Assert.True(obj.Id > 0);
+ Assert.Same(obj, model.FindObject(obj.Id));
+ if (obj.Guid != Guid.Empty)
+ Assert.Same(obj, model.FindObject(obj.Guid));
+ }
+
+ // Assemblies
+ foreach (var a in model.Assemblies)
+ {
+ Assert.True(a.Id > 0);
+ Assert.NotNull(a.Name);
+ Assert.Same(a, model.FindAssembly(a.Id));
+ Assert.Same(a, model.FindObject(a.Id));
+
+ if (a.MainPart != null)
+ {
+ Assert.Same(a, a.MainPart.Assembly);
+ Assert.True(a.MainPart.IsMainPart);
+ Assert.Contains(a.MainPart, a.Parts);
+ }
+
+ foreach (var sec in a.Secondaries)
+ {
+ Assert.Same(a, sec.Assembly);
+ Assert.False(sec.IsMainPart);
+ Assert.Contains(sec, a.Parts);
+ }
+
+ foreach (var b in a.Bolts)
+ Assert.True(b.ConnectedParts.Any(p => p.Assembly == a) || b.Assembly == a);
+
+ foreach (var w in a.Welds)
+ Assert.True(w.Assembly == a || w.Parent == a);
+ }
+
+ // Parts
+ foreach (var p in model.Parts)
+ {
+ Assert.True(p.Id > 0);
+ Assert.NotNull(p.Name);
+ Assert.NotNull(p.Profile);
+ Assert.NotNull(p.Material);
+ Assert.Same(p, model.FindPart(p.Id));
+ Assert.Same(p, model.FindObject(p.Id));
+
+ if (p.Assembly != null)
+ Assert.Contains(p, p.Assembly.Parts);
+
+ if (p.StartPoint.HasValue)
+ {
+ var pt = p.StartPoint.Value;
+ Assert.True(double.IsFinite(pt.X) && double.IsFinite(pt.Y) && double.IsFinite(pt.Z));
+ }
+ if (p.EndPoint.HasValue)
+ {
+ var pt = p.EndPoint.Value;
+ Assert.True(double.IsFinite(pt.X) && double.IsFinite(pt.Y) && double.IsFinite(pt.Z));
+ }
+
+ foreach (var b in p.Bolts)
+ Assert.Contains(p, b.ConnectedParts);
+ }
+
+ // Bolts
+ foreach (var b in model.Bolts)
+ {
+ Assert.True(b.Id > 0);
+ Assert.Same(b, model.FindBolt(b.Id));
+ Assert.Same(b, model.FindObject(b.Id));
+
+ foreach (var h in b.Holes)
+ {
+ if (h.Part != null)
+ Assert.Contains(h.Part, b.ConnectedParts);
+ }
+ }
+
+ // Welds
+ foreach (var w in model.Welds)
+ {
+ Assert.True(w.Id > 0);
+ Assert.Same(w, model.FindWeld(w.Id));
+ Assert.Same(w, model.FindObject(w.Id));
+ }
+ }
+ }
+
+ [Fact]
+ public void DeletedRowsAreExcludedFromModelWhileRetainedInLowLevelApi()
+ {
+ var activeGuid = Guid.NewGuid();
+ var deletedGuid = Guid.NewGuid();
+
+ // Row 1: Active object (Id = 1, Marker = 0x04)
+ var activeRow = MakeRowWithMarker(ObjectRow.ExpectedRowSize, 0x04, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ activeGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 1); // Part
+ });
+
+ // Row 2: Deleted object (Id = 2, Marker = 0x0C)
+ var deletedRow = MakeRowWithMarker(ObjectRow.ExpectedRowSize, 0x0C, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 2);
+ deletedGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 1); // Part
+ });
+
+ // Row 3: Superseded/deleted version of Id = 1 (Marker = 0x0C)
+ var oldRow = MakeRowWithMarker(ObjectRow.ExpectedRowSize, 0x0C, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ Guid.NewGuid().TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 99);
+ });
+
+ var section = MakeSection(ObjectRow.ExpectedRowSize, ObjectRow.TableKey, oldRow, activeRow, deletedRow);
+
+ // Low-level API retains all 3 rows
+ var allDecoded = section.AsObjects();
+ Assert.Equal(3, allDecoded.Count);
+
+ // High-level ModelBuilder only includes active rows
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = ModelBuilder.BuildFromSections(doc, [section]);
+
+ Assert.Single(model.Objects);
+ var obj = model.Objects[0];
+ Assert.Equal(1, obj.Id);
+ Assert.Equal(activeGuid, obj.Guid);
+ Assert.Equal(1, obj.Type);
+ Assert.Null(model.FindObject(2));
+ }
+
+ [Fact]
+ public void StringPoolFollowsChainsAndReconstructsMultiByteUtf8AcrossChunks()
+ {
+ // Chunk 1: 28 ASCII bytes + 0xD0 (first byte of 2-byte UTF-8 Cyrillic character 'Д')
+ var chunk1Bytes = new byte[29];
+ for (int i = 0; i < 28; i++) chunk1Bytes[i] = (byte)('A' + (i % 26));
+ chunk1Bytes[28] = 0xD0;
+
+ var spRow1 = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1); // Id = 1
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2); // NextId = 2
+ chunk1Bytes.CopyTo(span[16..]);
+ });
+
+ // Chunk 2: 0x94 (second byte of 'Д') + "оска\0"
+ var chunk2Bytes = new byte[29];
+ chunk2Bytes[0] = 0x94;
+ Encoding.UTF8.GetBytes("оска\0").CopyTo(chunk2Bytes.AsSpan(1));
+
+ var spRow2 = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 2); // Id = 2
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], -1); // NextId = -1 (terminating)
+ chunk2Bytes.CopyTo(span[16..]);
+ });
+
+ var spSec = MakeSection(StringPoolRow.ExpectedRowSize, StringPoolRow.TableKey, spRow1, spRow2);
+
+ // StrAttrAttr row referencing string pool chunk 1
+ var strDefRow = MakeRow(StrAttrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10);
+ Encoding.UTF8.GetBytes("ATTR_NAME\0").CopyTo(span[8..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[112..], 1); // ValueId = 1
+ });
+ var strDefSec = MakeSection(StrAttrAttrRow.ExpectedRowSize, StrAttrAttrRow.TableKey, strDefRow);
+
+ var strAttrRow = MakeRow(StrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 10); // AttrId = 10
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); // FatherId = 100
+ });
+ var strAttrSec = MakeSection(StrAttrRow.ExpectedRowSize, StrAttrRow.TableKey, strAttrRow);
+
+ var objRow = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ });
+ var objSec = MakeSection(ObjectRow.ExpectedRowSize, ObjectRow.TableKey, objRow);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = ModelBuilder.BuildFromSections(doc, [objSec, spSec, strDefSec, strAttrSec]);
+
+ var obj = model.FindObject(100);
+ Assert.NotNull(obj);
+ Assert.NotNull(obj.StringAttributes);
+ string expectedPrefix = new string([.. chunk1Bytes[..28].Select(b => (char)b)]);
+ Assert.Equal(expectedPrefix + "Доска", obj.StringAttributes["ATTR_NAME"]);
+ }
+
+ [Fact]
+ public void StringPoolReconstructsMultiByteUtf8WhenContinuationChunkPrecedesHeadChunk()
+ {
+ // Continuation chunk 302 appears FIRST in row order, but starts with UTF-8 continuation byte 0x94.
+ // Head chunk 301 appears SECOND, ending with 0xD0 (leading byte of 'Д').
+ var chunk1Bytes = new byte[29];
+ for (int i = 0; i < 28; i++) chunk1Bytes[i] = (byte)('A' + (i % 26));
+ chunk1Bytes[28] = 0xD0;
+
+ var spRowHead = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 301); // Id = 301
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 302); // NextId = 302
+ chunk1Bytes.CopyTo(span[16..]);
+ });
+
+ var chunk2Bytes = new byte[29];
+ chunk2Bytes[0] = 0x94;
+ Encoding.UTF8.GetBytes("оска\0").CopyTo(chunk2Bytes.AsSpan(1));
+
+ var spRowCont = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 302); // Id = 302
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], -1); // NextId = -1 (terminating)
+ chunk2Bytes.CopyTo(span[16..]);
+ });
+
+ // Continuation row precedes head row in section
+ var spSec = MakeSection(StringPoolRow.ExpectedRowSize, StringPoolRow.TableKey, spRowCont, spRowHead);
+
+ var strDefRow = MakeRow(StrAttrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10);
+ Encoding.UTF8.GetBytes("ATTR_NAME\0").CopyTo(span[8..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[112..], 301); // ValueId = 301 (head)
+ });
+ var strDefSec = MakeSection(StrAttrAttrRow.ExpectedRowSize, StrAttrAttrRow.TableKey, strDefRow);
+
+ var strAttrRow = MakeRow(StrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 10);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100);
+ });
+ var strAttrSec = MakeSection(StrAttrRow.ExpectedRowSize, StrAttrRow.TableKey, strAttrRow);
+
+ var objRow = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ });
+ var objSec = MakeSection(ObjectRow.ExpectedRowSize, ObjectRow.TableKey, objRow);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = ModelBuilder.BuildFromSections(doc, [objSec, spSec, strDefSec, strAttrSec]);
+
+ var obj = model.FindObject(100);
+ Assert.NotNull(obj);
+ Assert.NotNull(obj.StringAttributes);
+ string expectedPrefix = new string([.. chunk1Bytes[..28].Select(b => (char)b)]);
+ Assert.Equal(expectedPrefix + "Доска", obj.StringAttributes["ATTR_NAME"]);
+ }
+
+ [Fact]
+ public void StringPoolCycleThrowsInvalidDataException()
+ {
+ var spRow1 = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2); // NextId = 2
+ });
+ var spRow2 = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 2);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 1); // NextId = 1 (cycle)
+ });
+ var spSec = MakeSection(StringPoolRow.ExpectedRowSize, StringPoolRow.TableKey, spRow1, spRow2);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ Assert.Throws(() => ModelBuilder.BuildFromSections(doc, [spSec]));
+ }
+
+ [Fact]
+ public void StringPoolMissingLinkThrowsInvalidDataException()
+ {
+ var spRow1 = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 999); // NextId = 999 (missing)
+ });
+ var spSec = MakeSection(StringPoolRow.ExpectedRowSize, StringPoolRow.TableKey, spRow1);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ Assert.Throws(() => ModelBuilder.BuildFromSections(doc, [spSec]));
+ }
+
+ [Fact]
+ public void ObjectNumberingRowMapsObjectIdToNumberId()
+ {
+ // ObjectRow for Part (Id = 200)
+ var objRow = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 200);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 1); // Part
+ });
+ var objSec = MakeSection(ObjectRow.ExpectedRowSize, ObjectRow.TableKey, objRow);
+
+ var partRow = MakeRow(PartRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 200);
+ BinaryPrimitives.WriteInt32LittleEndian(span[20..], 20); // PartAttrId = 20
+ });
+ var partSec = MakeSection(PartRow.ExpectedRowSize, PartRow.TableKey, partRow);
+
+ var paRow = MakeRow(PartAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 20);
+ Encoding.UTF8.GetBytes("BEAM\0").CopyTo(span[32..]);
+ });
+ var paSec = MakeSection(PartAttrRow.ExpectedRowSize, PartAttrRow.TableKey, paRow);
+
+ // Table 105: ObjectNumberingRow maps Object Id 200 -> NumberId 777
+ var objNumRow = MakeRow(ObjectNumberingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 200); // Id = 200
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 777); // NumberId = 777
+ });
+ var objNumSec = MakeSection(ObjectNumberingRow.ExpectedRowSize, ObjectNumberingRow.TableKey, objNumRow);
+
+ // Table 94: PartNumberingRow with Id = 777
+ var partNumRow = MakeRow(PartNumberingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 777); // Id = 777
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 50); // StartNumber = 50
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 12); // FPos = 12
+ Encoding.UTF8.GetBytes("BM/\0").CopyTo(span[20..]); // Prefix = BM/
+ });
+ var partNumSec = MakeSection(PartNumberingRow.ExpectedRowSize, PartNumberingRow.TableKey, partNumRow);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = ModelBuilder.BuildFromSections(doc, [objSec, partSec, paSec, objNumSec, partNumSec]);
+
+ Assert.Single(model.Parts);
+ var part = model.Parts[0];
+ Assert.Equal(200, part.Id);
+ Assert.Equal("BM/", part.Prefix);
+ Assert.Equal(50, part.StartNumber);
+ Assert.Equal(12, part.PositionNumber);
+ }
+
+ [Fact]
+ public void WeldParentResolvesFromGenericComponent()
+ {
+ var assGuid = Guid.NewGuid();
+ var compGuid = Guid.NewGuid();
+ var weldGuid = Guid.NewGuid();
+
+ // Assembly (Id = 100)
+ var objAss = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ assGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 2); // Assembly
+ });
+ var assRow = MakeRow(AssemblyRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ });
+ var assSec = MakeSection(AssemblyRow.ExpectedRowSize, AssemblyRow.TableKey, assRow);
+
+ // Generic Component/Connection (Id = 300, Type = 3, AssemblyId = 100)
+ var objComp = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 300);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); // AssemblyId = 100
+ compGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 3); // Type = 3 (Component/Connection)
+ });
+
+ // Weld (Id = 400, ParentId = 300)
+ var objWeld = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 400);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 300); // ParentId = 300
+ weldGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 13); // Weld
+ });
+ var objSec = MakeSection(ObjectRow.ExpectedRowSize, ObjectRow.TableKey, objAss, objComp, objWeld);
+
+ var weldRow = MakeRow(WeldingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 400);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 55);
+ });
+ var weldSec = MakeSection(WeldingRow.ExpectedRowSize, WeldingRow.TableKey, weldRow);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = ModelBuilder.BuildFromSections(doc, [objSec, assSec, weldSec]);
+
+ Assert.Single(model.Welds);
+ var weld = model.Welds[0];
+ Assert.Equal(400, weld.Id);
+ Assert.NotNull(weld.Parent);
+ Assert.Equal(300, weld.Parent.Id);
+ Assert.Equal(compGuid, weld.Parent.Guid);
+ Assert.NotNull(weld.Assembly);
+ Assert.Equal(100, weld.Assembly.Id);
+ }
+
+ [Fact]
+ public void AssemblyWithUnresolvedMainPartLeavesMainPartNull()
+ {
+ var assGuid = Guid.NewGuid();
+ var partGuid = Guid.NewGuid();
+
+ var objAss = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ assGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 2);
+ });
+
+ // Assembly points to MainPartId = 999 which does NOT exist
+ var assRow = MakeRow(AssemblyRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 999); // MainPartId = 999 (missing)
+ Encoding.UTF8.GetBytes("GIRDER\0").CopyTo(span[20..]);
+ });
+ var assSec = MakeSection(AssemblyRow.ExpectedRowSize, AssemblyRow.TableKey, assRow);
+
+ // Child part in this assembly (Id = 101)
+ var objPart = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 101);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); // AssemblyId = 100
+ partGuid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 1);
+ });
+ var objSec = MakeSection(ObjectRow.ExpectedRowSize, ObjectRow.TableKey, objAss, objPart);
+
+ var partRow = MakeRow(PartRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 101);
+ });
+ var partSec = MakeSection(PartRow.ExpectedRowSize, PartRow.TableKey, partRow);
+
+ var doc = Db1Document.Create(Synthetic.Db1Payload([]));
+ var model = ModelBuilder.BuildFromSections(doc, [objSec, assSec, partSec]);
+
+ Assert.Single(model.Assemblies);
+ var ass = model.Assemblies[0];
+ Assert.Null(ass.MainPart);
+ Assert.Single(ass.Parts);
+ Assert.Single(ass.Secondaries);
+ Assert.Equal(101, ass.Secondaries[0].Id);
+ }
+}
diff --git a/tests/TdbIO.Tests/TableRowDecoderTests.cs b/tests/TdbIO.Tests/TableRowDecoderTests.cs
new file mode 100644
index 0000000..0014315
--- /dev/null
+++ b/tests/TdbIO.Tests/TableRowDecoderTests.cs
@@ -0,0 +1,684 @@
+using System.Buffers.Binary;
+using System.Text;
+using TdbIO.Internal;
+using Xunit;
+
+namespace TdbIO.Tests;
+
+public class TableRowDecoderTests
+{
+ private delegate void FillSpan(Span span);
+
+ private static TableRow MakeRow(int size, FillSpan fill)
+ {
+ var bytes = new byte[size];
+ fill(bytes);
+ return new TableRow(100, 4, bytes, 1, 2);
+ }
+
+ private static TableSection MakeSection(int rowSize, int? key, params TableRow[] rows) =>
+ new(0, 0, 100, key, rowSize, [0, 0, 0], 20, rows);
+
+ [Fact]
+ public void ObjectRowDecodesCorrectly()
+ {
+ var guid = Guid.NewGuid();
+ var extType = Guid.NewGuid();
+ var row = MakeRow(ObjectRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 12345);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 67890);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 11111);
+ guid.TryWriteBytes(span[12..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[32..], 2);
+ extType.TryWriteBytes(span[36..], bigEndian: true, out _);
+ BinaryPrimitives.WriteInt32LittleEndian(span[52..], 100);
+ BinaryPrimitives.WriteInt32LittleEndian(span[56..], 200);
+ BinaryPrimitives.WriteInt32LittleEndian(span[60..], 300);
+ BinaryPrimitives.WriteInt32LittleEndian(span[64..], 400);
+ BinaryPrimitives.WriteInt32LittleEndian(span[68..], 500);
+ });
+
+ var decoded = row.AsObject();
+ Assert.Equal(12345, decoded.Id);
+ Assert.Equal(67890, decoded.ParentId);
+ Assert.Equal(11111, decoded.AssemblyId);
+ Assert.Equal(guid, decoded.Guid);
+ Assert.Equal(1, decoded.Type);
+ Assert.Equal(2, decoded.Subtype);
+ Assert.Equal(extType, decoded.ExternalType);
+ Assert.Equal(100, decoded.Mask1);
+ Assert.Equal(200, decoded.Mask2);
+ Assert.Equal(300, decoded.ObjFlag);
+ Assert.Equal(400, decoded.OwnerId);
+ Assert.Equal(500, decoded.PrivilegeId);
+ }
+
+ [Fact]
+ public void AssemblyRowDecodesCorrectly()
+ {
+ var row = MakeRow(AssemblyRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 20);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 30);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 40);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 50);
+ Encoding.UTF8.GetBytes("COLUMN\0").CopyTo(span[20..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[84..], 60);
+ BinaryPrimitives.WriteInt32LittleEndian(span[88..], 1);
+ });
+
+ var decoded = row.AsAssembly();
+ Assert.Equal(10, decoded.Id);
+ Assert.Equal(20, decoded.Type);
+ Assert.Equal(30, decoded.Class);
+ Assert.Equal(40, decoded.MainPartId);
+ Assert.Equal(50, decoded.Lot);
+ Assert.Equal("COLUMN", decoded.Name);
+ Assert.Equal(60, decoded.Flags);
+ Assert.Equal(1, decoded.MainPartByUser);
+ }
+
+ [Fact]
+ public void AssemblyRowWithInvalidUtf8SequenceThrowsInvalidDataException()
+ {
+ var row = MakeRow(AssemblyRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10);
+ span[20] = 0xFF;
+ });
+
+ var e = Assert.Throws(() => row.AsAssembly());
+ Assert.Equal(20, e.Offset);
+ }
+
+ [Fact]
+ public void CoordsysRowDecodesCorrectly()
+ {
+ var row = MakeRow(CoordsysRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 100.5);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[16..], 200.75);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 300.125);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[32..], 1000.0);
+ });
+
+ var decoded = row.AsCoordsys();
+ Assert.Equal(1, decoded.Id);
+ Assert.Equal(2, decoded.AttrId);
+ Assert.Equal(100.5, decoded.X);
+ Assert.Equal(200.75, decoded.Y);
+ Assert.Equal(300.125, decoded.Z);
+ Assert.Equal(1000.0, decoded.Length);
+ }
+
+ [Fact]
+ public void PartRowDecodesCorrectly()
+ {
+ var row = MakeRow(PartRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 101);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 102);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 103);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 104);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 105);
+ BinaryPrimitives.WriteInt32LittleEndian(span[20..], 106);
+ BinaryPrimitives.WriteInt32LittleEndian(span[24..], 107);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[32..], 10.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[40..], 20.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[48..], 30.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[56..], 500.0);
+ });
+
+ var decoded = row.AsPart();
+ Assert.Equal(101, decoded.Id);
+ Assert.Equal(102, decoded.PartAttrId);
+ Assert.Equal(103, decoded.PositioningAttrId);
+ Assert.Equal(104, decoded.StartPointId);
+ Assert.Equal(105, decoded.EndPointId);
+ Assert.Equal(106, decoded.GeometryTreeRootId);
+ Assert.Equal(107, decoded.CoordsysAttrId);
+ Assert.Equal(0, decoded.Reserved);
+ Assert.Equal(10.0, decoded.CoordsysX);
+ Assert.Equal(20.0, decoded.CoordsysY);
+ Assert.Equal(30.0, decoded.CoordsysZ);
+ Assert.Equal(500.0, decoded.Length);
+ }
+
+ [Fact]
+ public void PointRowDecodesCorrectly()
+ {
+ var row = MakeRow(PointRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 777);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 4);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 1234.5);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[16..], -6789.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 0.0);
+ });
+
+ var decoded = row.AsPoint();
+ Assert.Equal(777, decoded.Id);
+ Assert.Equal(4, decoded.Visibility);
+ Assert.Equal(1234.5, decoded.X);
+ Assert.Equal(-6789.0, decoded.Y);
+ Assert.Equal(0.0, decoded.Z);
+ }
+
+ [Fact]
+ public void RelationRowDecodesCorrectly()
+ {
+ var row = MakeRow(RelationRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 55);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 61000);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 11);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 22);
+ Encoding.UTF8.GetBytes("7b4b9794-f4b8-4040-b87b-3da518911e24\0").CopyTo(span[16..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[56..], 99);
+ });
+
+ var decoded = row.AsRelation();
+ Assert.Equal(55, decoded.Id);
+ Assert.Equal(61000, decoded.Type);
+ Assert.Equal(11, decoded.Id1);
+ Assert.Equal(22, decoded.Id2);
+ Assert.Equal("7b4b9794-f4b8-4040-b87b-3da518911e24", decoded.Guid);
+ Assert.Equal(99, decoded.Flags);
+ }
+
+ [Fact]
+ public void WeldingRowDecodesCorrectly()
+ {
+ var row = MakeRow(WeldingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 3);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 4);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 5);
+ BinaryPrimitives.WriteInt32LittleEndian(span[20..], 6);
+ });
+
+ var decoded = row.AsWelding();
+ Assert.Equal(1, decoded.Id);
+ Assert.Equal(2, decoded.CommonAttrId);
+ Assert.Equal(3, decoded.Seam1Id);
+ Assert.Equal(4, decoded.Seam2Id);
+ Assert.Equal(5, decoded.CompoundSeam1Id);
+ Assert.Equal(6, decoded.CompoundSeam2Id);
+ }
+
+ [Fact]
+ public void BoltRowDecodesCorrectly()
+ {
+ var row = MakeRow(BoltRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 20);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 30);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 40);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 50);
+ BinaryPrimitives.WriteInt32LittleEndian(span[20..], 60);
+ });
+
+ var decoded = row.AsBolt();
+ Assert.Equal(10, decoded.Id);
+ Assert.Equal(20, decoded.BoltAttrId);
+ Assert.Equal(30, decoded.PositioningAttrId);
+ Assert.Equal(40, decoded.FirstPointId);
+ Assert.Equal(50, decoded.SecondPointId);
+ Assert.Equal(60, decoded.PolygonId);
+ }
+
+ [Fact]
+ public void ObjectPhaseRowDecodesCorrectly()
+ {
+ var row = MakeRow(ObjectPhaseRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 123);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 3);
+ });
+
+ var decoded = row.AsObjectPhase();
+ Assert.Equal(123, decoded.ObjectId);
+ Assert.Equal(3, decoded.PhaseNumber);
+ }
+
+ [Fact]
+ public void ObjectNumberingRowDecodesCorrectly()
+ {
+ var row = MakeRow(ObjectNumberingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 500);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 600);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 700);
+ });
+
+ var decoded = row.AsObjectNumbering();
+ Assert.Equal(500, decoded.Id);
+ Assert.Equal(600, decoded.NumberId);
+ Assert.Equal(700, decoded.NumberingGroup);
+ }
+
+ [Fact]
+ public void ObjectModificationRowDecodesCorrectly()
+ {
+ var row = MakeRow(ObjectModificationRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 3);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 4);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 5);
+ });
+
+ var decoded = row.AsObjectModification();
+ Assert.Equal(1, decoded.ModificationId);
+ Assert.Equal(2, decoded.Id);
+ Assert.Equal(3, decoded.ModType);
+ Assert.Equal(4, decoded.DependencyId);
+ Assert.Equal(5, decoded.ModTime);
+ }
+
+ [Fact]
+ public void NumAttrAndStrAttrRowsDecodeCorrectly()
+ {
+ var numRow = MakeRow(NumAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 3);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 4);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 5);
+ BinaryPrimitives.WriteInt32LittleEndian(span[20..], 6);
+ });
+ var num = numRow.AsNumAttr();
+ Assert.Equal(1, num.Id);
+ Assert.Equal(2, num.AttrId);
+ Assert.Equal(3, num.FatherId);
+ Assert.Equal(4, num.OwnerId);
+ Assert.Equal(5, num.Flags);
+ Assert.Equal(6, num.NameId);
+
+ var strRow = MakeRow(StrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 20);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 30);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 40);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 50);
+ BinaryPrimitives.WriteInt32LittleEndian(span[20..], 60);
+ });
+ var str = strRow.AsStrAttr();
+ Assert.Equal(10, str.Id);
+ Assert.Equal(20, str.AttrId);
+ Assert.Equal(30, str.FatherId);
+ Assert.Equal(40, str.OwnerId);
+ Assert.Equal(50, str.Flags);
+ Assert.Equal(60, str.NameId);
+ }
+
+ [Fact]
+ public void PartAttrRowDecodesCorrectly()
+ {
+ var row = MakeRow(PartAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 0);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 4);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[20..], 0);
+ BinaryPrimitives.WriteInt32LittleEndian(span[24..], 2);
+ BinaryPrimitives.WriteInt32LittleEndian(span[28..], 0);
+ Encoding.UTF8.GetBytes("B\0").CopyTo(span[32..]);
+ Encoding.UTF8.GetBytes("BEAM\0").CopyTo(span[54..]);
+ Encoding.UTF8.GetBytes("HEA300\0").CopyTo(span[116..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[180..], 999);
+ Encoding.UTF8.GetBytes("A\0").CopyTo(span[184..]);
+ Encoding.UTF8.GetBytes("MAIN_BEAM\0").CopyTo(span[206..]);
+ Encoding.UTF8.GetBytes("S355J2\0").CopyTo(span[268..]);
+ Encoding.UTF8.GetBytes("PAINTED\0").CopyTo(span[300..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[364..], 7);
+ BinaryPrimitives.WriteInt32LittleEndian(span[368..], 2);
+ });
+
+ var decoded = row.AsPartAttr();
+ Assert.Equal(1, decoded.Id);
+ Assert.Equal(2, decoded.ObjType);
+ Assert.Equal(0, decoded.FormType);
+ Assert.Equal(4, decoded.ObjClass);
+ Assert.Equal(1, decoded.AssStartNo);
+ Assert.Equal(0, decoded.Flags);
+ Assert.Equal(2, decoded.NPoints);
+ Assert.Equal(0, decoded.PartFlags);
+ Assert.Equal("B", decoded.Prefix);
+ Assert.Equal("BEAM", decoded.Name);
+ Assert.Equal("HEA300", decoded.Profile);
+ Assert.Equal(999, decoded.ParameterStringId);
+ Assert.Equal("A", decoded.AssemblyPosition);
+ Assert.Equal("MAIN_BEAM", decoded.AssemblyName);
+ Assert.Equal("S355J2", decoded.Material);
+ Assert.Equal("PAINTED", decoded.Finish);
+ Assert.Equal(7, decoded.AssemblyType);
+ Assert.Equal(2, decoded.PourPhase);
+ }
+
+ [Fact]
+ public void AttrDefinitionRowsDecodeCorrectly()
+ {
+ var numAttrRow = MakeRow(NumAttrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 2);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 42.5);
+ Encoding.UTF8.GetBytes("DIAMETER\0").CopyTo(span[16..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[40..], 99);
+ });
+ var num = numAttrRow.AsNumAttrAttr();
+ Assert.Equal(1, num.Id);
+ Assert.Equal(2, num.Type);
+ Assert.Equal(42.5, num.Value);
+ Assert.Equal("DIAMETER", num.Name);
+ Assert.Equal(99, num.PrivilegeId);
+
+ var strAttrRow = MakeRow(StrAttrAttrRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 3);
+ Encoding.UTF8.GetBytes("COMMENT\0").CopyTo(span[8..]);
+ Encoding.UTF8.GetBytes("Important part\0").CopyTo(span[29..]);
+ BinaryPrimitives.WriteInt32LittleEndian(span[112..], 500);
+ BinaryPrimitives.WriteInt32LittleEndian(span[116..], 0);
+ });
+ var str = strAttrRow.AsStrAttrAttr();
+ Assert.Equal(10, str.Id);
+ Assert.Equal(3, str.Type);
+ Assert.Equal("COMMENT", str.Name);
+ Assert.Equal("Important part", str.Value);
+ Assert.Equal(500, str.ValueId);
+ Assert.Equal(0, str.PrivilegeId);
+ }
+
+ [Fact]
+ public void StringPoolRowDecodesCorrectly()
+ {
+ var row = MakeRow(StringPoolRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], -1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 12345);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 1);
+ Encoding.UTF8.GetBytes("Hello Tekla\0").CopyTo(span[16..]);
+ });
+
+ var decoded = row.AsStringPool();
+ Assert.Equal(100, decoded.Id);
+ Assert.Equal(-1, decoded.NextId);
+ Assert.Equal(12345, decoded.HashId);
+ Assert.Equal(1, decoded.RefCount);
+ Assert.Equal("Hello Tekla", decoded.Text);
+ }
+
+ [Fact]
+ public void NumberingRowsDecodeCorrectly()
+ {
+ var partNumRow = MakeRow(PartNumberingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 0);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 5);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 0);
+ Encoding.UTF8.GetBytes("P-\0").CopyTo(span[20..]);
+ });
+ var pnum = partNumRow.AsPartNumbering();
+ Assert.Equal(1, pnum.Id);
+ Assert.Equal(0, pnum.SeriesId);
+ Assert.Equal(100, pnum.StartNumber);
+ Assert.Equal(5, pnum.FPos);
+ Assert.Equal(0, pnum.MultiFPos);
+ Assert.Equal("P-", pnum.Prefix);
+
+ var assNumRow = MakeRow(AssemblyNumberingRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 2);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 0);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 200);
+ BinaryPrimitives.WriteInt32LittleEndian(span[12..], 10);
+ BinaryPrimitives.WriteInt32LittleEndian(span[16..], 0);
+ BinaryPrimitives.WriteInt32LittleEndian(span[20..], 0);
+ BinaryPrimitives.WriteInt32LittleEndian(span[24..], 0);
+ Encoding.UTF8.GetBytes("B-\0").CopyTo(span[28..]);
+ });
+ var anum = assNumRow.AsAssemblyNumbering();
+ Assert.Equal(2, anum.Id);
+ Assert.Equal(0, anum.SeriesId);
+ Assert.Equal(200, anum.StartNumber);
+ Assert.Equal(10, anum.FPos);
+ Assert.Equal("B-", anum.Prefix);
+ }
+
+ [Fact]
+ public void BoltHolesRowsDecodeCorrectly()
+ {
+ var holeRow = MakeRow(BoltHoleRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ BinaryPrimitives.WriteInt32LittleEndian(span[4..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[8..], 200);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[16..], 15.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 30.0);
+ BinaryPrimitives.WriteInt32LittleEndian(span[32..], 1);
+ BinaryPrimitives.WriteInt32LittleEndian(span[36..], 2);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[40..], -5.0);
+ });
+ var hole = holeRow.AsBoltHole();
+ Assert.Equal(100, hole.BoltId);
+ Assert.Equal(1, hole.No);
+ Assert.Equal(200, hole.PartId);
+ Assert.Equal(15.0, hole.PointZ);
+ Assert.Equal(30.0, hole.Length);
+ Assert.Equal(1, hole.LongHoleDir);
+ Assert.Equal(2, hole.LongHoleType);
+ Assert.Equal(-5.0, hole.ShorteningLength);
+
+ var ptsRow = MakeRow(BoltHolePointsRow.ExpectedRowSize, span =>
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[8..], 1.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[16..], 2.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[24..], 3.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[32..], 4.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[40..], 5.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(span[48..], 6.0);
+ BinaryPrimitives.WriteInt32LittleEndian(span[56..], 8);
+ });
+ var pts = ptsRow.AsBoltHolePoints();
+ Assert.Equal(100, pts.BoltId);
+ Assert.Equal(1.0, pts.IntPoint1X);
+ Assert.Equal(2.0, pts.IntPoint1Y);
+ Assert.Equal(3.0, pts.IntPoint1Z);
+ Assert.Equal(4.0, pts.IntPoint2X);
+ Assert.Equal(5.0, pts.IntPoint2Y);
+ Assert.Equal(6.0, pts.IntPoint2Z);
+ Assert.Equal(8, pts.NumHoles);
+ }
+
+ [Fact]
+ public void BodyTooShortThrowsArgumentException()
+ {
+ var shortRow = MakeRow(10, _ => { });
+ Assert.Throws(() => shortRow.AsObject());
+ Assert.Throws(() => shortRow.AsPoint());
+ Assert.Throws(() => shortRow.AsPart());
+ }
+
+ [Fact]
+ public void SectionRowSizeMismatchThrowsInvalidOperationException()
+ {
+ var row = MakeRow(32, _ => { });
+ var section = MakeSection(32, 13, row);
+
+ // Section has RowSize 32, but AsObjects expects 72
+ Assert.Throws(() => section.AsObjects());
+ Assert.Throws(() => section.AsParts());
+
+ // AsPoints matches 32
+ var points = section.AsPoints();
+ Assert.Single(points);
+ }
+
+ [SkippableFact]
+ public void RealModelsDecodeKnownTableSections()
+ {
+ var files = TestFiles.FindAll(".db1", ".bak").Where(f => TdbFile.DetectKind(f) == TdbFileKind.Db1).ToList();
+ if (files.Count == 0) throw TestFiles.Missing("model database files");
+
+ foreach (string file in files)
+ {
+ var doc = (Db1Document)TdbFile.Open(file);
+ var sections = doc.ReadTables();
+
+ foreach (var section in sections)
+ {
+ if (section.Rows.Count == 0) continue;
+
+ switch (section.Key)
+ {
+ case ObjectRow.TableKey when section.RowSize == ObjectRow.ExpectedRowSize:
+ var objects = section.AsObjects();
+ Assert.Equal(section.Rows.Count, objects.Count);
+ Assert.All(objects, o => Assert.NotEqual(Guid.Empty, o.Guid));
+ break;
+
+ case AssemblyRow.TableKey when section.RowSize == AssemblyRow.ExpectedRowSize:
+ var assemblies = section.AsAssemblies();
+ Assert.Equal(section.Rows.Count, assemblies.Count);
+ Assert.All(assemblies, a => Assert.True(a.Id > 0 && a.Name != null));
+ break;
+
+ case PointRow.TableKey when section.RowSize == PointRow.ExpectedRowSize:
+ var points = section.AsPoints();
+ Assert.Equal(section.Rows.Count, points.Count);
+ Assert.All(points, p => Assert.True(double.IsFinite(p.X) && double.IsFinite(p.Y) && double.IsFinite(p.Z)));
+ break;
+
+ case PartRow.TableKey when section.RowSize == PartRow.ExpectedRowSize:
+ var parts = section.AsParts();
+ Assert.Equal(section.Rows.Count, parts.Count);
+ Assert.All(parts, p => Assert.True(p.Id > 0 && p.StartPointId > 0 && p.EndPointId > 0));
+ break;
+
+ case CoordsysRow.TableKey when section.RowSize == CoordsysRow.ExpectedRowSize:
+ var csys = section.AsCoordsys();
+ Assert.Equal(section.Rows.Count, csys.Count);
+ Assert.All(csys, c => Assert.True(double.IsFinite(c.X) && double.IsFinite(c.Y) && double.IsFinite(c.Z)));
+ break;
+
+ case BoltRow.TableKey when section.RowSize == BoltRow.ExpectedRowSize:
+ var bolts = section.AsBolts();
+ Assert.Equal(section.Rows.Count, bolts.Count);
+ Assert.All(bolts, b => Assert.True(b.Id > 0 && b.FirstPointId > 0 && b.SecondPointId > 0));
+ break;
+
+ case WeldingRow.TableKey when section.RowSize == WeldingRow.ExpectedRowSize:
+ var welds = section.AsWeldings();
+ Assert.Equal(section.Rows.Count, welds.Count);
+ Assert.All(welds, w => Assert.True(w.Id > 0));
+ break;
+
+ case ObjectPhaseRow.TableKey when section.RowSize == ObjectPhaseRow.ExpectedRowSize:
+ var phases = section.AsObjectPhases();
+ Assert.Equal(section.Rows.Count, phases.Count);
+ Assert.All(phases, ph => Assert.True(ph.ObjectId > 0 && ph.PhaseNumber >= 0));
+ break;
+
+ case RelationRow.TableKey when section.RowSize == RelationRow.ExpectedRowSize:
+ var rels = section.AsRelations();
+ Assert.Equal(section.Rows.Count, rels.Count);
+ Assert.All(rels, r => Assert.True(r.Id > 0 && r.Guid != null));
+ break;
+
+ case NumAttrRow.TableKey when section.RowSize == NumAttrRow.ExpectedRowSize:
+ var numAttrs = section.AsNumAttrs();
+ Assert.Equal(section.Rows.Count, numAttrs.Count);
+ Assert.All(numAttrs, n => Assert.True(n.Id > 0 && n.AttrId > 0));
+ break;
+
+ case StrAttrRow.TableKey when section.RowSize == StrAttrRow.ExpectedRowSize:
+ var strAttrs = section.AsStrAttrs();
+ Assert.Equal(section.Rows.Count, strAttrs.Count);
+ Assert.All(strAttrs, s => Assert.True(s.Id > 0 && s.AttrId > 0));
+ break;
+
+ case PartAttrRow.TableKey when section.RowSize == PartAttrRow.ExpectedRowSize:
+ var partAttrs = section.AsPartAttrs();
+ Assert.Equal(section.Rows.Count, partAttrs.Count);
+ Assert.All(partAttrs, pa => Assert.True(pa.Id > 0 && pa.Profile != null));
+ break;
+
+ case PartNumberingRow.TableKey when section.RowSize == PartNumberingRow.ExpectedRowSize:
+ var partNums = section.AsPartNumberings();
+ Assert.Equal(section.Rows.Count, partNums.Count);
+ Assert.All(partNums, pn => Assert.True(pn.Id > 0 && pn.Prefix != null));
+ break;
+
+ case AssemblyNumberingRow.TableKey when section.RowSize == AssemblyNumberingRow.ExpectedRowSize:
+ var assNums = section.AsAssemblyNumberings();
+ Assert.Equal(section.Rows.Count, assNums.Count);
+ Assert.All(assNums, an => Assert.True(an.Id > 0 && an.Prefix != null));
+ break;
+
+ case ObjectNumberingRow.TableKey when section.RowSize == ObjectNumberingRow.ExpectedRowSize:
+ var objNums = section.AsObjectNumberings();
+ Assert.Equal(section.Rows.Count, objNums.Count);
+ Assert.All(objNums, on => Assert.True(on.Id > 0));
+ break;
+
+ case ObjectModificationRow.TableKey when section.RowSize == ObjectModificationRow.ExpectedRowSize:
+ var mods = section.AsObjectModifications();
+ Assert.Equal(section.Rows.Count, mods.Count);
+ Assert.All(mods, m => Assert.True(m.ModificationId > 0 && m.Id > 0));
+ break;
+
+ case BoltHoleRow.TableKey when section.RowSize == BoltHoleRow.ExpectedRowSize:
+ var holes = section.AsBoltHoles();
+ Assert.Equal(section.Rows.Count, holes.Count);
+ Assert.All(holes, h => Assert.True(h.BoltId > 0 && h.PartId > 0));
+ break;
+
+ case BoltHolePointsRow.TableKey when section.RowSize == BoltHolePointsRow.ExpectedRowSize:
+ var holePts = section.AsBoltHolePoints();
+ Assert.Equal(section.Rows.Count, holePts.Count);
+ Assert.All(holePts, hp => Assert.True(hp.BoltId > 0 && hp.NumHoles > 0));
+ break;
+
+ case StrAttrAttrRow.TableKey when section.RowSize == StrAttrAttrRow.ExpectedRowSize:
+ var strDefs = section.AsStrAttrAttrs();
+ Assert.Equal(section.Rows.Count, strDefs.Count);
+ Assert.All(strDefs, sd => Assert.True(sd.Id > 0 && sd.Name != null));
+ break;
+
+ case NumAttrAttrRow.TableKey when section.RowSize == NumAttrAttrRow.ExpectedRowSize:
+ var numDefs = section.AsNumAttrAttrs();
+ Assert.Equal(section.Rows.Count, numDefs.Count);
+ Assert.All(numDefs, nd => Assert.True(nd.Id > 0 && nd.Name != null));
+ break;
+
+ case StringPoolRow.TableKey when section.RowSize == StringPoolRow.ExpectedRowSize:
+ var strPool = section.AsStringPool();
+ Assert.Equal(section.Rows.Count, strPool.Count);
+ Assert.All(strPool, sp => Assert.True(sp.Id > 0 && sp.Text != null));
+ break;
+ }
+ }
+ }
+ }
+}