From 2d075f1d24ef6d447fea178ce34489cf3aa721fa Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Sun, 6 Dec 2026 18:31:14 +0300 Subject: [PATCH] Read property sets and units from older reference caches --- CHANGELOG.md | 1 + README.md | 2 +- src/TdbIO.Cli/Cli.cs | 1 + .../TdbSceneReader.LegacyReferences.cs | 19 ++++- .../TrimBimSceneReader.Properties.cs | 37 ++++---- .../LegacyReferenceAttributeReader.cs | 85 ++++++++++++++++++- .../Container/LegacyReferenceCacheReader.cs | 6 +- .../Internal/TrimBimPropertyUnitReader.cs | 32 +++++++ src/TdbIO/LegacyReferenceCacheDocuments.cs | 35 +++++++- src/TdbIO/TrimBimDocument.PropertyUnits.cs | 31 ++----- src/TdbIO/TrimBimPropertySet.cs | 8 +- .../TdbSceneReader.ReferenceTests.cs | 47 ++++++++++ tests/TdbIO.Tests/CliTests.cs | 4 +- .../TdbIO.Tests/LegacyReferenceCacheTests.cs | 44 ++++++++++ .../TdbIO.Tests/Synthetic.LegacyReference.cs | 21 +++++ 15 files changed, 318 insertions(+), 55 deletions(-) create mode 100644 src/TdbIO/Internal/TrimBimPropertyUnitReader.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index b9fff71..09b4145 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ API between minor releases. ### Added +- Read saved property sets from older reference caches and export typed values using the IFC project's declared units. - 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. diff --git a/README.md b/README.md index f80efdf..7f27f0a 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, labels and material names, 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, materials and property sets, 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 47c7721..be26bbc 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -537,6 +537,7 @@ private static Command Parse(string[] args) case LegacyReferenceAttributesDocument attributes: Add("objectLabels", attributes.Labels.Count); Add("materialNames", attributes.MaterialNames.Count); + Add("propertySets", attributes.PropertySets.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 722372f..8ce5d3e 100644 --- a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs @@ -33,8 +33,9 @@ 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 = ReadOptional("foreignobjects.tsfodat", - "legacy-reference-identity", "object identities")?.Objects.ToDictionary(item => item.Id, item => item.IfcGlobalId) ?? []; + var foreignObjects = ReadOptional("foreignobjects.tsfodat", + "legacy-reference-identity", "object identities"); + var identities = foreignObjects?.Objects.ToDictionary(item => item.Id, item => item.IfcGlobalId) ?? []; var savedRelations = ReadOptional("hierarchy.tsfodat", "legacy-reference-hierarchy", "object relationships")?.Relations ?? []; var attributes = ReadOptional("attributes.tsfodat", @@ -57,9 +58,11 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n 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. + // Keep instance objects in their original order, then add objects reached by relations or properties. + var propertySets = attributes?.PropertySets ?? []; uint[] objectKeys = instances.Select(instance => instance.ObjectId) - .Union(usableRelations.SelectMany(relation => new[] { relation.ParentObjectId, relation.ChildObjectId })).ToArray(); + .Union(usableRelations.SelectMany(relation => new[] { relation.ParentObjectId, relation.ChildObjectId })) + .Union(propertySets.Where(set => HasObject(set.ObjectId)).Select(set => set.ObjectId)).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(); @@ -105,6 +108,14 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n source.Elements.Add(element); } TrimBimSceneReader.AddGroupMemberships(source, groupMembers); + var units = (attributes != null && foreignObjects != null ? attributes.ReadPropertyUnits(foreignObjects) : []) + .ToDictionary(unit => unit.Kind); + foreach (var set in propertySets) + { + if (objectIndices.TryGetValue(set.ObjectId, out int index) && + TrimBimSceneReader.AddSavedPropertySet(source, set.Name, set.Properties, units) is int setId) + source.Elements[index + 1].PropertySetIds.Add(setId); + } if (generateGeometry) { diff --git a/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs b/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs index 3d86e6d..4df3ed6 100644 --- a/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs +++ b/src/TdbIO.Scene/TrimBimSceneReader.Properties.cs @@ -79,25 +79,32 @@ private static void AddPropertySets(SceneDocument scene, TrimBimDocument documen foreach (var source in document.ReadPropertySets()) { if (source.ObjectIndices.Count == 0) continue; - var set = new ScenePropertySet - { - Id = scene.PropertySets.Count + 1, Name = source.Name, - Key = $"trimbim:property-set:{Uri.EscapeDataString(source.Name)}", - }; - var occurrences = new Dictionary(StringComparer.Ordinal); - foreach (var property in source.Properties) - { - if (ConvertProperty(property, units) is not SceneValue value) continue; - string key = PropertyKey(set.Key, property.Name, occurrences); - set.Properties.Add(new SceneProperty { Name = property.Name, Key = key, Value = value }); - } - if (set.Properties.Count == 0) continue; - scene.PropertySets.Add(set); + if (AddSavedPropertySet(scene, source.Name, source.Properties, units) is not int setId) continue; foreach (int index in source.ObjectIndices.Distinct()) - scene.Elements[index + 1].PropertySetIds.Add(set.Id); + scene.Elements[index + 1].PropertySetIds.Add(setId); } } + internal static int? AddSavedPropertySet(SceneDocument scene, string name, IReadOnlyList properties, + IReadOnlyDictionary units) + { + var set = new ScenePropertySet + { + Id = scene.PropertySets.Count + 1, Name = name, + Key = $"trimbim:property-set:{Uri.EscapeDataString(name)}", + }; + var occurrences = new Dictionary(StringComparer.Ordinal); + foreach (var property in properties) + { + if (ConvertProperty(property, units) is not SceneValue value) continue; + string key = PropertyKey(set.Key, property.Name, occurrences); + set.Properties.Add(new SceneProperty { Name = property.Name, Key = key, Value = value }); + } + if (set.Properties.Count == 0) return null; + scene.PropertySets.Add(set); + return set.Id; + } + private static string PropertyKey(string scope, string name, Dictionary occurrences) { int occurrence = occurrences.GetValueOrDefault(name) + 1; diff --git a/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs index 5cd3890..b693895 100644 --- a/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs +++ b/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs @@ -6,6 +6,9 @@ internal static partial class LegacyReferenceCacheReader { private const int AttributeHeaderSize = 8; private const uint ObjectNameAttribute = 29; + private const uint PropertySetAttribute = 30; + private const int PropertySetHeaderSize = 22; + private const int MinimumScalarPropertySize = 17; private const uint ObjectMetadataAttribute = 31; private const uint ObjectMaterialAttribute = 33; private const int ObjectMaterialTailSize = 5; @@ -18,11 +21,20 @@ 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)) + var propertySets = new List(); + var propertySetIds = new HashSet(); + foreach (var (id, 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 == PropertySetAttribute) + { + if (!propertySetIds.Add(id)) throw FormatError.At("Duplicate reference cache property set ID", body); + propertySets.Add(ReadPropertySet(data, id, objectId, body + AttributeHeaderSize, body + size)); + continue; + } + 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" @@ -58,7 +70,76 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data) labels[objectId] = label; } return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary(labels), - new ReadOnlyDictionary(materialNames)); + new ReadOnlyDictionary(materialNames), propertySets.AsReadOnly()); + } + + private static LegacyReferencePropertySet ReadPropertySet(byte[] data, uint id, uint objectId, int offset, int end) + { + Bytes.Need(offset, PropertySetHeaderSize, end, "Reference cache property set header"); + offset += PropertySetHeaderSize; + string name = ReadAttributeText(data, ref offset, end) ?? string.Empty; + string? description = ReadAttributeText(data, ref offset, end); + Bytes.Need(offset, sizeof(uint), end, "Reference cache property count"); + uint count = Bytes.U32(data, offset); + offset += sizeof(uint); + Bytes.Need(offset, MinimumScalarPropertySize * (long)count, end, "Reference cache properties"); + var properties = new TrimBimProperty[count]; + for (int i = 0; i < properties.Length; i++) + { + Bytes.Need(offset, sizeof(uint), end, "Reference cache property layout"); + if (Bytes.U32(data, offset) != 1) + throw FormatError.At("Unsupported reference cache property layout", offset); + offset += sizeof(uint); + string propertyName = ReadAttributeText(data, ref offset, end) ?? string.Empty; + string? propertyDescription = ReadAttributeText(data, ref offset, end); + Bytes.Need(offset, sizeof(uint), end, "Reference cache property kind"); + TrimBimPropertyKind kind = Bytes.U32(data, offset) switch + { + 1 => TrimBimPropertyKind.Text, + 2 => TrimBimPropertyKind.Boolean, + 3 => TrimBimPropertyKind.Integer, + 4 => TrimBimPropertyKind.Number, + 5 => TrimBimPropertyKind.Length, + 6 => TrimBimPropertyKind.Volume, + 7 => TrimBimPropertyKind.Mass, + 8 => TrimBimPropertyKind.Area, + 9 => TrimBimPropertyKind.Angle, + _ => throw FormatError.At("Unsupported reference cache property kind", offset), + }; + offset += sizeof(uint); + properties[i] = new TrimBimProperty(propertyName, kind, ReadLegacyPropertyValue(data, kind, ref offset, end)) + { + Description = propertyDescription, + }; + } + + if (offset != end) throw FormatError.At("Invalid reference cache property set record length", offset); + return new LegacyReferencePropertySet(id, objectId, name, description, Array.AsReadOnly(properties)); + } + + private static object ReadLegacyPropertyValue(byte[] data, TrimBimPropertyKind kind, ref int offset, int end) + { + if (kind == TrimBimPropertyKind.Text) return ReadAttributeText(data, ref offset, end) ?? string.Empty; + int width = kind switch + { + TrimBimPropertyKind.Boolean => sizeof(byte), + TrimBimPropertyKind.Integer => sizeof(int), + _ => sizeof(double), + }; + int start = offset; + Bytes.Need(start, width, end, "Reference cache property value"); + offset += width; + if (kind == TrimBimPropertyKind.Boolean) + return data[start] switch + { + 0 => false, + 1 => true, + _ => throw FormatError.At("Invalid reference cache boolean property", start), + }; + if (kind == TrimBimPropertyKind.Integer) return Bytes.I32(data, start); + double value = Bytes.F64(data, start); + if (!double.IsFinite(value)) throw FormatError.At("Non-finite reference cache property value", start); + return value; } private static string? ReadAttributeText(byte[] data, ref int offset, int end) diff --git a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs index 7eec67c..241be37 100644 --- a/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs +++ b/src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs @@ -107,7 +107,11 @@ public static LegacyReferenceObjectsDocument ReadObjects(byte[] data) long identity = (long)body + ObjectFixedSize + sizeof(uint) * (long)Bytes.U32(data, countOffset); int end = body + size; if (identity > end) throw FormatError.At("Invalid reference cache object geometry key count", countOffset); - objects.Add(new LegacyReferenceObject(id, ReadObjectIfcGlobalId(data, (int)identity, end))); + string? ifcGlobalId = ReadObjectIfcGlobalId(data, (int)identity, end); + objects.Add(new LegacyReferenceObject(id, ifcGlobalId) + { + IsIfcProject = ifcGlobalId != null && Bytes.U32(data, body + 52) == 2 && Bytes.U32(data, body + 56) == 91, + }); } return new LegacyReferenceObjectsDocument(objects.AsReadOnly()); } diff --git a/src/TdbIO/Internal/TrimBimPropertyUnitReader.cs b/src/TdbIO/Internal/TrimBimPropertyUnitReader.cs new file mode 100644 index 0000000..62ee42d --- /dev/null +++ b/src/TdbIO/Internal/TrimBimPropertyUnitReader.cs @@ -0,0 +1,32 @@ +namespace TdbIO.Internal; + +internal static class TrimBimPropertyUnitReader +{ + private static readonly (TrimBimPropertyKind Kind, string Name, string Factor, double ToSi)[] PropertyUnitFields = + [ + (TrimBimPropertyKind.Length, "LENGTHUNIT.Name", "LENGTHUNIT.ScaleFactor", 0.001), + (TrimBimPropertyKind.Area, "AREAUNIT.Name", "AREAUNIT.ScaleFactor", 1), + (TrimBimPropertyKind.Volume, "VOLUMEUNIT.Name", "VOLUMEUNIT.ScaleFactor", 1), + (TrimBimPropertyKind.Mass, "MASSUNIT.Name", "MASSUNIT.ScaleFactor", 1), + (TrimBimPropertyKind.Angle, "PLANEANGLEUNIT.Name", "PLANEANGLEUNIT.Conversion", Math.PI / 180), + ]; + + internal static IEnumerable Read(IReadOnlyList properties) + { + var fields = properties.ToLookup(property => property.Name, property => property.Value, StringComparer.Ordinal); + foreach (var (kind, name, factor, toSi) in PropertyUnitFields) + { + string? unitName = ReadUniqueField(fields[name]) as string; + if (!string.IsNullOrWhiteSpace(unitName) && ReadUniqueField(fields[factor]) is double scale && scale > 0) + yield return new TrimBimPropertyUnit(kind, unitName, scale, toSi); + } + } + + private static object? ReadUniqueField(IEnumerable fields) + { + using var entries = fields.GetEnumerator(); + if (!entries.MoveNext()) return null; + var value = entries.Current; + return entries.MoveNext() ? null : value; + } +} diff --git a/src/TdbIO/LegacyReferenceCacheDocuments.cs b/src/TdbIO/LegacyReferenceCacheDocuments.cs index 36d500e..9648235 100644 --- a/src/TdbIO/LegacyReferenceCacheDocuments.cs +++ b/src/TdbIO/LegacyReferenceCacheDocuments.cs @@ -1,3 +1,5 @@ +using TdbIO.Internal; + namespace TdbIO; /// The saved layer table of an older reference cache, in file order. @@ -57,15 +59,16 @@ 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 and material names from a legacy reference attribute table. +/// The saved object labels, material names and property sets from a legacy reference attribute table. public sealed class LegacyReferenceAttributesDocument : TdbDocument { internal LegacyReferenceAttributesDocument(IReadOnlyDictionary labels, - IReadOnlyDictionary materialNames) + IReadOnlyDictionary materialNames, IReadOnlyList propertySets) : base(TdbFileKind.LegacyReferenceAttributes, []) { Labels = labels; MaterialNames = materialNames; + PropertySets = propertySets; } /// Labels by saved foreign object key. Full metadata takes precedence over name-only attributes. @@ -73,8 +76,30 @@ internal LegacyReferenceAttributesDocument(IReadOnlyDictionaryNonempty saved material names by foreign object key. public IReadOnlyDictionary MaterialNames { get; } + + /// Saved property sets in file order, including empty sets and sets with repeated names. + public IReadOnlyList PropertySets { get; } + + /// Reads declared property units for the single IFC project in the same reference cache. + public IEnumerable ReadPropertyUnits(LegacyReferenceObjectsDocument objects) + { + ArgumentNullException.ThrowIfNull(objects); + var projects = objects.Objects.Where(item => item.IsIfcProject).Take(2).ToArray(); + if (projects.Length != 1) return []; + var contexts = PropertySets.Where(set => set.ObjectId == projects[0].Id && set.Name == "UnitsInContext").Take(2).ToArray(); + return contexts.Length == 1 ? TrimBimPropertyUnitReader.Read(contexts[0].Properties) : []; + } } +/// A stored set of properties belonging to a foreign object in an older cache. +/// The saved attribute table key. +/// The key of the object in the same reference cache. +/// The saved set name. +/// The saved description, when present. +/// The stored property values in file order. +public sealed record LegacyReferencePropertySet(uint Id, uint ObjectId, string Name, string? Description, + IReadOnlyList Properties); + /// The saved descriptive fields of a foreign object in an older reference cache. /// The saved object name, when present. /// The saved object description, when present. @@ -84,7 +109,11 @@ internal LegacyReferenceAttributesDocument(IReadOnlyDictionaryA 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. -public readonly record struct LegacyReferenceObject(uint Id, string? IfcGlobalId); +public readonly record struct LegacyReferenceObject(uint Id, string? IfcGlobalId) +{ + /// Whether the cache identifies the object as an IFC project. + public bool IsIfcProject { get; init; } +} /// A named layer in an older reference cache. /// The key referenced by geometry instances from the same cache. diff --git a/src/TdbIO/TrimBimDocument.PropertyUnits.cs b/src/TdbIO/TrimBimDocument.PropertyUnits.cs index d64d95f..a140060 100644 --- a/src/TdbIO/TrimBimDocument.PropertyUnits.cs +++ b/src/TdbIO/TrimBimDocument.PropertyUnits.cs @@ -1,42 +1,21 @@ +using TdbIO.Internal; + namespace TdbIO; public sealed partial class TrimBimDocument { - private static readonly (TrimBimPropertyKind Kind, string Name, string Factor, double ToSi)[] PropertyUnitFields = - [ - (TrimBimPropertyKind.Length, "LENGTHUNIT.Name", "LENGTHUNIT.ScaleFactor", 0.001), - (TrimBimPropertyKind.Area, "AREAUNIT.Name", "AREAUNIT.ScaleFactor", 1), - (TrimBimPropertyKind.Volume, "VOLUMEUNIT.Name", "VOLUMEUNIT.ScaleFactor", 1), - (TrimBimPropertyKind.Mass, "MASSUNIT.Name", "MASSUNIT.ScaleFactor", 1), - (TrimBimPropertyKind.Angle, "PLANEANGLEUNIT.Name", "PLANEANGLEUNIT.Conversion", Math.PI / 180), - ]; - /// Reads property-unit declarations from an unambiguous IFC project context. /// A measurement kind with no usable declaration is omitted. /// A metadata vector, index or value is invalid. public IEnumerable ReadPropertyUnits() { var projects = ReadObjectLabels().Where(label => label.TypeName == "IFCPROJECT").Take(2).ToArray(); - if (projects.Length != 1) yield break; + if (projects.Length != 1) return []; int projectIndex = projects[0].ObjectIndex; var contexts = ReadPropertySets("UnitsInContext") .Where(set => set.ObjectIndices is [int index] && index == projectIndex).Take(2).ToArray(); - if (contexts.Length != 1) yield break; + if (contexts.Length != 1) return []; - var fields = contexts[0].Properties.ToLookup(property => property.Name, property => property.Value, StringComparer.Ordinal); - foreach (var (kind, name, factor, toSi) in PropertyUnitFields) - { - string? unitName = ReadUniqueField(fields[name]) as string; - if (!string.IsNullOrWhiteSpace(unitName) && ReadUniqueField(fields[factor]) is double scale && scale > 0) - yield return new TrimBimPropertyUnit(kind, unitName, scale, toSi); - } - } - - private static object? ReadUniqueField(IEnumerable fields) - { - using var entries = fields.GetEnumerator(); - if (!entries.MoveNext()) return null; - var value = entries.Current; - return entries.MoveNext() ? null : value; + return TrimBimPropertyUnitReader.Read(contexts[0].Properties); } } diff --git a/src/TdbIO/TrimBimPropertySet.cs b/src/TdbIO/TrimBimPropertySet.cs index 6bff56c..8b8d9a6 100644 --- a/src/TdbIO/TrimBimPropertySet.cs +++ b/src/TdbIO/TrimBimPropertySet.cs @@ -11,7 +11,11 @@ public sealed record TrimBimPropertySet(string Name, IReadOnlyList ObjectIn /// The stored value kind. Future kinds can have unnamed codes. /// The stored string, , or . /// For an unrecognized kind, the encoded word is returned as a . -public readonly record struct TrimBimProperty(string Name, TrimBimPropertyKind Kind, object Value); +public readonly record struct TrimBimProperty(string Name, TrimBimPropertyKind Kind, object Value) +{ + /// The saved description, when the cache records one. + public string? Description { get; init; } +} /// Identifies the storage and measurement kind of a TrimBIM property. public enum TrimBimPropertyKind : uint @@ -26,7 +30,7 @@ public enum TrimBimPropertyKind : uint Mass = 3, /// An angle in the cache's property units. Angle = 4, - /// UTF-8 text. + /// Text. Text = 5, /// A signed integer. Integer = 6, diff --git a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs index 7c97f7e..d88b100 100644 --- a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs +++ b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs @@ -304,6 +304,53 @@ public void UsesSavedObjectLabelsAndMaterialsInBothPlacementsOfAnOlderCache(bool Assert.Empty(scene.Materials); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void UsesOnlyTheLegacyIfcProjectForMeasurementsInBothPlacements(bool hasProjectMarker) + { + const string projectGuid = "0000000000000000000099"; + string input = CreateInput(writeCurrent: false); + byte[] project = hasProjectMarker ? Synthetic.LegacyReferenceProjectRecord(99, projectGuid) + : Synthetic.LegacyReferenceObjectRecord(99, projectGuid); + string cache = CreateLegacyCache(project, Synthetic.LegacyReferenceObjectRecord(25, "0000000000000000000025")); + WriteLegacyAttributes(cache, + Synthetic.LegacyReferencePropertySetRecord(1, 99, "UnitsInContext", + Synthetic.LegacyReferenceTextProperty("LENGTHUNIT.Name", "METRE"), + Synthetic.LegacyReferenceNumberProperty("LENGTHUNIT.ScaleFactor", 4, 0.001)), + Synthetic.LegacyReferencePropertySetRecord(2, 25, "UnitsInContext", + Synthetic.LegacyReferenceTextProperty("LENGTHUNIT.Name", "Other"), + Synthetic.LegacyReferenceNumberProperty("LENGTHUNIT.ScaleFactor", 4, 50), + Synthetic.LegacyReferenceTextProperty("MASSUNIT.Name", "Other"), + Synthetic.LegacyReferenceNumberProperty("MASSUNIT.ScaleFactor", 4, 1)), + Synthetic.LegacyReferencePropertySetRecord(3, 25, "Measurements", + Synthetic.LegacyReferenceNumberProperty("Length", 5, 1250), + Synthetic.LegacyReferenceNumberProperty("Mass", 7, 4), + Synthetic.LegacyReferenceProperty("In use", 2, [0])), + Synthetic.LegacyReferencePropertySetRecord(4, 25, "Measurements", + Synthetic.LegacyReferenceTextProperty("Comment", "Second occurrence"))); + + var result = TdbSceneReader.Read(input, new() { IncludeReferenceModels = true, GenerateGeometry = false }); + Assert.Empty(result.Diagnostics); + var scene = result.Document; + Assert.Equal(2, scene.Elements.Count(item => item.IfcGuid == projectGuid)); + Assert.All(scene.Elements.Where(item => item.IfcGuid == projectGuid), + item => Assert.Contains(scene.PropertySets, set => set.Name == "UnitsInContext" && item.PropertySetIds.Contains(set.Id))); + var objects = scene.Elements.Where(item => item.IfcGuid == "0000000000000000000025").ToArray(); + Assert.Equal(2, objects.Length); + Assert.All(objects, item => + { + var measurements = scene.PropertySets.Where(set => set.Name == "Measurements" && item.PropertySetIds.Contains(set.Id)).ToArray(); + Assert.Equal(2, measurements.Length); + var values = measurements.SelectMany(set => set.Properties).ToDictionary(property => property.Name, property => property.Value); + Assert.Equal(hasProjectMarker ? SceneValue.FromNumber(1.25, SceneUnits.Metre, "1.25 m") + : SceneValue.FromText("1250"), values["Length"]); + Assert.Equal(SceneValue.FromText("4"), values["Mass"]); + Assert.Equal(SceneValue.FromBoolean(false, "False"), values["In use"]); + Assert.Equal(SceneValue.FromText("Second occurrence"), values["Comment"]); + }); + } + [Fact] public void KeepsOlderReferenceGeometryWhenTheAttributeTableIsMalformed() { diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index cc356cf..5a47bc8 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -108,7 +108,8 @@ public void InfoCountsOlderReferenceObjectLabelsAndMaterialNames() { string file = File("attributes.tsfodat", Gzip(Concat(LegacyReferenceNameRecord(1, 25, "Post"), LegacyReferenceLabelRecord(2, 25, "Post", "Steel post", "Post type"), - LegacyReferenceObjectMaterialRecord(3, 25, "Steel"), LegacyReferenceObjectMaterialRecord(4, 26, "Concrete")))); + LegacyReferenceObjectMaterialRecord(3, 25, "Steel"), LegacyReferenceObjectMaterialRecord(4, 26, "Concrete"), + LegacyReferencePropertySetRecord(5, 25, "Properties")))); var (exit, stdout, stderr) = Run("info", file, "--json"); Assert.Equal(Cli.ExitOk, exit); Assert.Empty(stderr); @@ -116,6 +117,7 @@ public void InfoCountsOlderReferenceObjectLabelsAndMaterialNames() Assert.Equal("LegacyReferenceAttributes", json.RootElement.GetProperty("kind").GetString()); Assert.Equal(1, json.RootElement.GetProperty("objectLabels").GetInt32()); Assert.Equal(2, json.RootElement.GetProperty("materialNames").GetInt32()); + Assert.Equal(1, json.RootElement.GetProperty("propertySets").GetInt32()); } [Fact] diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs index 9a4a5c4..f45cc08 100644 --- a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -113,6 +113,50 @@ public void ReadsSavedLabelsAndPrefersTheFullMetadataRegardlessOfOrder(bool reve Assert.Equal(default, document.Labels[9]); } + [Fact] + public void ReadsLegacyScalarPropertyKindsAndPreservesSavedOccurrences() + { + using var file = new MemoryStream(Gzip(Concat( + LegacyReferencePropertySetRecord(8, 25, "Probe", + LegacyReferenceTextProperty("Identifier", "Часть 🟦"), LegacyReferenceTextProperty("Empty", ""), + LegacyReferenceProperty("Flag", 2, [1]), LegacyReferenceProperty("Count", 3, Le32(-7), "Signed"), + LegacyReferenceNumberProperty("Number", 4, 2.5), LegacyReferenceNumberProperty("Length", 5, 1000), + LegacyReferenceNumberProperty("Volume", 6, 3), LegacyReferenceNumberProperty("Mass", 7, 4), + LegacyReferenceNumberProperty("Area", 8, 5), LegacyReferenceNumberProperty("Angle", 9, 90)), + LegacyReferencePropertySetRecord(9, 25, "Probe")))); + var document = Assert.IsType(TdbFile.Open(file, "attributes.tsfodat")); + Assert.Equal(2, document.PropertySets.Count); + var set = document.PropertySets[0]; + Assert.Equal(8u, set.Id); + Assert.Equal(25u, set.ObjectId); + Assert.Equal("Probe", set.Name); + Assert.Equal(new[] + { + new TrimBimProperty("Identifier", TrimBimPropertyKind.Text, "Часть 🟦"), + new TrimBimProperty("Empty", TrimBimPropertyKind.Text, ""), + new TrimBimProperty("Flag", TrimBimPropertyKind.Boolean, true), + new TrimBimProperty("Count", TrimBimPropertyKind.Integer, -7) { Description = "Signed" }, + new TrimBimProperty("Number", TrimBimPropertyKind.Number, 2.5), + new TrimBimProperty("Length", TrimBimPropertyKind.Length, 1000d), + new TrimBimProperty("Volume", TrimBimPropertyKind.Volume, 3d), + new TrimBimProperty("Mass", TrimBimPropertyKind.Mass, 4d), + new TrimBimProperty("Area", TrimBimPropertyKind.Area, 5d), + new TrimBimProperty("Angle", TrimBimPropertyKind.Angle, 90d), + }, set.Properties); + Assert.Equal("Probe", document.PropertySets[1].Name); + Assert.Empty(document.PropertySets[1].Properties); + } + + [Fact] + public void RejectsAPropertyCountThatWouldReadBeyondTheRecord() + { + byte[] body = Concat(Le32(25), Le32(30), new byte[22], Le32(0), Le32(0), Le32(uint.MaxValue)); + using var file = new MemoryStream(Gzip(Concat(LegacyReferenceRecord(1, body), + LegacyReferencePropertySetRecord(2, 26, "Other")))); + Assert.Contains("Reference cache properties", Assert.Throws( + () => TdbFile.Open(file, "attributes.tsfodat")).Message); + } + [Fact] public void ReadsMaterialNamesByObjectKeyIndependentlyOfObjectLabels() { diff --git a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs index 66df522..a43dcc4 100644 --- a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs +++ b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs @@ -67,6 +67,27 @@ internal static byte[] LegacyReferenceLabelRecord(uint id, uint objectId, string internal static byte[] LegacyReferenceObjectMaterialRecord(uint id, uint objectId, string name) => LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(33), LegacyAttributeText(name), [0], Le32(-1))); + internal static byte[] LegacyReferenceProjectRecord(uint id, string ifcGlobalId) + { + byte[] record = LegacyReferenceObjectRecord(id, ifcGlobalId); + Le32(2).CopyTo(record, 8 + 52); + Le32(91).CopyTo(record, 8 + 56); + return record; + } + + internal static byte[] LegacyReferencePropertySetRecord(uint id, uint objectId, string name, params byte[][] properties) + => LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(30), new byte[22], + LegacyAttributeText(name), Le32(0), Le32(properties.Length), Concat(properties))); + + internal static byte[] LegacyReferenceProperty(string name, uint kind, byte[] value, string description = "") + => Concat(Le32(1), LegacyAttributeText(name), LegacyAttributeText(description), Le32(kind), value); + + internal static byte[] LegacyReferenceTextProperty(string name, string value) + => LegacyReferenceProperty(name, 1, LegacyAttributeText(value)); + + internal static byte[] LegacyReferenceNumberProperty(string name, uint kind, double value) + => LegacyReferenceProperty(name, kind, LegacyDoubles(value)); + 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)