Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ API between minor releases.

### Added

- Show saved object names, descriptions and object type text from older reference caches.
- Restore the saved object hierarchy and group memberships when exporting references from older caches.
- Read saved IFC GlobalIds from older reference caches and link each insertion to its own Tekla object identities.
- Read saved double-precision curve sets from older reference caches and export their curve-only lines, points and arcs.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ extension and the property fields.
| `.idrm` | `IdRanges` | Next free value, ranges | One field of each range |
| `guid.mapper` | `GuidMapper` | GUID pairs | The header line (raw bytes) |
| TrimBIM caches (`.trb`, TRB8) | `TrimBim` | Source object GUIDs, names, classes, descriptions, placements, relationships and geometry | Original cache bytes |
| Older reference cache tables (`layers.tsfodat`, `materials.tsfodat`, `instances.tsfodat`, `foreignobjects.tsfodat`, `hierarchy.tsfodat`, `definitions.tsfodat`, `textures.tsfodat`) | Legacy reference cache documents | Geometry instances, IFC GlobalIds, object relationships, polygon meshes with holes and UV or normals, layer names, colors and images | Saved layer state code |
| Older reference cache tables (`layers.tsfodat`, `materials.tsfodat`, `instances.tsfodat`, `foreignobjects.tsfodat`, `hierarchy.tsfodat`, `attributes.tsfodat`, `definitions.tsfodat`, `textures.tsfodat`) | Legacy reference cache documents | Geometry instances, IFC GlobalIds, object relationships and labels, polygon meshes with holes and UV or normals, layer names, colors and images | Saved layer state code |
| `history.db` | `History` | Header, revisions and linked object actions | Stored times, action codes and time GUIDs |
| `.nc1` (DSTV NC) | `Nc1` | Header fields, geometry, manufacturing data, information entries and comments | Original lines for all blocks, including unrecognized codes |
| `.tpl`, `.rpt` | `Template` | Block tree, properties, strings, numbers, identifiers, tuples | Expressions inside strings are not evaluated |
Expand Down
3 changes: 3 additions & 0 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,9 @@ private static Command Parse(string[] args)
case LegacyReferenceHierarchyDocument hierarchy:
Add("relationships", hierarchy.Relations.Count);
break;
case LegacyReferenceAttributesDocument attributes:
Add("objectLabels", attributes.Labels.Count);
break;
case LegacyReferenceDefinitionsDocument definitions:
Add("polygonMeshes", definitions.Meshes.Count);
Add("curveSets", definitions.CurveSets.Count);
Expand Down
7 changes: 6 additions & 1 deletion src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
"legacy-reference-identity", "object identities")?.Objects.ToDictionary(item => item.Id, item => item.IfcGlobalId) ?? [];
var savedRelations = ReadOptional<LegacyReferenceHierarchyDocument>("hierarchy.tsfodat",
"legacy-reference-hierarchy", "object relationships")?.Relations ?? [];
var labels = ReadOptional<LegacyReferenceAttributesDocument>("attributes.tsfodat",
"legacy-reference-labels", "object labels")?.Labels;
var instancesByObject = instances.ToLookup(instance => instance.ObjectId);
var usableRelations = new List<LegacyReferenceRelation>();
int invalidRelations = 0;
Expand Down Expand Up @@ -73,11 +75,13 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
uint objectKey = objectKeys[index];
string id = objectKey.ToString(CultureInfo.InvariantCulture);
identities.TryGetValue(objectKey, out string? ifcGlobalId);
var label = labels?.GetValueOrDefault(objectKey) ?? default;
var element = new SceneElement
{
Id = ElementId(index), ModelId = 1, ParentId = parents[index] < 0 ? 1 : ElementId(parents[index]),
SourceId = ifcGlobalId ?? id, IfcGuid = ifcGlobalId,
Kind = groupMembers.Contains(index) ? SceneNodeKind.Group : SceneNodeKind.Element, Name = $"Object {id}",
Kind = groupMembers.Contains(index) ? SceneNodeKind.Group : SceneNodeKind.Element,
Name = label.Name ?? $"Object {id}",
};
foreach (uint layerId in instancesByObject[objectKey].Select(instance => instance.LayerId).Distinct())
{
Expand All @@ -96,6 +100,7 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
}
element.PropertySetIds.Add(propertySetId);
}
TrimBimSceneReader.AddObjectMetadata(source, element, label.Description, label.ObjectType);
source.Elements.Add(element);
}
TrimBimSceneReader.AddGroupMemberships(source, groupMembers);
Expand Down
14 changes: 14 additions & 0 deletions src/TdbIO.Scene/TrimBimSceneReader.Properties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ private static void AddImportMetadata(SceneDocument scene, TrimBimDocument docum
scene.Elements[0].PropertySetIds.Add(set.Id);
}

