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 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.
- Read older reference cache layer names, material colors and geometry instance placements from `.tsfodat` files.
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`, `definitions.tsfodat`, `textures.tsfodat`) | Legacy reference cache documents | Geometry instances, 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`, `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 |
| `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
4 changes: 4 additions & 0 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,10 @@ private static Command Parse(string[] args)
case LegacyReferenceInstancesDocument instances:
Add("instances", instances.Instances.Count);
break;
case LegacyReferenceObjectsDocument objects:
Add("objects", objects.Objects.Count);
Add("ifcGlobalIds", objects.Objects.Count(item => item.IfcGlobalId is not null));
break;
case LegacyReferenceDefinitionsDocument definitions:
Add("polygonMeshes", definitions.Meshes.Count);
Add("curveSets", definitions.CurveSets.Count);
Expand Down
25 changes: 23 additions & 2 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,17 @@ 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<LegacyReferenceInstancesDocument>("instances.tsfodat").Instances;
var layers = Open<LegacyReferenceLayersDocument>("layers.tsfodat").Layers.ToDictionary(layer => layer.Id);
var identities = ReadObjectIdentities();
var layerProperties = new Dictionary<uint, int>();
var objectIds = new Dictionary<uint, long>();
foreach (var group in instances.GroupBy(instance => instance.ObjectId))
{
string id = group.Key.ToString(CultureInfo.InvariantCulture);
identities.TryGetValue(group.Key, out string? ifcGlobalId);
var element = new SceneElement
{
Id = source.Elements.Count + 1, ModelId = 1, ParentId = 1, SourceId = id,
Kind = SceneNodeKind.Element, Name = $"Object {id}",
Id = source.Elements.Count + 1, ModelId = 1, ParentId = 1, SourceId = ifcGlobalId ?? id,
IfcGuid = ifcGlobalId, Kind = SceneNodeKind.Element, Name = $"Object {id}",
};
foreach (uint layerId in group.Select(instance => instance.LayerId).Distinct())
{
Expand Down Expand Up @@ -157,6 +159,25 @@ T Open<T>(string fileName) where T : TdbDocument
return TdbFile.Open(path) as T ?? throw new InvalidDataException($"Invalid older cache file '{fileName}'.");
}

Dictionary<uint, string?> ReadObjectIdentities()
{
try
{
return Open<LegacyReferenceObjectsDocument>("foreignobjects.tsfodat").Objects
.ToDictionary(item => item.Id, item => item.IfcGlobalId);
}
catch (FileNotFoundException)
{
return [];
}
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 [];
}
}

Dictionary<uint, LegacyReferenceTexture> ReadTextureTable()
{
try
Expand Down
39 changes: 39 additions & 0 deletions src/TdbIO/Internal/Container/LegacyReferenceCacheReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ internal static partial class LegacyReferenceCacheReader
private const int LayerFixedSize = 8;
private const int MaterialSize = 29;
private const int InstanceSize = 120;
private const int ObjectGeometryKeyCountOffset = 60;
private const int ObjectFixedSize = ObjectGeometryKeyCountOffset + sizeof(uint);
private const int IfcIdentitySize = 96;
private const int IdentityTagSize = 3 * sizeof(uint);
private static readonly Encoding LayerEncoding = new UnicodeEncoding(false, false, true);

public static TdbFileKind KindFromName(string? fileName)
Expand All @@ -18,6 +22,7 @@ public static TdbFileKind KindFromName(string? fileName)
if (string.Equals(name, "instances.tsfodat", StringComparison.OrdinalIgnoreCase)) return TdbFileKind.LegacyReferenceInstances;
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;
return TdbFileKind.Unknown;
}

Expand All @@ -34,6 +39,8 @@ public static bool HasRecordHeader(ReadOnlySpan<byte> head, TdbFileKind kind)
TdbFileKind.LegacyReferenceInstances => size == InstanceSize,
TdbFileKind.LegacyReferenceDefinitions => head.Length >= 16 && size >= 8 && Bytes.U32(head, 12) <= size - 8,
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,
_ => false,
};
}
Expand Down Expand Up @@ -82,6 +89,38 @@ public static LegacyReferenceInstancesDocument ReadInstances(byte[] data)
return new LegacyReferenceInstancesDocument(instances.AsReadOnly());
}

