Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ API between minor releases.

### Added

- 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.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ extension and the property fields.
| `.idrm` | `IdRanges` | Next free value, ranges | One field of each range |
| `guid.mapper` | `GuidMapper` | GUID pairs | The header line (raw bytes) |
| TrimBIM caches (`.trb`, TRB8) | `TrimBim` | Source object GUIDs, names, classes, descriptions, placements, relationships and geometry | Original cache bytes |
| Older reference cache tables (`layers.tsfodat`, `materials.tsfodat`, `instances.tsfodat`, `foreignobjects.tsfodat`, `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 |
Expand Down
1 change: 1 addition & 0 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
35 changes: 35 additions & 0 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferenceMeasurements.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using IOScene;

namespace TdbIO.Scene;

public static partial class TdbSceneReader
{
private static readonly Dictionary<TrimBimPropertyKind, TrimBimPropertyUnit> 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<uint, int> objectIndices,
IReadOnlyDictionary<uint, LegacyReferenceGeometryValues> 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);
}
}
}
6 changes: 5 additions & 1 deletion src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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));

Expand Down
28 changes: 27 additions & 1 deletion src/TdbIO/Internal/Container/LegacyReferenceAttributeReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -20,6 +22,7 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data)
{
var labels = new Dictionary<uint, LegacyReferenceObjectLabel>();
var materialNames = new Dictionary<uint, string>();
var calculatedGeometry = new Dictionary<uint, LegacyReferenceGeometryValues>();
var seen = new HashSet<(uint ObjectId, uint Kind)>();
var propertySets = new List<LegacyReferencePropertySet>();
var propertySetIds = new HashSet<uint>();
Expand All @@ -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)))
Expand Down Expand Up @@ -70,7 +80,23 @@ public static LegacyReferenceAttributesDocument ReadAttributes(byte[] data)
labels[objectId] = label;
}
return new LegacyReferenceAttributesDocument(new ReadOnlyDictionary<uint, LegacyReferenceObjectLabel>(labels),
new ReadOnlyDictionary<uint, string>(materialNames), propertySets.AsReadOnly());
new ReadOnlyDictionary<uint, string>(materialNames), propertySets.AsReadOnly(),
new ReadOnlyDictionary<uint, LegacyReferenceGeometryValues>(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)
Expand Down
16 changes: 14 additions & 2 deletions src/TdbIO/LegacyReferenceCacheDocuments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,18 @@ public enum LegacyReferencePortRelationKind
PortConnection,
}

/// <summary>The saved object labels, material names and property sets from a legacy reference attribute table.</summary>
/// <summary>The saved object metadata, property sets and calculated geometry from a legacy reference attribute table.</summary>
public sealed class LegacyReferenceAttributesDocument : TdbDocument
{
internal LegacyReferenceAttributesDocument(IReadOnlyDictionary<uint, LegacyReferenceObjectLabel> labels,
IReadOnlyDictionary<uint, string> materialNames, IReadOnlyList<LegacyReferencePropertySet> propertySets)
IReadOnlyDictionary<uint, string> materialNames, IReadOnlyList<LegacyReferencePropertySet> propertySets,
IReadOnlyDictionary<uint, LegacyReferenceGeometryValues> calculatedGeometryValues)
: base(TdbFileKind.LegacyReferenceAttributes, [])
{
Labels = labels;
MaterialNames = materialNames;
PropertySets = propertySets;
CalculatedGeometryValues = calculatedGeometryValues;
}

/// <summary>Labels by saved foreign object key. Full metadata takes precedence over name-only attributes.</summary>
Expand All @@ -126,6 +128,9 @@ internal LegacyReferenceAttributesDocument(IReadOnlyDictionary<uint, LegacyRefer
/// <summary>Saved property sets in file order, including empty sets and sets with repeated names.</summary>
public IReadOnlyList<LegacyReferencePropertySet> PropertySets { get; }

/// <summary>Geometry measurements written by the importer, keyed by foreign object.</summary>
public IReadOnlyDictionary<uint, LegacyReferenceGeometryValues> CalculatedGeometryValues { get; }

/// <summary>Reads declared property units for the single IFC project in the same reference cache.</summary>
public IEnumerable<TrimBimPropertyUnit> ReadPropertyUnits(LegacyReferenceObjectsDocument objects)
{
Expand All @@ -146,6 +151,13 @@ public IEnumerable<TrimBimPropertyUnit> ReadPropertyUnits(LegacyReferenceObjects
public sealed record LegacyReferencePropertySet(uint Id, uint ObjectId, string Name, string? Description,
IReadOnlyList<TrimBimProperty> Properties);

/// <summary>The stored CalculatedGeometryValues fields for an object in an older reference cache.</summary>
/// <param name="Volume">The stored volume in cubic metres.</param>
/// <param name="Area">The stored surface area in square metres.</param>
/// <param name="CenterOfGravity">The stored center in cache coordinates, in millimetres.</param>
/// <param name="IsSolid">The importer's saved solid classification.</param>
public readonly record struct LegacyReferenceGeometryValues(double Volume, double Area, ModelVector3D CenterOfGravity, bool IsSolid);

/// <summary>The saved descriptive fields of a foreign object in an older reference cache.</summary>
/// <param name="Name">The saved object name, when present.</param>
/// <param name="Description">The saved object description, when present.</param>
Expand Down
31 changes: 31 additions & 0 deletions tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SceneProperty> TeklaIds(SceneDocument scene, SceneElement element) =>
scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id))
.SelectMany(set => set.Properties)
Expand Down
6 changes: 4 additions & 2 deletions tests/TdbIO.Tests/CliTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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]
Expand Down
28 changes: 28 additions & 0 deletions tests/TdbIO.Tests/LegacyReferenceCacheTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,34 @@ public void ReadsStoredHierarchyKeysEndpointsAndRawCodesInFileOrder()
Assert.Empty(Assert.IsType<LegacyReferenceHierarchyDocument>(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<LegacyReferenceAttributesDocument>(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<InvalidDataException>(() => TdbFile.Open(stream, "attributes.tsfodat")).Message);
}
}

[Fact]
public void ReadsPortRelationsInIfcOrderAndKeepsUnresolvedRecords()
{
Expand Down
4 changes: 4 additions & 0 deletions tests/TdbIO.Tests/Synthetic.LegacyReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
Loading