internal static void AddObjectMetadata(SceneDocument scene, SceneElement element, string? description, string? objectType = null)
{
if (description == null && objectType == null) return;

const string key = "trimbim:object";
var set = new ScenePropertySet { Id = scene.PropertySets.Count + 1, Name = "TrimBIM", Key = key };
if (description != null)
set.Properties.Add(new SceneProperty { Name = "Description", Key = $"{key}:description", Value = SceneValue.FromText(description) });
if (objectType != null)
set.Properties.Add(new SceneProperty { Name = "Object type", Key = $"{key}:object-type", Value = SceneValue.FromText(objectType) });
scene.PropertySets.Add(set);
element.PropertySetIds.Add(set.Id);
}

internal static void AddGroupMemberships(SceneDocument scene, ILookup<int, int> groupMembers)
{
foreach (var members in groupMembers)
Expand Down
14 changes: 1 addition & 13 deletions src/TdbIO.Scene/TrimBimSceneReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,7 @@ private static TrimBimSceneResult Convert(TrimBimDocument document, string key,
Name = label.Name ?? globalId ?? string.Create(CultureInfo.InvariantCulture, $"Object {index + 1}"),
Category = label.TypeName ?? string.Empty,
};
if (label.Description is { } description)
{
var properties = new ScenePropertySet
{
Id = scene.PropertySets.Count + 1, Name = "TrimBIM", Key = "trimbim:object",
Properties = [new SceneProperty
{
Name = "Description", Key = "trimbim:object:description", Value = SceneValue.FromText(description),
}],
};
scene.PropertySets.Add(properties);
element.PropertySetIds.Add(properties.Id);
}
AddObjectMetadata(scene, element, label.Description);
scene.Elements.Add(element);
}
AddLevels(scene, placements, parents, spatialParents, metresPerUnit);
Expand Down
64 changes: 64 additions & 0 deletions src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System.Collections.ObjectModel;

namespace TdbIO.Internal;

internal static partial class LegacyReferenceCacheReader
{
private const int AttributeHeaderSize = 8;
private const uint ObjectNameAttribute = 29;
private const uint ObjectMetadataAttribute = 31;
private const int ObjectNameTailSize = 96;
private const int ObjectHistoryTextCount = 13;
private const int ObjectHistoryFixedSize = 21;

public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data)
{
var labels = new Dictionary<uint, LegacyReferenceObjectLabel>();
var seen = new HashSet<(uint ObjectId, uint Kind)>();
foreach (var (_, body, size) in ReadRecords(data))
{
if (size < AttributeHeaderSize) throw FormatError.At("Invalid reference cache attribute size", body - 4);
uint objectId = Bytes.U32(data, body);
uint kind = Bytes.U32(data, body + sizeof(uint));
if (kind is not (ObjectNameAttribute or ObjectMetadataAttribute)) continue;
if (!seen.Add((objectId, kind))) throw FormatError.At("Duplicate reference cache object label attribute", body);

int offset = body + AttributeHeaderSize;
int end = body + size;
if (kind == ObjectNameAttribute)
{
string? name = ReadAttributeText(data, ref offset, end);
if (end - offset != ObjectNameTailSize) throw FormatError.At("Invalid reference cache object name record length", offset);
labels.TryAdd(objectId, new LegacyReferenceObjectLabel(name, null, null));
continue;
}

// The three label fields follow the saved history strings and its fixed-width fields.
for (int i = 0; i < ObjectHistoryTextCount; i++)
offset += sizeof(uint) + ReadAttributeTextLength(data, offset, end);
Bytes.Need(offset, ObjectHistoryFixedSize, end, "Reference cache object history");
offset += ObjectHistoryFixedSize;
var label = new LegacyReferenceObjectLabel(ReadAttributeText(data, ref offset, end),
ReadAttributeText(data, ref offset, end), ReadAttributeText(data, ref offset, end));
if (offset != end) throw FormatError.At("Invalid reference cache object label record length", offset);
labels[objectId] = label;
}
return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary<uint, LegacyReferenceObjectLabel>(labels));
}

private static string? ReadAttributeText(byte[] data, ref int offset, int end)
{
int length = ReadAttributeTextLength(data, offset, end);
int start = offset + sizeof(uint);
offset = start + length;
return length == 0 ? null : Bytes.LengthDelimitedText(data, start, length, Utf16Encoding);
}

