diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d4e392..9bdd28e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ API between minor releases. ### Added +- Read stored surface area, volume, center of gravity and solid status from older reference caches and export them with scene properties. - Read IFC distribution port attachments and connections from older reference caches and show them in scene properties. - Restore recognized IFC classes, storey elevations and spatial containment in scenes from older reference caches. - Read saved property sets from older reference caches and export typed values using the IFC project's declared units. diff --git a/README.md b/README.md index fcbdb30..9135ab9 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, recognized IFC classes and storeys, object relationships including distribution port connections, labels, materials and property sets, 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, recognized IFC classes and storeys, object relationships including distribution port connections, labels, materials, property sets and stored geometry measurements, 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 9e65ca7..1fc504e 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -540,6 +540,7 @@ private static Command Parse(string[] args) Add("objectLabels", attributes.Labels.Count); Add("materialNames", attributes.MaterialNames.Count); Add("propertySets", attributes.PropertySets.Count); + Add("calculatedGeometryValues", attributes.CalculatedGeometryValues.Count); break; case LegacyReferenceDefinitionsDocument definitions: Add("polygonMeshes", definitions.Meshes.Count); diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferenceMeasurements.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferenceMeasurements.cs new file mode 100644 index 0000000..6cfaddb --- /dev/null +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferenceMeasurements.cs @@ -0,0 +1,35 @@ +using IOScene; + +namespace TdbIO.Scene; + +public static partial class TdbSceneReader +{ + private static readonly Dictionary LegacyCalculatedGeometryUnits = new() + { + [TrimBimPropertyKind.Volume] = new(TrimBimPropertyKind.Volume, "CUBIC_METRE", 1, 1), + [TrimBimPropertyKind.Area] = new(TrimBimPropertyKind.Area, "SQUARE_METRE", 1, 1), + [TrimBimPropertyKind.Length] = new(TrimBimPropertyKind.Length, "MILLIMETRE", 1, 0.001), + }; + + private static void AddLegacyCalculatedGeometry(SceneDocument scene, Dictionary objectIndices, + IReadOnlyDictionary geometry) + { + foreach (var (objectId, measurements) in geometry) + { + if (!objectIndices.TryGetValue(objectId, out int index)) continue; + var center = measurements.CenterOfGravity; + TrimBimProperty[] properties = + [ + new("Volume", TrimBimPropertyKind.Volume, measurements.Volume), + new("Area", TrimBimPropertyKind.Area, measurements.Area), + new("CenterOfGravityX", TrimBimPropertyKind.Length, center.X), + new("CenterOfGravityY", TrimBimPropertyKind.Length, center.Y), + new("CenterOfGravityZ", TrimBimPropertyKind.Length, center.Z), + new("IsSolid", TrimBimPropertyKind.Boolean, measurements.IsSolid), + ]; + if (TrimBimSceneReader.AddSavedPropertySet(scene, "CalculatedGeometryValues", properties, + LegacyCalculatedGeometryUnits) is int setId) + scene.Elements[index + 1].PropertySetIds.Add(setId); + } + } +} diff --git a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs index 8e31e49..095c9f0 100644 --- a/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs +++ b/src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs @@ -61,10 +61,12 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n // Keep instance objects in their original order, then add non-geometric objects with saved metadata. var propertySets = attributes?.PropertySets ?? []; + var calculatedGeometry = attributes?.CalculatedGeometryValues; uint[] objectKeys = instances.Select(instance => instance.ObjectId) .Union(usableRelations.SelectMany(relation => new[] { relation.ParentObjectId, relation.ChildObjectId })) .Union(propertySets.Where(set => HasObject(set.ObjectId)).Select(set => set.ObjectId)) - .Union(objects.Values.Where(item => item.IfcTypeName != null).Select(item => item.Id)).ToArray(); + .Union(objects.Values.Where(item => item.IfcTypeName != null).Select(item => item.Id)) + .Union(calculatedGeometry?.Keys.Where(HasObject) ?? []).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(); @@ -123,6 +125,8 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n TrimBimSceneReader.AddSavedPropertySet(source, set.Name, set.Properties, units) is int setId) source.Elements[index + 1].PropertySetIds.Add(setId); } + if (calculatedGeometry != null) + AddLegacyCalculatedGeometry(source, objectIndices, calculatedGeometry); if (foreignObjects != null && hierarchy != null) AddLegacyPortRelations(source, objectIndices, hierarchy.ReadPortRelations(foreignObjects)); diff --git a/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs b/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs index b693895..c26c276 100644 --- a/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs +++ b/src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs @@ -11,6 +11,8 @@ internal static partial class LegacyReferenceCacheReader private const int MinimumScalarPropertySize = 17; private const uint ObjectMetadataAttribute = 31; private const uint ObjectMaterialAttribute = 33; + private const uint CalculatedGeometryAttribute = 39; + private const int CalculatedGeometryValueSize = 5 * sizeof(double) + sizeof(byte); private const int ObjectMaterialTailSize = 5; private const int ObjectNameTailSize = 96; private const int ObjectHistoryTextCount = 13; @@ -20,6 +22,7 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data) { var labels = new Dictionary(); var materialNames = new Dictionary(); + var calculatedGeometry = new Dictionary(); var seen = new HashSet<(uint ObjectId, uint Kind)>(); var propertySets = new List(); var propertySetIds = new HashSet(); @@ -34,6 +37,13 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data) propertySets.Add(ReadPropertySet(data, id, objectId, body + AttributeHeaderSize, body + size)); continue; } + if (kind == CalculatedGeometryAttribute) + { + var values = ReadCalculatedGeometry(data, body + AttributeHeaderSize, size - AttributeHeaderSize); + if (!calculatedGeometry.TryAdd(objectId, values)) + throw FormatError.At("Duplicate reference cache calculated geometry attribute", body); + continue; + } if (kind is not (ObjectNameAttribute or ObjectMetadataAttribute or ObjectMaterialAttribute)) continue; if (!seen.Add((objectId, kind))) @@ -70,7 +80,23 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data) labels[objectId] = label; } return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary(labels), - new ReadOnlyDictionary(materialNames), propertySets.AsReadOnly()); + new ReadOnlyDictionary(materialNames), propertySets.AsReadOnly(), + new ReadOnlyDictionary(calculatedGeometry)); + } + + private static LegacyReferenceGeometryValues ReadCalculatedGeometry(byte[] data, int offset, int size) + { + if (size != CalculatedGeometryValueSize) + throw FormatError.At("Invalid reference cache calculated geometry attribute length", offset); + double volume = Bytes.F64(data, offset); + double area = Bytes.F64(data, offset + sizeof(double)); + if (!double.IsFinite(volume) || !double.IsFinite(area)) + throw FormatError.At("Non-finite reference cache geometry measurement", offset); + var center = ReadVector(data, offset + 2 * sizeof(double)); + int flagOffset = offset + 5 * sizeof(double); + byte flag = data[flagOffset]; + if (flag > 1) throw FormatError.At("Invalid reference cache solid flag", flagOffset); + return new LegacyReferenceGeometryValues(volume, area, center, flag == 1); } private static LegacyReferencePropertySet ReadPropertySet(byte[] data, uint id, uint objectId, int offset, int end) diff --git a/src/TdbIO/LegacyReferenceCacheDocuments.cs b/src/TdbIO/LegacyReferenceCacheDocuments.cs index 51a1cfd..6e60fe4 100644 --- a/src/TdbIO/LegacyReferenceCacheDocuments.cs +++ b/src/TdbIO/LegacyReferenceCacheDocuments.cs @@ -105,16 +105,18 @@ public enum LegacyReferencePortRelationKind PortConnection, } -/// The saved object labels, material names and property sets from a legacy reference attribute table. +/// The saved object metadata, property sets and calculated geometry from a legacy reference attribute table. public sealed class LegacyReferenceAttributesDocument : TdbDocument { internal LegacyReferenceAttributesDocument(IReadOnlyDictionary labels, - IReadOnlyDictionary materialNames, IReadOnlyList propertySets) + IReadOnlyDictionary materialNames, IReadOnlyList propertySets, + IReadOnlyDictionary calculatedGeometryValues) : base(TdbFileKind.LegacyReferenceAttributes, []) { Labels = labels; MaterialNames = materialNames; PropertySets = propertySets; + CalculatedGeometryValues = calculatedGeometryValues; } /// Labels by saved foreign object key. Full metadata takes precedence over name-only attributes. @@ -126,6 +128,9 @@ internal LegacyReferenceAttributesDocument(IReadOnlyDictionarySaved property sets in file order, including empty sets and sets with repeated names. public IReadOnlyList PropertySets { get; } + /// Geometry measurements written by the importer, keyed by foreign object. + public IReadOnlyDictionary CalculatedGeometryValues { get; } + /// Reads declared property units for the single IFC project in the same reference cache. public IEnumerable ReadPropertyUnits(LegacyReferenceObjectsDocument objects) { @@ -146,6 +151,13 @@ public IEnumerable ReadPropertyUnits(LegacyReferenceObjects public sealed record LegacyReferencePropertySet(uint Id, uint ObjectId, string Name, string? Description, IReadOnlyList Properties); +/// The stored CalculatedGeometryValues fields for an object in an older reference cache. +/// The stored volume in cubic metres. +/// The stored surface area in square metres. +/// The stored center in cache coordinates, in millimetres. +/// The importer's saved solid classification. +public readonly record struct LegacyReferenceGeometryValues(double Volume, double Area, ModelVector3D CenterOfGravity, bool IsSolid); + /// 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. diff --git a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs index 7bfcd9e..250ae99 100644 --- a/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs +++ b/tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs @@ -364,6 +364,37 @@ public void KeepsOlderReferenceGeometryWhenTheAttributeTableIsMalformed() Assert.Equal(2, result.Document.Elements.Count(element => element.Name == "Object 25")); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ExposesLegacyCalculatedGeometryInSourceUnitsConvertedToSi(bool generateGeometry) + { + const string guid = "0000000000000000000027"; + string path = CreateInput(writeCurrent: false); + string cache = CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(27, guid)); + WriteLegacyAttributes(cache, + Synthetic.LegacyReferenceCalculatedGeometryRecord(1, 27, 0.125, 2.5, -1500, 250, 0, 0), + Synthetic.LegacyReferenceCalculatedGeometryRecord(2, 35, 100, 100, 0, 0, 0, 1)); + + var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = generateGeometry }); + Assert.Empty(result.Diagnostics); + var scene = result.Document; + var set = Assert.Single(scene.PropertySets, item => item.Name == "CalculatedGeometryValues"); + var elements = scene.Elements.Where(element => element.IfcGuid == guid).ToArray(); + Assert.Equal(2, elements.Length); + Assert.All(elements, element => Assert.Contains(set.Id, element.PropertySetIds)); + Assert.Equal(new[] + { + SceneValue.FromNumber(0.125, SceneUnits.CubicMetre, "0.125 m3"), + SceneValue.FromNumber(2.5, SceneUnits.SquareMetre, "2.5 m2"), + SceneValue.FromNumber(-1.5, SceneUnits.Metre, "-1.5 m"), + SceneValue.FromNumber(0.25, SceneUnits.Metre, "0.25 m"), + SceneValue.FromNumber(0, SceneUnits.Metre, "0 m"), + SceneValue.FromBoolean(false, "False"), + }, set.Properties.Select(property => property.Value)); + Assert.DoesNotContain(scene.Elements, element => element.SourceId == "35"); + } + private static IEnumerable TeklaIds(SceneDocument scene, SceneElement element) => scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id)) .SelectMany(set => set.Properties) diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index 695d2cb..e732bc9 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -106,12 +106,13 @@ public void InfoCountsOlderReferenceRelationships() } [Fact] - public void InfoCountsOlderReferenceObjectLabelsAndMaterialNames() + public void InfoCountsOlderReferenceObjectAttributes() { 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"), - LegacyReferencePropertySetRecord(5, 25, "Properties")))); + LegacyReferencePropertySetRecord(5, 25, "Properties"), + LegacyReferenceCalculatedGeometryRecord(6, 25, 3, 10, 1250, 0, 0, 1)))); var (exit, stdout, stderr) = Run("info", file, "--json"); Assert.Equal(Cli.ExitOk, exit); Assert.Empty(stderr); @@ -120,6 +121,7 @@ public void InfoCountsOlderReferenceObjectLabelsAndMaterialNames() Assert.Equal(1, json.RootElement.GetProperty("objectLabels").GetInt32()); Assert.Equal(2, json.RootElement.GetProperty("materialNames").GetInt32()); Assert.Equal(1, json.RootElement.GetProperty("propertySets").GetInt32()); + Assert.Equal(1, json.RootElement.GetProperty("calculatedGeometryValues").GetInt32()); } [Fact] diff --git a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs index 98f1842..431692e 100644 --- a/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs +++ b/tests/TdbIO.Tests/LegacyReferenceCacheTests.cs @@ -113,6 +113,34 @@ public void ReadsStoredHierarchyKeysEndpointsAndRawCodesInFileOrder() Assert.Empty(Assert.IsType(TdbFile.Open(empty, "hierarchy.tsfodat")).Relations); } + [Fact] + public void ReadsCalculatedGeometryValuesByTheirObjectKeys() + { + using var file = new MemoryStream(Gzip(Concat( + LegacyReferenceCalculatedGeometryRecord(2, 25, 1.25, 12, -1500, 2000, 42, 1), + LegacyReferenceCalculatedGeometryRecord(1, 18, 0.0625, 0.5, 0, -750, 125, 0)))); + var document = Assert.IsType(TdbFile.Open(file, "attributes.tsfodat")); + Assert.Equal(new LegacyReferenceGeometryValues(1.25, 12, new(-1500, 2000, 42), true), document.CalculatedGeometryValues[25]); + Assert.Equal(new LegacyReferenceGeometryValues(0.0625, 0.5, new(0, -750, 125), false), document.CalculatedGeometryValues[18]); + } + + [Fact] + public void RejectsMalformedCalculatedGeometry() + { + byte[] valid = LegacyReferenceCalculatedGeometryRecord(1, 25, 0, 1, 0, 0, 0, 0); + OpenFails(LegacyReferenceRecord(1, valid[8..^1]), "attribute length"); + OpenFails(LegacyReferenceCalculatedGeometryRecord(1, 25, double.NaN, 1, 0, 0, 0, 0), "geometry measurement"); + OpenFails(LegacyReferenceCalculatedGeometryRecord(1, 25, 0, 1, 0, double.PositiveInfinity, 0, 0), "coordinate"); + OpenFails(LegacyReferenceCalculatedGeometryRecord(1, 25, 0, 1, 0, 0, 0, 2), "solid flag"); + OpenFails(Concat(valid, LegacyReferenceCalculatedGeometryRecord(2, 25, 0, 1, 0, 0, 0, 0)), "Duplicate"); + + static void OpenFails(byte[] bytes, string reason) + { + using var stream = new MemoryStream(Gzip(bytes)); + Assert.Contains(reason, Assert.Throws(() => TdbFile.Open(stream, "attributes.tsfodat")).Message); + } + } + [Fact] public void ReadsPortRelationsInIfcOrderAndKeepsUnresolvedRecords() { diff --git a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs index 5d94691..4bc3381 100644 --- a/tests/TdbIO.Tests/Synthetic.LegacyReference.cs +++ b/tests/TdbIO.Tests/Synthetic.LegacyReference.cs @@ -67,6 +67,10 @@ 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[] LegacyReferenceCalculatedGeometryRecord(uint id, uint objectId, double volume, double area, + double x, double y, double z, byte isSolid) + => LegacyReferenceRecord(id, Concat(Le32(objectId), Le32(39), LegacyDoubles(volume, area, x, y, z), [isSolid])); + internal static byte[] LegacyReferenceProjectRecord(uint id, string ifcGlobalId) => LegacyTypedReferenceObjectRecord(id, ifcGlobalId, 91);