diff --git a/CHANGELOG.md b/CHANGELOG.md index 4390afb..b9fff71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ API between minor releases. ### Added +- Read saved object material names from older reference caches and show them in scene metadata. - 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. diff --git a/README.md b/README.md index 6ae1fe3..f80efdf 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`, `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 | +| 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, labels and material names, 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 9e75d5a..47c7721 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -536,6 +536,7 @@ private static Command Parse(string[] args) break; case LegacyReferenceAttributesDocument attributes: Add("objectLabels", attributes.Labels.Count); + Add("materialNames", attributes.MaterialNames.Count); break; case LegacyReferenceDefinitionsDocument definitions: Add("polygonMeshes", definitions.Meshes.Count); diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs index d52e7f1..722372f 100644 --- a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs @@ -37,8 +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("hierarchy.tsfodat", "legacy-reference-hierarchy", "object relationships")?.Relations ?? []; - var labels = ReadOptional("attributes.tsfodat", - "legacy-reference-labels", "object labels")?.Labels; + var attributes = ReadOptional("attributes.tsfodat", + "legacy-reference-attributes", "object attributes"); var instancesByObject = instances.ToLookup(instance => instance.ObjectId); var usableRelations = new List(); int invalidRelations = 0; @@ -75,7 +75,7 @@ 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 label = attributes?.Labels.GetValueOrDefault(objectKey) ?? default; var element = new SceneElement { Id = ElementId(index), ModelId = 1, ParentId = parents[index] < 0 ? 1 : ElementId(parents[index]), @@ -100,7 +100,8 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n } element.PropertySetIds.Add(propertySetId); } - TrimBimSceneReader.AddObjectMetadata(source, element, label.Description, label.ObjectType); + TrimBimSceneReader.AddObjectMetadata(source, element, label.Description, label.ObjectType, + attributes?.MaterialNames.GetValueOrDefault(objectKey)); source.Elements.Add(element); } TrimBimSceneReader.AddGroupMemberships(source, groupMembers); diff --git a/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs b/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs index 2b85cac..3d86e6d 100644 --- a/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs +++ b/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs @@ -31,9 +31,10 @@ 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) + internal static void AddObjectMetadata(SceneDocument scene, SceneElement element, string? description, + string? objectType = null, string? materialName = null) { - if (description == null && objectType == null) return; + if (description == null && objectType == null && materialName == null) return; const string key = "trimbim:object"; var set = new ScenePropertySet { Id = scene.PropertySets.Count + 1, Name = "TrimBIM", Key = key }; @@ -41,6 +42,8 @@ internal static void AddObjectMetadata(SceneDocument scene, SceneElement element 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) }); + if (materialName != null) + set.Properties.Add(new SceneProperty { Name = "Material", Key = $"{key}:material", Value = SceneValue.FromText(materialName) }); scene.PropertySets.Add(set); element.PropertySetIds.Add(set.Id); } diff --git a/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs index 067a283..5cd3890 100644 --- a/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs +++ b/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs @@ -7,6 +7,8 @@ internal static partial class LegacyReferenceCacheReader private const int AttributeHeaderSize = 8; private const uint ObjectNameAttribute = 29; private const uint ObjectMetadataAttribute = 31; + private const uint ObjectMaterialAttribute = 33; + private const int ObjectMaterialTailSize = 5; private const int ObjectNameTailSize = 96; private const int ObjectHistoryTextCount = 13; private const int ObjectHistoryFixedSize = 21; @@ -14,14 +16,17 @@ internal static partial class LegacyReferenceCacheReader public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data) { var labels = new Dictionary(); + var materialNames = new Dictionary(); 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); + if (kind is not (ObjectNameAttribute or ObjectMetadataAttribute or ObjectMaterialAttribute)) continue; + if (!seen.Add((objectId, kind))) + throw FormatError.At(kind == ObjectMaterialAttribute ? "Duplicate reference cache object material attribute" + : "Duplicate reference cache object label attribute", body); int offset = body + AttributeHeaderSize; int end = body + size; @@ -33,6 +38,15 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data) continue; } + if (kind == ObjectMaterialAttribute) + { + string? name = ReadAttributeText(data, ref offset, end); + if (end - offset != ObjectMaterialTailSize) + throw FormatError.At("Invalid reference cache object material record length", offset); + if (name != null) materialNames.Add(objectId, name); + 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); @@ -43,7 +57,8 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data) if (offset != end) throw FormatError.At("Invalid reference cache object label record length", offset); labels[objectId] = label; } - return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary(labels)); + return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary(labels), + new ReadOnlyDictionary(materialNames)); } private static string? ReadAttributeText(byte[] data, ref int offset, int end) diff --git a/src/TdbIO/LegacyReferenceCacheDocuments.cs b/src/TdbIO/LegacyReferenceCacheDocuments.cs index 6928aef..36d500e 100644 --- a/src/TdbIO/LegacyReferenceCacheDocuments.cs +++ b/src/TdbIO/LegacyReferenceCacheDocuments.cs @@ -57,14 +57,22 @@ internal LegacyReferenceHierarchyDocument(IReadOnlyList /// The raw saved relationship code. public readonly record struct LegacyReferenceRelation(uint Id, uint ParentObjectId, uint ChildObjectId, uint KindCode); -/// The saved object labels from a legacy reference attribute table. +/// The saved object labels and material names from a legacy reference attribute table. public sealed class LegacyReferenceAttributesDocument : TdbDocument { - internal LegacyReferenceAttributesDocument(IReadOnlyDictionary labels) - : base(TdbFileKind.LegacyReferenceAttributes, []) => Labels = labels; + internal LegacyReferenceAttributesDocument(IReadOnlyDictionary labels, + IReadOnlyDictionary materialNames) + : base(TdbFileKind.LegacyReferenceAttributes, []) + { + Labels = labels; + MaterialNames = materialNames; + } /// Labels by saved foreign object key. Full metadata takes precedence over name-only attributes. public IReadOnlyDictionary Labels { get; } + + /// Nonempty saved material names by foreign object key. + public IReadOnlyDictionary MaterialNames { get; } } /// The saved descriptive fields of a foreign object in an older reference cache. diff --git a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs index 3f2b0fa..7c97f7e 100644 --- a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs +++ b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs @@ -263,8 +263,10 @@ public void KeepsOlderReferenceGeometryWhenTheHierarchyTableIsMalformed() Assert.Equal(2, result.Document.Elements.Count(element => element.IfcGuid == "0000000000000000000025")); } - [Fact] - public void UsesSavedObjectLabelsAndGroupNamesInBothPlacementsOfAnOlderCache() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void UsesSavedObjectLabelsAndMaterialsInBothPlacementsOfAnOlderCache(bool generateGeometry) { const string ifcId = "0000000000000000000025"; string path = CreateInput(writeCurrent: false); @@ -272,9 +274,11 @@ public void UsesSavedObjectLabelsAndGroupNamesInBothPlacementsOfAnOlderCache() Synthetic.LegacyReferenceObjectRecord(29, "0000000000000000000029")); WriteLegacyHierarchy(cache, Synthetic.LegacyReferenceRelationRecord(1, 6, 29, 25)); WriteLegacyAttributes(cache, Synthetic.LegacyReferenceLabelRecord(1, 25, "Стойка", "Входной узел", "Column type"), - Synthetic.LegacyReferenceNameRecord(2, 29, "Контур 🟦")); + Synthetic.LegacyReferenceNameRecord(2, 29, "Контур 🟦"), + Synthetic.LegacyReferenceObjectMaterialRecord(3, 25, "Сталь"), + Synthetic.LegacyReferenceObjectMaterialRecord(4, 26, "Бетон")); - var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = false }); + var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = generateGeometry }); Assert.Empty(result.Diagnostics); var scene = result.Document; var parts = scene.Elements.Where(element => element.IfcGuid == ifcId).ToArray(); @@ -287,20 +291,28 @@ public void UsesSavedObjectLabelsAndGroupNamesInBothPlacementsOfAnOlderCache() 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("Сталь", Assert.Single(properties, item => item.Key == "trimbim:object:material").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")); + var fallbackObjects = scene.Elements.Where(element => element.Name == "Object 26").ToArray(); + Assert.Equal(2, fallbackObjects.Length); + Assert.All(fallbackObjects, element => Assert.Contains(scene.PropertySets, set => + element.PropertySetIds.Contains(set.Id) && set.Properties.Any(property => + property.Key == "trimbim:object:material" && property.Value.Text == "Бетон"))); + Assert.Equal(generateGeometry ? 4 : 0, scene.Instances.Count); + Assert.All(scene.Instances, instance => Assert.Equal(new RgbaColor(3, 17, 31, 190), instance.Color)); + Assert.Empty(scene.Materials); } [Fact] - public void KeepsOlderReferenceGeometryWhenTheLabelTableIsMalformed() + public void KeepsOlderReferenceGeometryWhenTheAttributeTableIsMalformed() { 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.Contains("The older cache object attributes 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")); } diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index f45ea30..cc356cf 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -104,16 +104,18 @@ public void InfoCountsOlderReferenceRelationships() } [Fact] - public void InfoCountsOlderReferenceObjectLabels() + public void InfoCountsOlderReferenceObjectLabelsAndMaterialNames() { string file = File("attributes.tsfodat", Gzip(Concat(LegacyReferenceNameRecord(1, 25, "Post"), - LegacyReferenceLabelRecord(2, 25, "Post", "Steel post", "Post type")))); + LegacyReferenceLabelRecord(2, 25, "Post", "Steel post", "Post type"), + LegacyReferenceObjectMaterialRecord(3, 25, "Steel"), LegacyReferenceObjectMaterialRecord(4, 26, "Concrete")))); var (exit, stdout, stderr) = Run("info", file, "--json"); Assert.Equal(Cli.ExitOk, exit); Assert.Empty(stderr); using var json = JsonDocument.Parse(stdout); Assert.Equal("LegacyReferenceAttributes", json.RootElement.GetProperty("kind").GetString()); Assert.Equal(1, json.RootElement.GetProperty("objectLabels").GetInt32()); + Assert.Equal(2, json.RootElement.GetProperty("materialNames").GetInt32()); } [Fact] diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs index 58183a4..9a4a5c4 100644 --- a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -113,6 +113,31 @@ public void ReadsSavedLabelsAndPrefersTheFullMetadataRegardlessOfOrder(bool reve Assert.Equal(default, document.Labels[9]); } + [Fact] + public void ReadsMaterialNamesByObjectKeyIndependentlyOfObjectLabels() + { + using var file = new MemoryStream(Gzip(Concat(LegacyReferenceObjectMaterialRecord(1, 25, "Сталь 🟦"), + LegacyReferenceNameRecord(2, 25, "Member"), LegacyReferenceObjectMaterialRecord(3, 26, "Concrete"), + LegacyReferenceObjectMaterialRecord(4, 27, "")))); + var document = Assert.IsType(TdbFile.Open(file, "attributes.tsfodat")); + Assert.Equal("Member", Assert.Single(document.Labels).Value.Name); + Assert.Equal(2, document.MaterialNames.Count); + Assert.Equal("Сталь 🟦", document.MaterialNames[25]); + Assert.Equal("Concrete", document.MaterialNames[26]); + } + + [Fact] + public void RejectsTruncatedOrDuplicateMaterialNameRecords() + { + byte[] material = LegacyReferenceObjectMaterialRecord(1, 25, "Steel"); + using var truncated = new MemoryStream(Gzip(LegacyReferenceRecord(1, material[8..^1]))); + using var duplicate = new MemoryStream(Gzip(Concat(material, LegacyReferenceObjectMaterialRecord(2, 25, "Concrete")))); + Assert.Contains("object material record length", Assert.Throws( + () => TdbFile.Open(truncated, "attributes.tsfodat")).Message); + Assert.Contains("Duplicate reference cache object material", Assert.Throws( + () => TdbFile.Open(duplicate, "attributes.tsfodat")).Message); + } + [Fact] public void RejectsAnAttributeLengthThatWouldReadIntoTheNextRecord() { diff --git a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs index 526510d..66df522 100644 --- a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs +++ b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs @@ -64,6 +64,9 @@ internal static byte[] LegacyReferenceLabelRecord(uint id, uint objectId, string => LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(31), LegacyAttributeText("Author 🟦"), new byte[12 * sizeof(uint) + 21], LegacyAttributeText(name), LegacyAttributeText(description), LegacyAttributeText(objectType))); + internal static byte[] LegacyReferenceObjectMaterialRecord(uint id, uint objectId, string name) + => LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(33), LegacyAttributeText(name), [0], Le32(-1))); + private static byte[] LegacyAttributeText(string value) => Concat(Le32(value.Length), Encoding.Unicode.GetBytes(value)); internal static byte[] LegacyReferenceRelationRecord(uint id, uint kind, uint parent, uint child)