private static int ReadAttributeTextLength(byte[] data, int offset, int end)
{
Bytes.Need(offset, sizeof(uint), end, "Reference cache text length");
long length = 2L * Bytes.U32(data, offset);
Bytes.Need(offset + sizeof(uint), length, end, "Reference cache text");
return (int)length;
}
}
6 changes: 4 additions & 2 deletions src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ internal static partial class LegacyReferenceCacheReader
private const int ObjectFixedSize = ObjectGeometryKeyCountOffset + sizeof(uint);
private const int IfcIdentitySize = 96;
private const int IdentityTagSize = 3 * sizeof(uint);
private static readonly Encoding LayerEncoding = new UnicodeEncoding(false, false, true);
private static readonly Encoding Utf16Encoding = new UnicodeEncoding(false, false, true);

public static TdbFileKind KindFromName(string? fileName)
{
Expand All @@ -25,6 +25,7 @@ public static TdbFileKind KindFromName(string? fileName)
if (string.Equals(name, "textures.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceTextures;
if (string.Equals(name, "foreignobjects.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceObjects;
if (string.Equals(name, "hierarchy.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceHierarchy;
if (string.Equals(name, "attributes.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceAttributes;
return TdbFileKind.Unknown;
}

Expand All @@ -44,6 +45,7 @@ public static bool HasRecordHeader(ReadOnlySpan<byte> head, TdbFileKind kind)
TdbFileKind.LegacyReferenceObjects => head.Length >= RecordHeaderSize + ObjectFixedSize
&& ObjectFixedSize + sizeof(uint) * (long)Bytes.U32(head, RecordHeaderSize + ObjectGeometryKeyCountOffset) <= size,
TdbFileKind.LegacyReferenceHierarchy => size == RelationSize,
TdbFileKind.LegacyReferenceAttributes => size >= AttributeHeaderSize,
_ => false,
};
}
Expand All @@ -57,7 +59,7 @@ public static LegacyReferenceLayersDocument ReadLayers(byte[] data)
if (size < LayerFixedSize || size != LayerFixedSize + 2L * Bytes.U32(data, body))
throw FormatError.At("Invalid reference cache layer name length", body);
if (!ids.Add(id)) throw FormatError.At("Duplicate reference cache layer ID", body - RecordHeaderSize);
string name = Bytes.LengthDelimitedText(data, body + 4, size - LayerFixedSize, LayerEncoding);
string name = Bytes.LengthDelimitedText(data, body + 4, size - LayerFixedSize, Utf16Encoding);
layers.Add(new LegacyReferenceLayer(id, name, Bytes.U32(data, body + size - 4)));
}
return new LegacyReferenceLayersDocument(layers.AsReadOnly());
Expand Down
16 changes: 16 additions & 0 deletions src/TdbIO/LegacyReferenceCacheDocuments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,22 @@ internal LegacyReferenceHierarchyDocument(IReadOnlyList<LegacyReferenceRelation>
/// <param name="KindCode">The raw saved relationship code.</param>
public readonly record struct LegacyReferenceRelation(uint Id, uint ParentObjectId, uint ChildObjectId, uint KindCode);

/// <summary>The saved object labels from a legacy reference attribute table.</summary>
public sealed class LegacyReferenceAttributesDocument : TdbDocument
{
internal LegacyReferenceAttributesDocument(IReadOnlyDictionary<uint, LegacyReferenceObjectLabel> labels)
: base(TdbFileKind.LegacyReferenceAttributes, []) => Labels = labels;

/// <summary>Labels by saved foreign object key. Full metadata takes precedence over name-only attributes.</summary>
public IReadOnlyDictionary<uint, LegacyReferenceObjectLabel> Labels { get; }
}

/// <summary>The saved descriptive fields of a foreign object in an older reference cache.</summary>
/// <param name="Name">The saved object name, when present.</param>
/// <param name="Description">The saved object description, when present.</param>
/// <param name="ObjectType">The saved object type text, when present.</param>
public readonly record struct LegacyReferenceObjectLabel(string? Name, string? Description, string? ObjectType);

/// <summary>A saved foreign object in an older reference cache.</summary>
/// <param name="Id">The key referenced by geometry instances from the same cache.</param>
/// <param name="IfcGlobalId">The saved IFC GlobalId when present in a known identity record, otherwise null.</param>
Expand Down
1 change: 1 addition & 0 deletions src/TdbIO/TdbFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ private static TdbDocument Read(Stream stream, string? fileName, TdbReadOptions
TdbFileKind.LegacyReferenceTextures => LegacyReferenceCacheReader.ReadTextures(payload),
TdbFileKind.LegacyReferenceObjects => LegacyReferenceCacheReader.ReadObjects(payload),
TdbFileKind.LegacyReferenceHierarchy => LegacyReferenceCacheReader.ReadHierarchy(payload),
TdbFileKind.LegacyReferenceAttributes => LegacyReferenceCacheReader.ReadAttributes(payload),
_ => throw NotRecognised(),
};
}
Expand Down
3 changes: 3 additions & 0 deletions src/TdbIO/TdbFileKind.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,7 @@ public enum TdbFileKind

/// <summary>A gzip-compressed reference object relationship table named <c>hierarchy.tsfodat</c>.</summary>
LegacyReferenceHierarchy,

/// <summary>A gzip-compressed reference object attribute table named <c>attributes.tsfodat</c>.</summary>
LegacyReferenceAttributes,
}
45 changes: 45 additions & 0 deletions tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,48 @@ public void KeepsOlderReferenceGeometryWhenTheHierarchyTableIsMalformed()
Assert.Equal(2, result.Document.Elements.Count(element => element.IfcGuid == "0000000000000000000025"));
}

[Fact]
public void UsesSavedObjectLabelsAndGroupNamesInBothPlacementsOfAnOlderCache()
{
const string ifcId = "0000000000000000000025";
string path = CreateInput(writeCurrent: false);
string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, ifcId),
Synthetic.LegacyReferenceObjectRecord(29, "0000000000000000000029"));
WriteLegacyHierarchy(cache, Synthetic.LegacyReferenceRelationRecord(1, 6, 29, 25));
WriteLegacyAttributes(cache, Synthetic.LegacyReferenceLabelRecord(1, 25, "Стойка", "Входной узел", "Column type"),
Synthetic.LegacyReferenceNameRecord(2, 29, "Контур 🟦"));

var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = false });
Assert.Empty(result.Diagnostics);
var scene = result.Document;
var parts = scene.Elements.Where(element => element.IfcGuid == ifcId).ToArray();
Assert.Equal(2, parts.Length);
Assert.All(parts, element =>
{
Assert.Equal("Стойка", element.Name);
var properties = scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id))
.SelectMany(set => set.Properties);
Assert.Equal("Входной узел", Assert.Single(properties, item => item.Name == "Description").Value.Text);
Assert.Equal("Column type", Assert.Single(properties, item => item.Name == "Object type").Value.Text);
Assert.Equal("Контур 🟦", Assert.Single(properties, item => item.Name == "Group").Value.Text);
});
Assert.Equal(2, scene.Elements.Count(element => element.Kind == SceneNodeKind.Group && element.Name == "Контур 🟦"));
Assert.Equal(2, scene.Elements.Count(element => element.Name == "Object 26"));
}

