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 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.
- Read named TrimBIM layers on polygon mesh and curve set instances and list stored layer names in `tdbio info`.
Expand Down
10 changes: 7 additions & 3 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -818,16 +818,20 @@ and lists the layer names for a layer table.
`LegacyReferenceDefinitionsDocument.Meshes` returns stored polygon meshes
with 32-bit vertex indices, including hole contours and their outer contour
indices. Mesh vertices and normal vectors are read as saved doubles. UVs
are float pairs. `UnsupportedDefinitionCount` counts unhandled geometry
definitions. A material's `TextureId` identifies the encoded image in
are float pairs. `CurveSets` exposes saved lines, points and circular arcs
in double precision, including the envelope radius when stored. The scene
adapter renders curve-only definitions. It reports omitted geometry for
definitions whose body is unsupported. `UnsupportedDefinitionCount`
counts unhandled definitions in the native reader.
A material's `TextureId` identifies the encoded image in
`LegacyReferenceTexturesDocument`.

With reference exports enabled, the scene reader uses an older reference
cache when the current TRB8 file is absent. It looks in `RefCacheFolders`
under the model directory and then its parent. A cache directory name has
a numeric prefix followed by an underscore and the current revision hash.
The reader requires a unique match in the selected location. It preserves
mesh instances, transforms, colors, layer names and supported images.
mesh and curve instances, transforms, colors, layer names and supported images.
Scene diagnostics report omitted geometry. `TdbSceneResult.ReferenceCacheFiles`
lists the cache paths consulted during conversion.

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 @@ -529,6 +529,7 @@ private static Command Parse(string[] args)
break;
case LegacyReferenceDefinitionsDocument definitions:
Add("polygonMeshes", definitions.Meshes.Count);
Add("curveSets", definitions.CurveSets.Count);
Add("unsupportedDefinitions", definitions.UnsupportedDefinitionCount);
break;
case LegacyReferenceTexturesDocument textures:
Expand Down
26 changes: 19 additions & 7 deletions src/TdbIO.Scene/TdbSceneReader.LegacyReferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
.ToDictionary(material => material.Id);
var textures = new Dictionary<uint, int?>();
var textureTable = new Lazy<Dictionary<uint, LegacyReferenceTexture>>(ReadTextureTable);
var geometries = new Dictionary<uint, int>();
var geometries = new Dictionary<uint, (int? Mesh, int? Lines, int? Points)>();
int skippedFaces = 0;
foreach (var mesh in definitions.Meshes)
{
Expand All @@ -82,17 +82,24 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
skippedFaces += skipped;
if (indices.Count == 0) continue;
int id = source.Geometries.Count + 1;
geometries.Add(mesh.Id, id);
geometries.Add(mesh.Id, (id, null, null));
source.Geometries.Add(new SceneGeometry
{
Id = id, Topology = SceneTopology.Triangles, Vertices = vertices, Indices = indices, Normals = normals,
UVs = mesh.TextureCoordinates?.Select(uv => new Vector2d(uv.U, uv.V)).ToArray(),
});
}
foreach (var curves in definitions.CurveSets)
{
if (curves.EnvelopeRadius != null) continue;
var arcs = curves.Arcs.Select(arc => (arc.Center, arc.Normal, arc.StartDirection, arc.Radius, arc.SweepRadians));
var (lines, points) = TrimBimSceneReader.AddCurveGeometry(source, curves.Segments, arcs, metresPerUnit: 1);
if (lines != null || points != null) geometries.Add(curves.Id, (null, lines, points));
}
int skippedInstances = 0;
foreach (var instance in instances)
{
if (!geometries.TryGetValue(instance.DefinitionId, out int geometry))
if (!geometries.TryGetValue(instance.DefinitionId, out var geometry))
{
skippedInstances++;
continue;
Expand All @@ -102,18 +109,23 @@ private static TrimBimSceneResult ReadLegacyReference(string directory, string n
var rgba = material.Color;
var transform = new Transform3d(ToSceneVector(instance.AxisX), ToSceneVector(instance.AxisY),
ToSceneVector(instance.AxisZ), ToSceneVector(instance.Origin));
source.Instances.Add(new SceneInstance
if (geometry.Mesh is int mesh)
AddInstance(mesh, material.TextureId is uint texture ? AddLegacyTexture(texture) : null);
if (geometry.Lines is int lines) AddInstance(lines, null);
if (geometry.Points is int points) AddInstance(points, null);

void AddInstance(int id, int? materialId) => source.Instances.Add(new SceneInstance
{
ElementId = objectIds[instance.ObjectId], GeometryId = geometry,
ElementId = objectIds[instance.ObjectId], GeometryId = id,
Color = new RgbaColor(rgba.Red, rgba.Green, rgba.Blue, rgba.Alpha),
Transform = transform == Transform3d.Identity ? null : transform,
MaterialId = material.TextureId is uint texture ? AddLegacyTexture(texture) : null,
MaterialId = materialId,
});
}
if (skippedInstances > 0 || skippedFaces > 0)
diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "legacy-reference-incomplete",
string.Create(CultureInfo.InvariantCulture,
$"The older cache omitted {skippedInstances} instances with no supported mesh and {skippedFaces} faces that could not be triangulated.")));
$"The older cache omitted {skippedInstances} instances without supported renderable geometry and {skippedFaces} faces that could not be triangulated.")));

