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

- 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.
- Reconstruct polygon meshes with holes, UVs, normals and embedded images from older reference caches when a current TRB8 cache is absent.
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`, `definitions.tsfodat`, `textures.tsfodat`) | Legacy reference cache documents | Geometry instances, IFC GlobalIds, 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`, `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 |
| `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 @@ -531,6 +531,9 @@ private static Command Parse(string[] args)
Add("objects", objects.Objects.Count);
Add("ifcGlobalIds", objects.Objects.Count(item => item.IfcGlobalId is not null));
break;
case LegacyReferenceHierarchyDocument hierarchy:
Add("relationships", hierarchy.Relations.Count);
break;
case LegacyReferenceDefinitionsDocument definitions:
Add("polygonMeshes", definitions.Meshes.Count);
Add("curveSets", definitions.CurveSets.Count);
Expand Down
71 changes: 54 additions & 17 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,53 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
source.Elements.Add(new SceneElement { Id = 1, ModelId = 1, Kind = SceneNodeKind.Model, Name = name });
var instances = Open<LegacyReferenceInstancesDocument>("instances.tsfodat").Instances;
var layers = Open<LegacyReferenceLayersDocument>("layers.tsfodat").Layers.ToDictionary(layer => layer.Id);
var identities = ReadObjectIdentities();
var identities = ReadOptional<LegacyReferenceObjectsDocument>("foreignobjects.tsfodat",
"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 instancesByObject = instances.ToLookup(instance => instance.ObjectId);
var usableRelations = new List<LegacyReferenceRelation>();
int invalidRelations = 0;
foreach (var relation in savedRelations)
{
if (relation.KindCode is < 1 or > 6) continue;
if (!HasObject(relation.ParentObjectId) || !HasObject(relation.ChildObjectId) ||
(relation.KindCode is 5 or 6 && relation.ParentObjectId == relation.ChildObjectId))
{
invalidRelations++;
continue;
}
usableRelations.Add(relation);
}
if (invalidRelations > 0)
diagnostics.Add(new(SceneSeverity.Warning, "legacy-reference-hierarchy",
string.Create(CultureInfo.InvariantCulture, $"The older cache omitted {invalidRelations} relationships with invalid endpoints.")));

// Keep the instance objects in their original order, then add related objects without instances.
uint[] objectKeys = instances.Select(instance => instance.ObjectId)
.Union(usableRelations.SelectMany(relation => new[] { relation.ParentObjectId, relation.ChildObjectId })).ToArray();
var objectIndices = objectKeys.Select((key, index) => (key, index)).ToDictionary(pair => pair.key, pair => pair.index);
var relations = usableRelations.Select(relation => new TrimBimObjectRelation(objectIndices[relation.ParentObjectId],
objectIndices[relation.ChildObjectId], (int)relation.KindCode)).ToArray();
int[] parents = TrimBimSceneReader.ReadParents(relations, objectKeys.Length, out _, out int discardedParents);
if (discardedParents > 0)
diagnostics.Add(new(SceneSeverity.Warning, "legacy-reference-parent",
string.Create(CultureInfo.InvariantCulture, $"The older cache left {discardedParents} objects at the scene root after encountering conflicting or cyclic parents.")));
var groupMembers = relations.Where(relation => relation.IsGroupMembership)
.ToLookup(relation => relation.ParentObjectIndex, relation => relation.ChildObjectIndex);
var layerProperties = new Dictionary<uint, int>();
var objectIds = new Dictionary<uint, long>();
foreach (var group in instances.GroupBy(instance => instance.ObjectId))
for (int index = 0; index < objectKeys.Length; index++)
{
string id = group.Key.ToString(CultureInfo.InvariantCulture);
identities.TryGetValue(group.Key, out string? ifcGlobalId);
uint objectKey = objectKeys[index];
string id = objectKey.ToString(CultureInfo.InvariantCulture);
identities.TryGetValue(objectKey, out string? ifcGlobalId);
var element = new SceneElement
{
Id = source.Elements.Count + 1, ModelId = 1, ParentId = 1, SourceId = ifcGlobalId ?? id,
IfcGuid = ifcGlobalId, Kind = SceneNodeKind.Element, Name = $"Object {id}",
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}",
};
foreach (uint layerId in group.Select(instance => instance.LayerId).Distinct())
foreach (uint layerId in instancesByObject[objectKey].Select(instance => instance.LayerId).Distinct())
{
if (!layerProperties.TryGetValue(layerId, out int propertySetId))
{
Expand All @@ -62,9 +96,9 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
}
element.PropertySetIds.Add(propertySetId);
}
objectIds.Add(group.Key, element.Id);
source.Elements.Add(element);
}
TrimBimSceneReader.AddGroupMemberships(source, groupMembers);