public static LegacyReferenceObjectsDocument ReadObjects(byte[] data)
{
var objects = new List<LegacyReferenceObject>();
var ids = new HashSet<uint>();
foreach (var (id, body, size) in ReadRecords(data))
{
if (size < ObjectFixedSize) throw FormatError.At("Invalid reference cache object size", body - 4);
if (!ids.Add(id)) throw FormatError.At("Duplicate reference cache object ID", body - RecordHeaderSize);

int countOffset = body + ObjectGeometryKeyCountOffset;
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)));
}
return new LegacyReferenceObjectsDocument(objects.AsReadOnly());
}

private static string? ReadObjectIfcGlobalId(byte[] data, int identity, int end)
{
if (end - identity < IdentityTagSize || Bytes.U32(data, identity) != IfcIdentitySize
|| Bytes.U32(data, identity + 4) != 2 || Bytes.U32(data, identity + 8) != 0)
return null;

Bytes.Need(identity, IfcIdentitySize, end, "Reference cache IFC identity");
int offset = identity + IdentityTagSize;
var encoded = data.AsSpan(offset, IfcGuid.EncodedLength);
if (!IfcGuid.IsCanonical(encoded) || data[offset + IfcGuid.EncodedLength] != 0)
throw FormatError.At("Invalid reference cache object IFC GlobalId", offset);
return Encoding.ASCII.GetString(encoded);
}

private static IEnumerable<(uint Id, int Body, int Size)> ReadRecords(byte[] data)
{
int offset = 0;
Expand Down
7 changes: 2 additions & 5 deletions src/TdbIO/Internal/Db1ReferenceModelReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,10 @@ internal static IReadOnlyList<Db1ReferenceModelObjectIdentity> ReadObjectIdentit
var body = row.Body.Span;
if (Bytes.I32(body, 12) != 2) return null;

var encoded = body.Slice(20, 22);
var encoded = body.Slice(20, IfcGuid.EncodedLength);
long offset = row.Offset + 21;
if (encoded[0] is < (byte)'0' or > (byte)'3' || Bytes.U16(body, 42) != 0)
if (!IfcGuid.IsCanonical(encoded) || Bytes.U16(body, 42) != 0)
throw FormatError.At("Invalid reference object IFC GlobalId", offset);
foreach (byte digit in encoded)
if (!char.IsAsciiLetterOrDigit((char)digit) && digit is not ((byte)'_' or (byte)'$'))
throw FormatError.At("Invalid reference object IFC GlobalId", offset);

return Encoding.ASCII.GetString(encoded);
}
Expand Down
12 changes: 11 additions & 1 deletion src/TdbIO/Internal/IfcGuid.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ namespace TdbIO.Internal;
internal static class IfcGuid
{
private const string Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$";
public const int EncodedLength = 22;

public static bool IsCanonical(ReadOnlySpan<byte> encoded)
{
if (encoded.Length != EncodedLength || encoded[0] is < (byte)'0' or > (byte)'3') return false;
foreach (byte digit in encoded)
if (!char.IsAsciiLetterOrDigit((char)digit) && digit is not ((byte)'_' or (byte)'$'))
return false;
return true;
}

/// <summary>Convert a .NET Guid to IFC GlobalId (22 chars).</summary>
public static string ToIfcGuid(Guid guid)
Expand All @@ -34,7 +44,7 @@ public static string ToIfcGuid(Guid guid)
for (int i = 0; i < 8; i++) hi = (hi << 8) | u[i];
for (int i = 8; i < 16; i++) lo = (lo << 8) | u[i];

var result = new char[22];
var result = new char[EncodedLength];
// Char 0: top 2 bits (padded to 6)
result[0] = Chars[(int)(hi >> 62) & 0x3F];
// Chars 1-10: next 60 bits from hi
Expand Down
15 changes: 15 additions & 0 deletions src/TdbIO/LegacyReferenceCacheDocuments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,21 @@ internal LegacyReferenceInstancesDocument(IReadOnlyList<LegacyReferenceInstance>
public IReadOnlyList<LegacyReferenceInstance> Instances { get; }
}

/// <summary>The saved foreign objects of an older reference cache, in file order.</summary>
public sealed class LegacyReferenceObjectsDocument : TdbDocument
{
internal LegacyReferenceObjectsDocument(IReadOnlyList<LegacyReferenceObject> objects)
: base(TdbFileKind.LegacyReferenceObjects, []) => Objects = objects;

/// <summary>The object records, identified by their saved keys.</summary>
public IReadOnlyList<LegacyReferenceObject> Objects { get; }
}

/// <summary>A saved foreign object in an older reference cache.</summary>
/// <param name="Id">The key referenced by geometry instances from the same cache.</param>
/// <param name="IfcGlobalId">The saved IFC GlobalId when present in a known identity record, otherwise null.</param>
public readonly record struct LegacyReferenceObject(uint Id, string? IfcGlobalId);

/// <summary>A named layer in an older reference cache.</summary>
/// <param name="Id">The key referenced by geometry instances from the same cache.</param>
/// <param name="Name">The saved layer name.</param>
Expand Down
1 change: 1 addition & 0 deletions src/TdbIO/TdbFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ private static TdbDocument Read(Stream stream, string? fileName, TdbReadOptions
TdbFileKind.LegacyReferenceInstances => LegacyReferenceCacheReader.ReadInstances(payload),
TdbFileKind.LegacyReferenceDefinitions => LegacyReferenceCacheReader.ReadDefinitions(payload),
TdbFileKind.LegacyReferenceTextures => LegacyReferenceCacheReader.ReadTextures(payload),
TdbFileKind.LegacyReferenceObjects => LegacyReferenceCacheReader.ReadObjects(payload),
_ => throw NotRecognised(),
};
}
Expand Down
3 changes: 3 additions & 0 deletions src/TdbIO/TdbFileKind.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,7 @@ public enum TdbFileKind