[Fact]
public void KeepsOlderReferenceGeometryWhenTheLabelTableIsMalformed()
{
string path = CreateInput(writeCurrent: false);
string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, "0000000000000000000025"));
WriteLegacyAttributes(cache, Synthetic.LegacyReferenceRecord(1,
Synthetic.Concat(Synthetic.Le32(25), Synthetic.Le32(31), Synthetic.Le32(1000))));
var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true });
Assert.Contains("The older cache object labels could not be read.", Assert.Single(result.Diagnostics).Message);
Assert.Equal(4, result.Document.Instances.Count);
Assert.Equal(2, result.Document.Elements.Count(element => element.Name == "Object 25"));
}

private static IEnumerable<SceneProperty> TeklaIds(SceneDocument scene, SceneElement element) =>
scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id))
.SelectMany(set => set.Properties)
Expand Down Expand Up @@ -390,6 +432,9 @@ public void AssignsAReferenceObjectOnlyToItsSavedInsertion(bool legacy)
private static void WriteLegacyHierarchy(string cache, params byte[][] relations) =>
File.WriteAllBytes(Path.Combine(cache, "hierarchy.tsfodat"), Synthetic.Gzip(Synthetic.Concat(relations)));

private static void WriteLegacyAttributes(string cache, params byte[][] attributes) =>
File.WriteAllBytes(Path.Combine(cache, "attributes.tsfodat"), Synthetic.Gzip(Synthetic.Concat(attributes)));

private string CreateLegacyCache(params byte[][] objects)
{
string cache = Path.Combine(_directory, "RefCacheFolders", $"7_{Synthetic.ReferenceSceneHash}");
Expand Down
Loading
Loading