if (generateGeometry)
{
Expand Down Expand Up @@ -118,7 +152,7 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n

void AddInstance(int id, int? materialId) => source.Instances.Add(new SceneInstance
{
ElementId = objectIds[instance.ObjectId], GeometryId = id,
ElementId = ElementId(objectIndices[instance.ObjectId]), GeometryId = id,
Color = new RgbaColor(rgba.Red, rgba.Green, rgba.Blue, rgba.Alpha),
Transform = transform == Transform3d.Identity ? null : transform,
MaterialId = materialId,
Expand Down Expand Up @@ -159,22 +193,25 @@ T Open<T>(string fileName) where T : TdbDocument
return TdbFile.Open(path) as T ?? throw new InvalidDataException($"Invalid older cache file '{fileName}'.");
}

Dictionary<uint, string?> ReadObjectIdentities()
bool HasObject(uint key) => instancesByObject.Contains(key) || identities.ContainsKey(key);

static long ElementId(int index) => index + 2L;

T? ReadOptional<T>(string fileName, string code, string description) where T : TdbDocument
{
try
{
return Open<LegacyReferenceObjectsDocument>("foreignobjects.tsfodat").Objects
.ToDictionary(item => item.Id, item => item.IfcGlobalId);
return Open<T>(fileName);
}
catch (FileNotFoundException)
{
return [];
return null;
}
catch (Exception error) when (error is InvalidDataException or IOException or UnauthorizedAccessException)
{
diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "legacy-reference-identity",
$"The older cache object identities could not be read. {error.Message}"));
return [];
diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, code,
$"The older cache {description} could not be read. {error.Message}"));
return null;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/TdbIO.Scene/TrimBimSceneReader.Properties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ private static void AddImportMetadata(SceneDocument scene, TrimBimDocument docum
scene.Elements[0].PropertySetIds.Add(set.Id);
}