/// <summary>A gzip-compressed image table named <c>textures.tsfodat</c>.</summary>
LegacyReferenceTextures,

/// <summary>A gzip-compressed reference object table named <c>foreignobjects.tsfodat</c>.</summary>
LegacyReferenceObjects,
}
1 change: 1 addition & 0 deletions tests/TdbIO.Scene.Tests/TdbIO.Scene.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<Compile Include="..\TdbIO.Tests\Synthetic.Tables.cs" Link="Synthetic.Tables.cs" />
<Compile Include="..\TdbIO.Tests\Synthetic.TrimBim.cs" Link="Synthetic.TrimBim.cs" />
<Compile Include="..\TdbIO.Tests\Synthetic.ReferenceScene.cs" Link="Synthetic.ReferenceScene.cs" />
<Compile Include="..\TdbIO.Tests\Synthetic.LegacyReference.cs" Link="Synthetic.LegacyReference.cs" />
</ItemGroup>

<ItemGroup Condition="'$(BuildNativeCoreOnly)' != 'true'">
Expand Down
67 changes: 58 additions & 9 deletions tests/TdbIO.Scene.Tests/TdbSceneReader.ReferenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,21 +85,34 @@ public void ReportsAnInvalidPlacementAndKeepsTheOtherInsertion()
Assert.Equal(2, result.Document.Instances.Count);
}

[Fact]
public void AttachesItsOwnTeklaGuidToEachPlacementOfTheSameIfcObject()
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AttachesItsOwnTeklaGuidToEachPlacementOfTheSameIfcObject(bool legacy)
{
const string ifcId = "0000000000000000000001";
Guid firstGuid = new("cf9bd9a6-e0ab-44a7-8d86-a37902e0bd00");
Guid secondGuid = new("db84100b-7b65-4cf9-84b0-66a2570326d4");
string path = CreateInput(host: Synthetic.ReferenceScenePayload(identities:
string path = CreateInput(writeCurrent: !legacy, host: Synthetic.ReferenceScenePayload(identities:
[(11, firstGuid, ifcId), (12, secondGuid, ifcId)]));
if (legacy) CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, ifcId, 18));
var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true });

Assert.Empty(result.Diagnostics);
Assert.Single(result.Document.Geometries);
var copies = result.Document.Elements.Where(element => element.IfcGuid == ifcId).ToArray();
Assert.Equal(2, copies.Length);
Assert.All(copies, element => Assert.Equal(ifcId, element.SourceId));
if (legacy)
{
var unmatched = result.Document.Elements.Where(element => element.SourceId == "26").ToArray();
Assert.Equal(2, unmatched.Length);
Assert.All(unmatched, element =>
{
Assert.Null(element.IfcGuid);
Assert.Empty(TeklaIds(result.Document, element));
});
}

var firstHost = result.Document.Models.Single(m => m.Key.EndsWith(Synthetic.FirstReferenceGuid.ToString("D"),
StringComparison.Ordinal));
Expand All @@ -126,12 +139,15 @@ public void SkipsAnAmbiguousIdentityWithinOnePlacement()
Assert.Single(TeklaIds(result.Document, copies.Single(element => element.ModelId != firstHost.Id)));
}

