diff --git a/CHANGELOG.md b/CHANGELOG.md index 988a207..17150fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 36dc42c..d3687c5 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index 5e9f753..4e7e226 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -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); diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs index 72c6625..1621993 100644 --- a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs @@ -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("instances.tsfodat").Instances; var layers = Open("layers.tsfodat").Layers.ToDictionary(layer => layer.Id); - var identities = ReadObjectIdentities(); + var identities = ReadOptional("foreignobjects.tsfodat", + "legacy-reference-identity", "object identities")?.Objects.ToDictionary(item => item.Id, item => item.IfcGlobalId) ?? []; + var savedRelations = ReadOptional("hierarchy.tsfodat", + "legacy-reference-hierarchy", "object relationships")?.Relations ?? []; + var instancesByObject = instances.ToLookup(instance => instance.ObjectId); + var usableRelations = new List(); + 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(); - var objectIds = new Dictionary(); - 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)) { @@ -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) { @@ -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, @@ -159,22 +193,25 @@ T Open(string fileName) where T : TdbDocument return TdbFile.Open(path) as T ?? throw new InvalidDataException($"Invalid older cache file '{fileName}'."); } - Dictionary ReadObjectIdentities() + bool HasObject(uint key) => instancesByObject.Contains(key) || identities.ContainsKey(key); + + static long ElementId(int index) => index + 2L; + + T? ReadOptional(string fileName, string code, string description) where T : TdbDocument { try { - return Open("foreignobjects.tsfodat").Objects - .ToDictionary(item => item.Id, item => item.IfcGlobalId); + return Open(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; } } diff --git a/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs b/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs index 54f43e7..bba3c58 100644 --- a/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs +++ b/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs @@ -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 groupMembers) + internal static void AddGroupMemberships(SceneDocument scene, ILookup groupMembers) { foreach (var members in groupMembers) { diff --git a/src/TdbIO.Scene/TrimBimSceneReader.cs b/src/TdbIO.Scene/TrimBimSceneReader.cs index 569458a..22a6bee 100644 --- a/src/TdbIO.Scene/TrimBimSceneReader.cs +++ b/src/TdbIO.Scene/TrimBimSceneReader.cs @@ -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); @@ -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 relations, int count, - List diagnostics, out int[] spatialParents) + internal static int[] ReadParents(IReadOnlyList relations, int count, + out int[] spatialParents, out int discarded) { var parent = new int[count]; spatialParents = new int[count]; @@ -196,7 +199,7 @@ private static int[] ReadParents(IReadOnlyList relations, var visited = new bool[count]; var onPath = new bool[count]; var path = new List(); - 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]; @@ -222,11 +225,6 @@ private static int[] ReadParents(IReadOnlyList 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; } diff --git a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs index 7d83237..8a4b373 100644 --- a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs +++ b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs @@ -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; @@ -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; } @@ -41,6 +43,7 @@ public static bool HasRecordHeader(ReadOnlySpan 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, }; } @@ -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(); + var ids = new HashSet(); + 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 diff --git a/src/TdbIO/LegacyReferenceCacheDocuments.cs b/src/TdbIO/LegacyReferenceCacheDocuments.cs index ea020ea..2862ba0 100644 --- a/src/TdbIO/LegacyReferenceCacheDocuments.cs +++ b/src/TdbIO/LegacyReferenceCacheDocuments.cs @@ -40,6 +40,23 @@ internal LegacyReferenceObjectsDocument(IReadOnlyList obj public IReadOnlyList Objects { get; } } +/// The saved relationships between foreign objects in an older reference cache, in file order. +public sealed class LegacyReferenceHierarchyDocument : TdbDocument +{ + internal LegacyReferenceHierarchyDocument(IReadOnlyList relations) + : base(TdbFileKind.LegacyReferenceHierarchy, []) => Relations = relations; + + /// The relationship records, including unrecognised relationship codes. + public IReadOnlyList Relations { get; } +} + +/// A saved relationship between two foreign objects in an older reference cache. +/// The key of the relationship record. +/// The foreign object key of the parent or group. +/// The foreign object key of the child or group member. +/// The raw saved relationship code. +public readonly record struct LegacyReferenceRelation(uint Id, uint ParentObjectId, uint ChildObjectId, uint KindCode); + /// A saved foreign object in an older reference cache. /// The key referenced by geometry instances from the same cache. /// The saved IFC GlobalId when present in a known identity record, otherwise null. diff --git a/src/TdbIO/TdbFile.cs b/src/TdbIO/TdbFile.cs index faa2fa8..620f61d 100644 --- a/src/TdbIO/TdbFile.cs +++ b/src/TdbIO/TdbFile.cs @@ -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(), }; } diff --git a/src/TdbIO/TdbFileKind.cs b/src/TdbIO/TdbFileKind.cs index 9d3b956..b550167 100644 --- a/src/TdbIO/TdbFileKind.cs +++ b/src/TdbIO/TdbFileKind.cs @@ -90,4 +90,7 @@ public enum TdbFileKind /// A gzip-compressed reference object table named foreignobjects.tsfodat. LegacyReferenceObjects, + + /// A gzip-compressed reference object relationship table named hierarchy.tsfodat. + LegacyReferenceHierarchy, } diff --git a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs index ee8432b..1dd2aa4 100644 --- a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs +++ b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs @@ -190,6 +190,79 @@ public void KeepsOlderReferenceGeometryWhenTheObjectTableIsMalformed() Assert.DoesNotContain(result.Document.Elements, element => element.IfcGuid != null); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RestoresOlderReferenceParentsAndSharedGroupMemberships(bool generateGeometry) + { + const string groupGuid = "0000000000000000000028"; + const string systemGuid = "0000000000000000000029"; + string path = CreateInput(writeCurrent: false); + string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, "0000000000000000000025"), + Synthetic.LegacyReferenceObjectRecord(26, "0000000000000000000026"), + Synthetic.LegacyReferenceObjectRecord(27, "0000000000000000000027"), + Synthetic.LegacyReferenceObjectRecord(28, groupGuid), + Synthetic.LegacyReferenceObjectRecord(29, systemGuid), + Synthetic.LegacyReferenceObjectRecord(30, "0000000000000000000030")); + WriteLegacyHierarchy(cache, Synthetic.LegacyReferenceRelationRecord(1, 2, 27, 25), + Synthetic.LegacyReferenceRelationRecord(2, 4, 26, 25), Synthetic.LegacyReferenceRelationRecord(3, 1, 27, 26), + Synthetic.LegacyReferenceRelationRecord(4, 5, 28, 25), Synthetic.LegacyReferenceRelationRecord(5, 6, 29, 25), + Synthetic.LegacyReferenceRelationRecord(6, 5, 28, 25), Synthetic.LegacyReferenceRelationRecord(7, 0, 30, 25)); + + var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = generateGeometry }); + Assert.Empty(result.Diagnostics); + Assert.Equal(generateGeometry ? 4 : 0, result.Document.Instances.Count); + var scene = result.Document; + Assert.Equal(2, scene.PropertySets.Count(set => set.Name == "Group membership")); + foreach (var model in scene.Models.Skip(1)) + { + var nodes = scene.Elements.Where(element => element.ModelId == model.Id).ToDictionary(element => element.Name); + Assert.Equal(6, nodes.Count); + Assert.Equal(nodes["Object 26"].Id, nodes["Object 25"].ParentId); + Assert.Equal(nodes["Object 27"].Id, nodes["Object 26"].ParentId); + Assert.Equal(SceneNodeKind.Group, nodes["Object 28"].Kind); + Assert.Equal(SceneNodeKind.Group, nodes["Object 29"].Kind); + Assert.DoesNotContain("Object 30", nodes.Keys); + var memberSets = scene.PropertySets.Where(set => set.Name == "Group membership" + && nodes["Object 25"].PropertySetIds.Contains(set.Id)); + Assert.Equal(new[] { groupGuid, systemGuid }, + memberSets.Select(set => set.Properties.Single(property => property.Name == "IFC GlobalId").Value.Text)); + } + } + + [Fact] + public void KeepsOlderReferenceGeometryAndValidLinksWhenOtherLinksAreInvalid() + { + string path = CreateInput(writeCurrent: false); + string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(27, null), + Synthetic.LegacyReferenceObjectRecord(28, null)); + WriteLegacyHierarchy(cache, Synthetic.LegacyReferenceRelationRecord(1, 1, 25, 26), + Synthetic.LegacyReferenceRelationRecord(2, 4, 26, 25), Synthetic.LegacyReferenceRelationRecord(3, 2, 27, 28), + Synthetic.LegacyReferenceRelationRecord(4, 6, 999, 25)); + var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true }); + Assert.Equal(4, result.Document.Instances.Count); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message.Contains("1 relationships with invalid endpoints", StringComparison.Ordinal)); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message.Contains("1 objects at the scene root", StringComparison.Ordinal)); + Assert.DoesNotContain(result.Diagnostics, diagnostic => diagnostic.Severity == SceneSeverity.Error); + var first = result.Document.Elements.Where(element => element.ModelId == result.Document.Models[1].Id) + .ToDictionary(element => element.Name); + Assert.Equal(first["Object 27"].Id, first["Object 28"].ParentId); + Assert.DoesNotContain("Object 999", first.Keys); + } + + [Fact] + public void KeepsOlderReferenceGeometryWhenTheHierarchyTableIsMalformed() + { + string path = CreateInput(writeCurrent: false); + string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, "0000000000000000000025")); + WriteLegacyHierarchy(cache, Synthetic.LegacyReferenceRecord(1, new byte[11])); + var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true }); + var warning = Assert.Single(result.Diagnostics); + Assert.Contains("The older cache object relationships could not be read.", warning.Message); + Assert.Equal(4, result.Document.Instances.Count); + Assert.Equal(2, result.Document.Elements.Count(element => element.IfcGuid == "0000000000000000000025")); + } + private static IEnumerable TeklaIds(SceneDocument scene, SceneElement element) => scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id)) .SelectMany(set => set.Properties) @@ -314,7 +387,10 @@ public void AssignsAReferenceObjectOnlyToItsSavedInsertion(bool legacy) Assert.Equal("task-schedule-member", Assert.Single(nativeOnly.Diagnostics).Code); } - private void CreateLegacyCache(params byte[][] objects) + private static void WriteLegacyHierarchy(string cache, params byte[][] relations) => + File.WriteAllBytes(Path.Combine(cache, "hierarchy.tsfodat"), Synthetic.Gzip(Synthetic.Concat(relations))); + + private string CreateLegacyCache(params byte[][] objects) { string cache = Path.Combine(_directory, "RefCacheFolders", $"7_{Synthetic.ReferenceSceneHash}"); Directory.CreateDirectory(cache); @@ -324,6 +400,7 @@ private void CreateLegacyCache(params byte[][] objects) WriteTable("instances.tsfodat", Synthetic.LegacyReferenceInstanceRecord(18, 5, 3, 25), Synthetic.LegacyReferenceInstanceRecord(18, 5, 3, 26)); WriteTable("foreignobjects.tsfodat", objects); + return cache; void WriteTable(string filename, params byte[][] records) => File.WriteAllBytes(Path.Combine(cache, filename), Synthetic.Gzip(Synthetic.Concat(records))); diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index ebff45f..a5eb893 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -90,6 +90,19 @@ public void InfoCountsOlderReferenceObjectsAndSavedIfcGlobalIds() Assert.Equal(1, json.RootElement.GetProperty("ifcGlobalIds").GetInt32()); } + [Fact] + public void InfoCountsOlderReferenceRelationships() + { + string file = File("hierarchy.tsfodat", Gzip(Concat( + LegacyReferenceRelationRecord(1, 2, 18, 25), LegacyReferenceRelationRecord(2, 0, 26, 25)))); + var (exit, stdout, stderr) = Run("info", file, "--json"); + Assert.Equal(Cli.ExitOk, exit); + Assert.Empty(stderr); + using var json = JsonDocument.Parse(stdout); + Assert.Equal("LegacyReferenceHierarchy", json.RootElement.GetProperty("kind").GetString()); + Assert.Equal(2, json.RootElement.GetProperty("relationships").GetInt32()); + } + [Fact] public void InfoShowsSavedTrimBimGeometryLayersInOrder() { @@ -198,6 +211,8 @@ public void ExportsAndProtectsAnOlderReferenceCacheWhenTrimBimIsMissing() string instances = File(Path.Combine(cache, "instances.tsfodat"), saved); byte[] foreignObjects = Gzip(LegacyReferenceObjectRecord(25, "0000000000000000000001", 18)); string objects = File(Path.Combine(cache, "foreignobjects.tsfodat"), foreignObjects); + byte[] relations = Gzip([]); + string hierarchy = File(Path.Combine(cache, "hierarchy.tsfodat"), relations); var export = Run("export", db, "--scene-json", "--reference-models"); Assert.Equal(Cli.ExitOk, export.Exit); @@ -223,6 +238,11 @@ public void ExportsAndProtectsAnOlderReferenceCacheWhenTrimBimIsMissing() Assert.Contains("reference cache", overwrite.Err); Assert.Equal(foreignObjects, System.IO.File.ReadAllBytes(objects)); + overwrite = Run("export", db, hierarchy, "--scene-json", "--reference-models"); + Assert.Equal(Cli.ExitUsage, overwrite.Exit); + Assert.Contains("reference cache", overwrite.Err); + Assert.Equal(relations, System.IO.File.ReadAllBytes(hierarchy)); + Directory.CreateDirectory(Path.Combine(_folder, "RefCacheFolders", $"8_{ReferenceSceneHash}")); var ambiguous = Run("export", db, "--scene-json", "--reference-models"); Assert.Contains("Several older cache folders", ambiguous.Err); diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs index 6c99389..9bd7492 100644 --- a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -67,6 +67,33 @@ public void RejectsATruncatedIfcIdentityAndDuplicateForeignObjectKeys() () => TdbFile.Open(duplicate, "foreignobjects.tsfodat")).Message); } + [Fact] + public void ReadsStoredHierarchyKeysEndpointsAndRawCodesInFileOrder() + { + using var file = new MemoryStream(Gzip(Concat(LegacyReferenceRelationRecord(9, 6, 11, 12), + LegacyReferenceRelationRecord(2, 0, 18, 30), LegacyReferenceRelationRecord(5, uint.MaxValue, 10, 20)))); + Assert.Equal(TdbFileKind.Unknown, TdbFile.DetectKind(file, "relationships.tsfodat")); + Assert.Equal(TdbFileKind.LegacyReferenceHierarchy, TdbFile.DetectKind(file, "HIERARCHY.TSFODAT")); + var document = Assert.IsType(TdbFile.Open(file, "hierarchy.tsfodat")); + Assert.Equal(new[] { new LegacyReferenceRelation(9, 11, 12, 6), new LegacyReferenceRelation(2, 18, 30, 0), + new LegacyReferenceRelation(5, 10, 20, uint.MaxValue) }, document.Relations); + using var empty = new MemoryStream(Gzip([])); + Assert.Empty(Assert.IsType(TdbFile.Open(empty, "hierarchy.tsfodat")).Relations); + } + + [Fact] + public void RejectsWrongHierarchyRecordLengthsAndRepeatedRecordKeys() + { + using var malformed = new MemoryStream(Gzip(LegacyReferenceRecord(1, new byte[11]))); + using var duplicate = new MemoryStream(Gzip(Concat(LegacyReferenceRelationRecord(1, 6, 11, 12), + LegacyReferenceRelationRecord(1, 2, 11, 13)))); + Assert.Equal(TdbFileKind.Unknown, TdbFile.DetectKind(malformed, "hierarchy.tsfodat")); + Assert.Contains("relationship size", Assert.Throws( + () => TdbFile.Open(malformed, "hierarchy.tsfodat")).Message); + Assert.Contains("Duplicate reference cache relationship ID", Assert.Throws( + () => TdbFile.Open(duplicate, "hierarchy.tsfodat")).Message); + } + [Fact] public void ReadsMeshContoursImagesAndOptionalVertexFields() { diff --git a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs index f0f2c88..6e922b0 100644 --- a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs +++ b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs @@ -57,6 +57,9 @@ internal static byte[] LegacyReferenceObjectRecord(uint id, string? ifcGlobalId, Concat(geometryKeys.Select(Le32).ToArray()), identity)); } + internal static byte[] LegacyReferenceRelationRecord(uint id, uint kind, uint parent, uint child) + => LegacyReferenceRecord(id, Concat(Le32(kind), Le32(parent), Le32(child))); + internal static byte[] LegacyReferenceRecord(uint id, byte[] body) => Concat(Le32(id), Le32(body.Length), body); private static byte[] LegacyDoubles(params double[] coordinates)