private static void AddGroupMemberships(SceneDocument scene, ILookup<int, int> groupMembers)
internal static void AddGroupMemberships(SceneDocument scene, ILookup<int, int> groupMembers)
{
foreach (var members in groupMembers)
{
Expand Down
16 changes: 7 additions & 9 deletions src/TdbIO.Scene/TrimBimSceneReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ private static TrimBimSceneResult Convert(TrimBimDocument document, string key,
scene.Elements.Add(new SceneElement { Id = rootId, ModelId = modelId, Kind = SceneNodeKind.Model, Name = key });
var placements = document.ReadObjectPlacements().ToArray();
var relations = document.ReadObjectRelations().ToArray();
int[] parents = ReadParents(relations, placements.Length, diagnostics, out var spatialParents);
int[] parents = ReadParents(relations, placements.Length, out var spatialParents, out int discardedParents);
if (discardedParents > 0)
diagnostics.Add(new(SceneSeverity.Warning, "trimbim-parent",
string.Create(CultureInfo.InvariantCulture, $"TrimBIM left {discardedParents} objects at the scene root after encountering conflicting or cyclic parents.")));
var groupMembers = relations.Where(relation => relation.IsGroupMembership)
.ToLookup(relation => relation.ParentObjectIndex, relation => relation.ChildObjectIndex);
var labels = document.ReadObjectLabels().ToDictionary(label => label.ObjectIndex);
Expand Down Expand Up @@ -176,8 +179,8 @@ private static TrimBimSceneResult Convert(TrimBimDocument document, string key,
=> bytes.StartsWith(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }) ? "image/png"
: bytes.StartsWith(new byte[] { 0xFF, 0xD8, 0xFF }) ? "image/jpeg" : null;

private static int[] ReadParents(IReadOnlyList<TrimBimObjectRelation> relations, int count,
List<SceneDiagnostic> diagnostics, out int[] spatialParents)
internal static int[] ReadParents(IReadOnlyList<TrimBimObjectRelation> relations, int count,
out int[] spatialParents, out int discarded)
{
var parent = new int[count];
spatialParents = new int[count];
Expand All @@ -196,7 +199,7 @@ private static int[] ReadParents(IReadOnlyList<TrimBimObjectRelation> relations,
var visited = new bool[count];
var onPath = new bool[count];
var path = new List<int>();
int discarded = 0;
discarded = 0;
// An element may be nested under another element and also contained in a storey.
for (int i = 0; i < count; i++)
if (parent[i] == NoParent) parent[i] = spatialParents[i];
Expand All @@ -222,11 +225,6 @@ private static int[] ReadParents(IReadOnlyList<TrimBimObjectRelation> relations,
}
path.Clear();
}
if (discarded > 0)
{
diagnostics.Add(new(SceneSeverity.Warning, "trimbim-parent",
string.Create(CultureInfo.InvariantCulture, $"TrimBIM left {discarded} objects at the scene root after encountering conflicting or cyclic parents.")));
}
return parent;
}

Expand Down
17 changes: 17 additions & 0 deletions src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ internal static partial class LegacyReferenceCacheReader
private const int LayerFixedSize = 8;
private const int MaterialSize = 29;
private const int InstanceSize = 120;
private const int RelationSize = 12;
private const int ObjectGeometryKeyCountOffset = 60;
private const int ObjectFixedSize = ObjectGeometryKeyCountOffset + sizeof(uint);
private const int IfcIdentitySize = 96;
Expand All @@ -23,6 +24,7 @@ public static TdbFileKind KindFromName(string? fileName)
if (string.Equals(name, "definitions.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceDefinitions;
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;
return TdbFileKind.Unknown;
}

Expand All @@ -41,6 +43,7 @@ public static bool HasRecordHeader(ReadOnlySpan<byte> head, TdbFileKind kind)
TdbFileKind.LegacyReferenceTextures => head.Length >= 16 && size >= 8 && Bytes.U32(head, 12) == size - 8,
TdbFileKind.LegacyReferenceObjects => head.Length >= RecordHeaderSize + ObjectFixedSize
&& ObjectFixedSize + sizeof(uint) * (long)Bytes.U32(head, RecordHeaderSize + ObjectGeometryKeyCountOffset) <= size,
TdbFileKind.LegacyReferenceHierarchy => size == RelationSize,
_ => false,
};
}
Expand Down Expand Up @@ -107,6 +110,20 @@ public static LegacyReferenceObjectsDocument ReadObjects(byte[] data)
return new LegacyReferenceObjectsDocument(objects.AsReadOnly());
}

public static LegacyReferenceHierarchyDocument ReadHierarchy(byte[] data)
{
var relations = new List<LegacyReferenceRelation>();
var ids = new HashSet<uint>();
foreach (var (id, body, size) in ReadRecords(data))
{
if (size != RelationSize) throw FormatError.At("Invalid reference cache relationship size", body - 4);
if (!ids.Add(id)) throw FormatError.At("Duplicate reference cache relationship ID", body - RecordHeaderSize);
relations.Add(new LegacyReferenceRelation(id, Bytes.U32(data, body + 4), Bytes.U32(data, body + 8),
Bytes.U32(data, body)));
}
return new LegacyReferenceHierarchyDocument(relations.AsReadOnly());
}

private static string? ReadObjectIfcGlobalId(byte[] data, int identity, int end)
{
if (end - identity < IdentityTagSize || Bytes.U32(data, identity) != IfcIdentitySize
Expand Down
17 changes: 17 additions & 0 deletions src/TdbIO/LegacyReferenceCacheDocuments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@ internal LegacyReferenceObjectsDocument(IReadOnlyList<LegacyReferenceObject> obj
public IReadOnlyList<LegacyReferenceObject> Objects { get; }
}

/// <summary>The saved relationships between foreign objects in an older reference cache, in file order.</summary>
public sealed class LegacyReferenceHierarchyDocument : TdbDocument
{
internal LegacyReferenceHierarchyDocument(IReadOnlyList<LegacyReferenceRelation> relations)
: base(TdbFileKind.LegacyReferenceHierarchy, []) => Relations = relations;

/// <summary>The relationship records, including unrecognised relationship codes.</summary>
public IReadOnlyList<LegacyReferenceRelation> Relations { get; }
}

/// <summary>A saved relationship between two foreign objects in an older reference cache.</summary>
/// <param name="Id">The key of the relationship record.</param>
/// <param name="ParentObjectId">The foreign object key of the parent or group.</param>
/// <param name="ChildObjectId">The foreign object key of the child or group member.</param>
/// <param name="KindCode">The raw saved relationship code.</param>
public readonly record struct LegacyReferenceRelation(uint Id, uint ParentObjectId, uint ChildObjectId, uint KindCode);

/// <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 @@ -116,6 +116,7 @@ private static TdbDocument Read(Stream stream, string? fileName, TdbReadOptions
TdbFileKind.LegacyReferenceDefinitions => LegacyReferenceCacheReader.ReadDefinitions(payload),
TdbFileKind.LegacyReferenceTextures => LegacyReferenceCacheReader.ReadTextures(payload),
TdbFileKind.LegacyReferenceObjects => LegacyReferenceCacheReader.ReadObjects(payload),
TdbFileKind.LegacyReferenceHierarchy => LegacyReferenceCacheReader.ReadHierarchy(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 @@ -90,4 +90,7 @@ public enum TdbFileKind

/// <summary>A gzip-compressed reference object table named <c>foreignobjects.tsfodat</c>.</summary>
LegacyReferenceObjects,

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