[Fact]
public void SkipsIdentityWhenTheCacheContainsTwoObjectsWithTheSameIfcGuid()
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SkipsIdentityWhenTheCacheContainsTwoObjectsWithTheSameIfcGuid(bool legacy)
{
const string ifcId = "0000000000000000000001";
string path = CreateInput(currentCache: Synthetic.TrimBimScenePayload(duplicateIfcGuids: true),
string path = CreateInput(writeCurrent: !legacy, currentCache: Synthetic.TrimBimScenePayload(duplicateIfcGuids: true),
host: Synthetic.ReferenceScenePayload(identities: [(11, Guid.NewGuid(), ifcId)]));
if (legacy) CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, ifcId), Synthetic.LegacyReferenceObjectRecord(26, ifcId));

var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, GenerateGeometry = false });
var firstHost = result.Document.Models[1];
Expand Down Expand Up @@ -159,6 +175,21 @@ public void PreservesLinkedGeometryWhenSavedIdentitiesAreMalformed()
(instance.ElementId, instance.GeometryId, instance.Transform);
}

[Fact]
public void KeepsOlderReferenceGeometryWhenTheObjectTableIsMalformed()
{
string path = CreateInput(writeCurrent: false);
CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, "4000000000000000000001"));

var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true });
var warning = Assert.Single(result.Diagnostics);
Assert.Contains("The older cache object identities could not be read.", warning.Message);
Assert.Contains("IFC GlobalId", warning.Message);
Assert.Single(result.Document.Geometries);
Assert.Equal(4, result.Document.Instances.Count);
Assert.DoesNotContain(result.Document.Elements, element => element.IfcGuid != null);
}

private static IEnumerable<SceneProperty> TeklaIds(SceneDocument scene, SceneElement element) =>
scene.PropertySets.Where(set => element.PropertySetIds.Contains(set.Id))
.SelectMany(set => set.Properties)
Expand Down Expand Up @@ -257,13 +288,16 @@ public void ReportsMissingCurrentCachesWithoutReadingAnEarlierRevision()
Assert.All(result.Diagnostics, d => Assert.Equal("reference-cache", d.Code));
}

[Fact]
public void AssignsAReferenceObjectOnlyToItsSavedInsertion()
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AssignsAReferenceObjectOnlyToItsSavedInsertion(bool legacy)
{
const string ifcId = "0000000000000000000001";
string path = CreateInput(currentCache: Synthetic.TrimBimLabelPayload(),
string path = CreateInput(writeCurrent: !legacy, currentCache: Synthetic.TrimBimLabelPayload(),
host: Synthetic.ReferenceScenePayload(identities: [(11, Guid.NewGuid(), ifcId), (12, Guid.Empty, ifcId)],
additionalSections: TdbSceneReaderTests.ScheduleSections([(201, 301, [102])])));
if (legacy) CreateLegacyCache(Synthetic.LegacyReferenceObjectRecord(25, ifcId));
var result = TdbSceneReader.Read(path, new() { IncludeReferenceModels = true, IncludeTaskSchedule = true });
var scene = result.Document;
var task = Assert.Single(Assert.Single(scene.Schedules).Tasks);
Expand All @@ -280,6 +314,21 @@ public void AssignsAReferenceObjectOnlyToItsSavedInsertion()
Assert.Equal("task-schedule-member", Assert.Single(nativeOnly.Diagnostics).Code);
}

private void CreateLegacyCache(params byte[][] objects)
{
string cache = Path.Combine(_directory, "RefCacheFolders", $"7_{Synthetic.ReferenceSceneHash}");
Directory.CreateDirectory(cache);
WriteTable("definitions.tsfodat", Synthetic.LegacyReferenceMeshRecord(18));
WriteTable("layers.tsfodat", Synthetic.LegacyReferenceLayerRecord(3, "Outline", 1));
WriteTable("materials.tsfodat", Synthetic.LegacyReferenceMaterialRecord(5, [3, 17, 31, 190]));
WriteTable("instances.tsfodat", Synthetic.LegacyReferenceInstanceRecord(18, 5, 3, 25),
Synthetic.LegacyReferenceInstanceRecord(18, 5, 3, 26));
WriteTable("foreignobjects.tsfodat", objects);

void WriteTable(string filename, params byte[][] records) =>
File.WriteAllBytes(Path.Combine(cache, filename), Synthetic.Gzip(Synthetic.Concat(records)));
}

private string CreateInput(bool writeCurrent = true, byte[]? currentCache = null, byte[]? host = null)
{
string path = Path.Combine(_directory, "host.db1");
Expand Down
Loading
Loading