int? AddLegacyTexture(uint textureId)
{
Expand Down
62 changes: 35 additions & 27 deletions src/TdbIO.Scene/TrimBimSceneReader.Curves.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,11 @@ public static partial class TrimBimSceneReader
private static void AddCurves(SceneDocument scene, TrimBimDocument document,
TrimBimObjectPlacement[] placements, double metresPerUnit)
{
int nextId = (scene.Geometries.LastOrDefault()?.Id ?? 0) + 1;
var ids = new Dictionary<int, (int? Lines, int? Points)>();
foreach (var curves in document.ReadCurveSets())
{
var lines = new List<Vector3d>();
var points = new List<Vector3d>();
foreach (var segment in curves.Segments)
{
Vector3d p = Vector(segment.Start) * metresPerUnit;
if (segment.Start == segment.End) points.Add(p);
else
{
lines.Add(p);
lines.Add(Vector(segment.End) * metresPerUnit);
}
}
foreach (var arc in curves.Arcs)
AddArc(arc, metresPerUnit, lines, points);

ids.Add(curves.CurveSetIndex, (AddGeometry(SceneTopology.Lines, lines), AddGeometry(SceneTopology.Points, points)));
}
ids.Add(curves.CurveSetIndex, AddCurveGeometry(scene, curves.Segments,
curves.Arcs.Select(arc => (arc.Center, arc.Normal, arc.StartDirection,
(double)arc.Radius, (double)arc.SweepRadians)), metresPerUnit));

foreach (var instance in document.ReadCurveSetInstances())
{
Expand All @@ -36,20 +20,44 @@ private static void AddCurves(SceneDocument scene, TrimBimDocument document,
if (points is int pointId) AddInstance(pointId, instance);
}

void AddInstance(int id, TrimBimCurveSetInstance instance)
=> scene.Instances.Add(CreateInstance(id, placements[instance.ObjectIndex], instance.Origin,
instance.AxisX, instance.AxisY, instance.Color, metresPerUnit));
}

internal static (int? Lines, int? Points) AddCurveGeometry(SceneDocument scene, IEnumerable<TrimBimLineSegment> segments,
IEnumerable<(ModelVector3D Center, ModelVector3D Normal, ModelVector3D StartDirection, double Radius, double SweepRadians)> arcs,
double metresPerUnit)
{
var lines = new List<Vector3d>();
var points = new List<Vector3d>();
foreach (var segment in segments)
{
Vector3d p = Vector(segment.Start) * metresPerUnit;
if (segment.Start == segment.End) points.Add(p);
else
{
lines.Add(p);
lines.Add(Vector(segment.End) * metresPerUnit);
}
}
foreach (var arc in arcs)
AddArc(arc, metresPerUnit, lines, points);

return (AddGeometry(SceneTopology.Lines, lines), AddGeometry(SceneTopology.Points, points));

int? AddGeometry(SceneTopology topology, List<Vector3d> vertices)
{
if (vertices.Count == 0) return null;
int id = nextId++;
int id = (scene.Geometries.LastOrDefault()?.Id ?? 0) + 1;
scene.Geometries.Add(new SceneGeometry { Id = id, Topology = topology, Vertices = vertices });
return id;
}

void AddInstance(int id, TrimBimCurveSetInstance instance)
=> scene.Instances.Add(CreateInstance(id, placements[instance.ObjectIndex], instance.Origin,
instance.AxisX, instance.AxisY, instance.Color, metresPerUnit));
}

private static void AddArc(TrimBimCircularArc arc, double metresPerUnit, List<Vector3d> lines, List<Vector3d> points)
private static void AddArc(
(ModelVector3D Center, ModelVector3D Normal, ModelVector3D StartDirection, double Radius, double SweepRadians) arc,
double metresPerUnit, List<Vector3d> lines, List<Vector3d> points)
{
Vector3d center = Vector(arc.Center) * metresPerUnit;
Vector3d axisX = Vector(arc.StartDirection) * (arc.Radius * metresPerUnit);
Expand All @@ -64,11 +72,11 @@ private static void AddArc(TrimBimCircularArc arc, double metresPerUnit, List<Ve
const double maxStep = Math.PI / 36;
const int maxSegments = 720;
int segments = (int)Math.Clamp(Math.Ceiling(Math.Abs(arc.SweepRadians) / maxStep), 1, maxSegments);
bool closed = MathF.Abs(arc.SweepRadians) == MathF.Tau;
bool closed = Math.Abs(arc.SweepRadians) is Math.Tau or MathF.Tau;
Vector3d previous = start;
for (int i = 1; i <= segments; i++)
{
var (sin, cos) = Math.SinCos((double)arc.SweepRadians * i / segments);
var (sin, cos) = Math.SinCos(arc.SweepRadians * i / segments);
Vector3d end = closed && i == segments ? start : center + axisX * cos + axisY * sin;
lines.Add(previous);
lines.Add(end);
Expand Down
67 changes: 67 additions & 0 deletions src/TdbIO/Internal/Container/LegacyReferenceCurveReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
namespace TdbIO.Internal;

internal static partial class LegacyReferenceCacheReader
{
private static LegacyReferenceCurveSet? ReadCurveSet(byte[] data, uint id, bool hasEnvelope, int body, int end, uint size)
{
if (size != end - body - 8)
throw FormatError.At("Invalid reference curve definition length", body + 4);
int tail = end - (hasEnvelope ? sizeof(double) : sizeof(uint));
int offset = body + 8;
Bytes.Need(offset, sizeof(uint), tail, "Reference curve group count");
uint groupCount = Bytes.U32(data, offset);
offset += sizeof(uint);
var segments = new List<TrimBimLineSegment>();
var arcs = new List<LegacyReferenceCircularArc>();
for (int group = 0; group < groupCount; group++)
{
if (hasEnvelope)
{
Bytes.Need(offset, sizeof(uint), tail, "Reference curve group type");
if (Bytes.U32(data, offset) != 1) return null;
offset += sizeof(uint);
}
Bytes.Need(offset, sizeof(uint), tail, "Reference curve group length");
uint length = Bytes.U32(data, offset);
offset += sizeof(uint);
Bytes.Need(offset, length, tail, "Reference curve group");
int groupEnd = offset + (int)length;
while (offset < groupEnd)
{
Bytes.Need(offset, 8, groupEnd, "Reference curve primitive header");
uint kind = Bytes.U32(data, offset), width = Bytes.U32(data, offset + 4);
offset += 8;
Bytes.Need(offset, width, groupEnd, "Reference curve primitive");
switch (kind)
{
case 2:
if (width != 48) throw FormatError.At("Invalid reference curve segment length", offset - 4);
segments.Add(new TrimBimLineSegment(ReadVector(data, offset), ReadVector(data, offset + 24)));
break;
case 4:
if (width != 88) throw FormatError.At("Invalid reference circular arc length", offset - 4);
double radius = Bytes.F64(data, offset + 24), sweep = Bytes.F64(data, offset + 80);
if (!double.IsFinite(radius) || radius < 0)
throw FormatError.At("Invalid reference circular arc radius", offset + 24);
if (!double.IsFinite(sweep))
throw FormatError.At("Invalid reference circular arc sweep", offset + 80);
arcs.Add(new LegacyReferenceCircularArc(ReadVector(data, offset), ReadVector(data, offset + 32),
ReadVector(data, offset + 56), radius, sweep));
break;
default:
return null;
}
offset += (int)width;
}
}
if (offset != tail) throw FormatError.At("Extra data in reference curve groups", offset);
if (!hasEnvelope && Bytes.U32(data, tail) != 0) return null;
var set = new LegacyReferenceCurveSet(id, segments.AsReadOnly(), arcs.AsReadOnly());
if (!hasEnvelope) return set;

double envelopeRadius = Bytes.F64(data, tail);
if (!double.IsFinite(envelopeRadius) || envelopeRadius < 0)
throw FormatError.At("Invalid reference curve envelope radius", tail);
return set with { EnvelopeRadius = envelopeRadius };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ internal static partial class LegacyReferenceCacheReader
public static LegacyReferenceDefinitionsDocument ReadDefinitions(byte[] data)
{
var meshes = new List<LegacyReferenceMesh>();
var curves = new List<LegacyReferenceCurveSet>();
var ids = new HashSet<uint>();
int unsupported = 0;
foreach (var (id, body, size) in ReadRecords(data))
Expand All @@ -14,9 +15,11 @@ public static LegacyReferenceDefinitionsDocument ReadDefinitions(byte[] data)
uint type = Bytes.U32(data, body), baseSize = Bytes.U32(data, body + 4);
if (baseSize > size - 8) throw FormatError.At("Invalid reference geometry definition length", body + 4);
if (type is 1 or 4 or 5) meshes.Add(ReadMesh(data, id, type, body, body + 8 + (int)baseSize, body + size));
else if (type is 2 or 3 && ReadCurveSet(data, id, type == 3, body, body + size, baseSize) is { } curveSet)
curves.Add(curveSet);
else unsupported++;
}
return new LegacyReferenceDefinitionsDocument(meshes.AsReadOnly(), unsupported);
return new LegacyReferenceDefinitionsDocument(meshes.AsReadOnly(), curves.AsReadOnly(), unsupported);
}

public static LegacyReferenceTexturesDocument ReadTextures(byte[] data)
Expand Down
27 changes: 26 additions & 1 deletion src/TdbIO/LegacyReferenceGeometry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@ namespace TdbIO;
/// <summary>The supported geometry definitions in an older reference cache.</summary>
public sealed class LegacyReferenceDefinitionsDocument : TdbDocument
{
internal LegacyReferenceDefinitionsDocument(IReadOnlyList<LegacyReferenceMesh> meshes, int unsupportedDefinitionCount)
internal LegacyReferenceDefinitionsDocument(IReadOnlyList<LegacyReferenceMesh> meshes,
IReadOnlyList<LegacyReferenceCurveSet> curveSets, int unsupportedDefinitionCount)
: base(TdbFileKind.LegacyReferenceDefinitions, [])
{
Meshes = meshes;
CurveSets = curveSets;
UnsupportedDefinitionCount = unsupportedDefinitionCount;
}

/// <summary>The saved polygon meshes, in file order.</summary>
public IReadOnlyList<LegacyReferenceMesh> Meshes { get; }

/// <summary>The saved sets of line segments and circular arcs, in file order.</summary>
public IReadOnlyList<LegacyReferenceCurveSet> CurveSets { get; }

/// <summary>The number of saved definitions with an unsupported geometry type.</summary>
public int UnsupportedDefinitionCount { get; }
}
Expand All @@ -36,6 +41,26 @@ public readonly record struct LegacyReferenceMesh(uint Id, IReadOnlyList<ModelVe
/// <param name="OuterContourIndex">The zero-based outer contour index for a hole, or null for an outer contour.</param>
public readonly record struct LegacyReferencePolygon(IReadOnlyList<int> VertexIndices, int? OuterContourIndex);

/// <summary>A saved set of analytic curves in an older reference cache.</summary>
/// <param name="Id">The geometry definition key referenced by instances in the same cache.</param>
/// <param name="Segments">The saved line segments, including points with coincident endpoints.</param>
/// <param name="Arcs">The saved circular arcs.</param>
public readonly record struct LegacyReferenceCurveSet(uint Id, IReadOnlyList<TrimBimLineSegment> Segments,
IReadOnlyList<LegacyReferenceCircularArc> Arcs)
{
/// <summary>The saved radius that expands the bounds of a radius-bearing path, or null for a curve-only definition.</summary>
public double? EnvelopeRadius { get; init; }
}

/// <summary>A saved circular arc using double precision in an older reference cache.</summary>
/// <param name="Center">The local center of the circle.</param>
/// <param name="Normal">The stored normal of the circle.</param>
/// <param name="StartDirection">The stored direction from the center to the start.</param>
/// <param name="Radius">The stored arc radius.</param>
/// <param name="SweepRadians">The signed sweep angle in radians.</param>
public readonly record struct LegacyReferenceCircularArc(ModelVector3D Center, ModelVector3D Normal,
ModelVector3D StartDirection, double Radius, double SweepRadians);

/// <summary>The saved images in an older reference cache, in file order.</summary>
public sealed class LegacyReferenceTexturesDocument : TdbDocument
{
Expand Down
Loading
Loading