From ebd25c63437f0a4b14cdd52ef782d148afd34e33 Mon Sep 17 00:00:00 2001
From: mahach666 <79989386+mahach666@users.noreply.github.com>
Date: Tue, 24 Nov 2026 22:41:25 +0000
Subject: [PATCH] Read Leica PTG binary TLV headers and transposed scanner
poses
---
CHANGELOG.md | 2 +-
README.md | 4 +-
src/PclIO/Formats/Ptg/PtgHeader.cs | 292 ++++++++++++-------------
src/PclIO/Formats/Ptg/PtgScan.cs | 3 +
tests/PclIO.Tests/FormatTests.cs | 154 +++++++++++--
tests/PclIO.Tests/SyntheticFixtures.cs | 81 +++++--
6 files changed, 348 insertions(+), 188 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 115b543..1ec6911 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Read packed CC BIN point normals in file versions 41, 42 and 50.
- CC BIN (`*.bin`, `CCB2`) reader supporting single and multi-cloud entity datasets with 32-bit floating point Cartesian XYZ coordinates, global shift and scale vectors, 8-bit RGB colour arrays, 4x4 coordinate transform matrices, and scalar fields (including intensity). Added `CcBinDocument`, `CcBinScan`, and `PclFileKind.CcBin`.
-- Leica PTG (`*.ptg`) gridded point cloud reader supporting binary scan files with `PTG\0` signature, magic number `0x928FA3C7`, ASCII metadata header (`NumRows`, `NumCols`, `%%properties`, `%%transform`), column offset array, and column validity bitmasks with single or double precision Cartesian XYZ coordinates, intensity and RGB colour. Top-level ASCII index files (`.ptg`) referencing binary scan files are aggregated into multi-scan documents. Added `PtgDocument`, `PtgScan`, and `PclFileKind.LeicaPtg`.
+- Leica PTG (`*.ptg`) gridded point cloud reader supporting binary scan files with `PTG\0` signature, magic number `0x928FA3C7`, a binary TLV metadata header (`%%version`, `%%cols`, `%%rows`, `%%properties`, `%%transform` and name records), a uint64 column offset array, and column validity bitmasks (most significant bit first) with single or double precision Cartesian XYZ coordinates, intensity and RGB colour. The scanner pose matrix is transposed from the PTG row-vector convention on load. Top-level ASCII index files (`.ptg`) referencing binary scan files are aggregated into multi-scan documents. Added `PtgDocument`, `PtgScan`, and `PclFileKind.LeicaPtg`.
- Entwine Point Tile (EPT) reader supporting dataset manifests (`ept.json`), octree hierarchy traversal (`ept-hierarchy/`) with sub-hierarchy page resolution and cycle detection, and point data tile streaming (`ept-data/`) across `"laszip"`, `"binary"`, and `"zstandard"` compression formats. Added `EptDocument`, `EptScan`, `EptKey`, `EptNode`, and `EptDimension`, with spatial bounding box queries (`FindNodes`, `ReadPoints`) and schema-driven dimension extraction.
### Changed
diff --git a/README.md b/README.md
index a1fe843..4c03c2f 100644
--- a/README.md
+++ b/README.md
@@ -54,7 +54,7 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies
| LAZ | `.laz` | LASzip compressed ASPRS LAS (versions 1.0 to 1.4, point formats 0 to 3): XYZ with scale and offset, intensity, classification and 8-bit RGB colour. Decoded via clean-room arithmetic decoder and integer decompressor with pointwise chunked compression (compressor 2) and pointwise uncompressed records (compressor 1). CRS is read from GeoTIFF or WKT VLRs. Point formats 6 to 10 with layered chunked compressor (compressor 3), waveform packets and EVLRs are not currently read. |
| COPC | `.copc.laz`, `.laz` | Cloud Optimized Point Cloud (COPC octree in LAS 1.4 / LAZ): reads the octree hierarchy (root and sub-hierarchy pages) and voxel bounding boxes, center, halfsize and spacing metadata, streaming points by octree node, bounding box or across the whole dataset. LAS formats 0 to 3 are fully decompressed via LASzip arithmetic decoding; LAS 1.4 formats 6 to 8 decode uncompressed anchor points with exact positions, intensity, classification and RGB colour per octree node. |
| EPT | `ept.json`, `.laz`, `.bin`, `.zst` | Entwine Point Tile (EPT octree datasets): reads dataset manifest (`ept.json`), octree hierarchy (`ept-hierarchy/`), and point data tiles (`ept-data/`) across `"laszip"`, `"binary"`, and `"zstandard"` storage types. Supports schema dimension extraction (XYZ, intensity, classification, RGB colour, normals), spatial querying by bounding box (`FindNodes`, `ReadPoints`), depth filtering, and single-node streaming. |
-| Leica PTG | `.ptg` | Leica Cyclone gridded binary exchange point clouds: binary scan files (`.ptg`) with 8-byte signature and magic (`0x928FA3C7`), ASCII metadata header (`NumRows`, `NumCols`, `%%properties`, `%%transform`), column offset array, and column validity bitmasks with single or double precision Cartesian XYZ coordinates, intensity [0..1] and 8-bit RGB colour. Top-level ASCII index files (`.ptg`) referencing binary scan files are aggregated into multi-scan documents. Coordinate transforms applied unless `ApplyTransform` is false. |
+| Leica PTG | `.ptg` | Leica Cyclone gridded binary exchange point clouds: binary scan files (`.ptg`) with 8-byte signature and magic (`0x928FA3C7`), a binary TLV metadata header (`%%version`, `%%cols`, `%%rows`, `%%properties`, `%%transform` and name records), a uint64 column offset array, and column validity bitmasks (most significant bit first) with single or double precision Cartesian XYZ coordinates, intensity [0..1] and 8-bit RGB colour. The scanner pose matrix is stored in the PTG row-vector convention (translation in the last row) and is transposed on load. Top-level ASCII index files (`.ptg`) referencing binary scan files are aggregated into multi-scan documents. Coordinate transforms applied unless `ApplyTransform` is false. Header version 1 and the described record keys are read; other versions or keys are rejected. |
| CC BIN | `.bin` | CC BIN binary entity files (`*.bin`, signature `CCB2`): single or multi-cloud datasets with 32-bit floating point Cartesian XYZ coordinates, global shift and scale vectors, 8-bit RGB colour arrays, 4x4 coordinate transform matrices, and scalar fields (including intensity). The reader applies the stored matrix, divides by the global scale and subtracts the global shift unless `ApplyTransform` is false. Points with non-finite coordinates are skipped. Scalar values beyond the declared field length are absent. Packed normals are supported in file versions 41, 42 and 50. |
### Format detection
@@ -148,7 +148,7 @@ outside the file is fetched.
| PLY | 4096 header lines of at most 1 MiB each; at most 1024 elements with at most 1024 properties each; vertex records at most 1 MiB. |
| PTS | Lines of at most 1 MiB each; declared point count cannot exceed the physical capacity of the file. |
| PTX | Lines of at most 1 MiB each; declared grid counts cannot exceed the physical capacity of the file. |
-| Leica PTG | Metadata header up to 1 MiB; dimensions up to 100,000 rows and columns; grid cells up to 1,000,000,000; column offset table within file bounds; bitmask and point record byte counts checked against file size. |
+| Leica PTG | Metadata header up to 1 MiB with record names up to 256 bytes; header version 1 and described keys only; dimensions up to 100,000 rows and columns; grid cells up to 1,000,000,000; column offset table within file bounds; bitmask and point record byte counts checked against file size. |
| XYZ / text | Lines of at most 1 MiB each; point count cannot exceed the physical capacity of the file. |
| 3D Tiles | Binary chunk length and feature/batch table lengths checked against file size; glTF accessor bounds and byte strides checked against buffer view sizes. |
| Potree | Manifest 16 MiB; point record size up to 1 MiB; node binary file length must be an exact multiple of record size. |
diff --git a/src/PclIO/Formats/Ptg/PtgHeader.cs b/src/PclIO/Formats/Ptg/PtgHeader.cs
index 9b9d9ca..9fcdb2b 100644
--- a/src/PclIO/Formats/Ptg/PtgHeader.cs
+++ b/src/PclIO/Formats/Ptg/PtgHeader.cs
@@ -6,20 +6,32 @@
namespace PclIO.Formats.Ptg;
/// Parsed metadata and layout information from a Leica PTG binary scan header.
+///
+/// The header is a sequence of records: a uint32 name length, the name with a trailing NUL, then a value whose
+/// shape depends on the name. Strings carry a uint32 byte length and the bytes with a trailing NUL; counters are
+/// a bare uint32; the transform is 16 float64 values. The record %%header_end terminates the header and is
+/// immediately followed by the column offset table.
+///
internal sealed class PtgHeader
{
internal static readonly byte[] Tag = [0x50, 0x54, 0x47, 0x00];
internal const uint MagicNumber = 0x928FA3C7;
+ private const int MaxHeaderBytes = 1 << 20; // 1 MB limit
+ private const int MaxNameBytes = 256;
+
public int NumRows { get; }
public int NumCols { get; }
public int Properties { get; }
public PclTransform Transform { get; }
public long ColumnPositionsOffset { get; }
public string? ScanName { get; }
+ public string? ScannerName { get; }
public string? ScannerModel { get; }
public string? SoftwareName { get; }
public string? Version { get; }
+ public string? CreationDate { get; }
+ public string? CreationTime { get; }
public bool HasFloatCoordinates => (Properties & 0x01) != 0;
public bool HasDoubleCoordinates => (Properties & 0x02) != 0;
@@ -35,9 +47,12 @@ internal PtgHeader(
PclTransform transform,
long columnPositionsOffset,
string? scanName,
+ string? scannerName,
string? scannerModel,
string? softwareName,
- string? version)
+ string? version,
+ string? creationDate,
+ string? creationTime)
{
NumRows = numRows;
NumCols = numCols;
@@ -45,14 +60,16 @@ internal PtgHeader(
Transform = transform;
ColumnPositionsOffset = columnPositionsOffset;
ScanName = scanName;
+ ScannerName = scannerName;
ScannerModel = scannerModel;
SoftwareName = softwareName;
Version = version;
+ CreationDate = creationDate;
+ CreationTime = creationTime;
}
public static PtgHeader Parse(Stream stream)
{
- long origin = stream.Position;
Span head = stackalloc byte[8];
int read = stream.ReadAtLeast(head, 8, throwOnEndOfStream: false);
if (read < 8)
@@ -64,162 +81,89 @@ public static PtgHeader Parse(Stream stream)
if (BinaryPrimitives.ReadUInt32LittleEndian(head[4..8]) != MagicNumber)
throw FormatError.Corrupted("Invalid PTG magic number.");
- const int maxHeaderBytes = 1 << 20; // 1 MB limit
- byte[] buffer = new byte[4096];
- using var ms = new MemoryStream();
-
- byte[] endMarker = "%%header_end"u8.ToArray();
- int foundIndex = -1;
- int endLineLength = 0;
-
- while (ms.Length < maxHeaderBytes)
- {
- int n = stream.Read(buffer, 0, buffer.Length);
- if (n == 0) break;
- int prevLen = (int)ms.Length;
- ms.Write(buffer, 0, n);
-
- byte[] fullBytes = ms.GetBuffer();
- int totalBytes = (int)ms.Length;
-
- int searchStart = Math.Max(0, prevLen - endMarker.Length);
- int idx = fullBytes.AsSpan(searchStart, totalBytes - searchStart).IndexOf(endMarker);
- if (idx >= 0)
- {
- foundIndex = searchStart + idx;
- int afterTag = foundIndex + endMarker.Length;
- int nlIdx = fullBytes.AsSpan(afterTag, totalBytes - afterTag).IndexOf((byte)'\n');
- if (nlIdx >= 0)
- {
- endLineLength = afterTag + nlIdx + 1;
- break;
- }
- }
- }
-
- if (foundIndex < 0 || endLineLength == 0)
- throw FormatError.Truncated("PTG header end tag '%%header_end'");
-
- long columnPositionsOffset = origin + 8 + endLineLength;
- byte[] headerBytes = ms.ToArray();
- string headerText = Encoding.ASCII.GetString(headerBytes, 0, foundIndex);
-
- using var reader = new StringReader(headerText);
- string? line;
+ long headerStart = stream.Position;
int? numRows = null;
int? numCols = null;
int? properties = null;
- List? matrix = null;
+ double[]? matrix = null;
string? scanName = null;
+ string? scannerName = null;
string? scannerModel = null;
string? softwareName = null;
string? version = null;
+ string? creationDate = null;
+ string? creationTime = null;
- while ((line = reader.ReadLine()) != null)
+ byte[] nameBuf = new byte[MaxNameBytes];
+ bool ended = false;
+ while (!ended)
{
- line = line.Trim();
- if (line.Length == 0) continue;
- if (line.StartsWith("%%header_begin", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("header_begin", StringComparison.OrdinalIgnoreCase))
- {
- continue;
- }
+ if (stream.Position - headerStart > MaxHeaderBytes)
+ throw FormatError.Corrupted("PTG header exceeds the 1 MiB limit.");
- if (line.StartsWith("%%version", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("version", StringComparison.OrdinalIgnoreCase))
- {
- version = ExtractValue(line);
- continue;
- }
-
- if (line.StartsWith("NumRows", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("%%NumRows", StringComparison.OrdinalIgnoreCase))
- {
- string val = ExtractValue(line);
- if (!int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nr))
- throw FormatError.Corrupted($"Invalid NumRows value '{val}'.");
- numRows = nr;
- continue;
- }
-
- if (line.StartsWith("NumCols", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("%%NumCols", StringComparison.OrdinalIgnoreCase))
- {
- string val = ExtractValue(line);
- if (!int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nc))
- throw FormatError.Corrupted($"Invalid NumCols value '{val}'.");
- numCols = nc;
- continue;
- }
-
- if (line.StartsWith("%%properties", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("properties", StringComparison.OrdinalIgnoreCase))
- {
- string val = ExtractValue(line);
- int p;
- if (val.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
- {
- if (!int.TryParse(val[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out p))
- throw FormatError.Corrupted($"Invalid properties hex value '{val}'.");
- }
- else
- {
- if (!int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out p))
- throw FormatError.Corrupted($"Invalid properties value '{val}'.");
- }
- properties = p;
- continue;
- }
-
- if (line.StartsWith("%%transform", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("transform", StringComparison.OrdinalIgnoreCase))
- {
- matrix = [];
- string remaining = ExtractValue(line);
- if (!string.IsNullOrWhiteSpace(remaining))
- {
- AddDoubles(remaining, matrix);
- }
- while (matrix.Count < 16)
- {
- string? nextLine = reader.ReadLine();
- if (nextLine == null)
- throw FormatError.Truncated("PTG transform matrix; expected 16 values.");
- AddDoubles(nextLine, matrix);
- }
- if (matrix.Count != 16)
- throw FormatError.Corrupted($"Invalid PTG transform matrix: expected 16 values, got {matrix.Count}.");
- continue;
- }
-
- if (line.StartsWith("%%scan_name", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("scan_name", StringComparison.OrdinalIgnoreCase))
- {
- scanName = ExtractValue(line);
- continue;
- }
+ uint nameLength = ReadUInt32(stream);
+ if (nameLength < 2 || nameLength > MaxNameBytes)
+ throw FormatError.Corrupted($"Invalid PTG header record name length {nameLength}.");
- if (line.StartsWith("%%scanner_model", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("scanner_model", StringComparison.OrdinalIgnoreCase))
- {
- scannerModel = ExtractValue(line);
- continue;
- }
+ ReadExactly(stream, nameBuf.AsSpan(0, (int)nameLength), "PTG header record name");
+ if (nameBuf[(int)nameLength - 1] != 0)
+ throw FormatError.Corrupted("PTG header record name is not NUL-terminated.");
+ string key = Encoding.ASCII.GetString(nameBuf, 0, (int)nameLength - 1);
- if (line.StartsWith("%%sw_name", StringComparison.OrdinalIgnoreCase) ||
- line.StartsWith("sw_name", StringComparison.OrdinalIgnoreCase))
+ switch (key)
{
- softwareName = ExtractValue(line);
- continue;
+ case "%%header_begin":
+ break;
+ case "%%header_end":
+ ended = true;
+ break;
+ case "%%version":
+ uint v = ReadUInt32(stream);
+ if (v != 1)
+ throw FormatError.Unsupported($"PTG header version {v}; only version 1 is described.");
+ version = v.ToString(CultureInfo.InvariantCulture);
+ break;
+ case "%%cols":
+ numCols = ReadCount(stream, key);
+ break;
+ case "%%rows":
+ numRows = ReadCount(stream, key);
+ break;
+ case "%%properties":
+ properties = (int)ReadUInt32(stream);
+ break;
+ case "%%transform":
+ matrix = ReadTransform(stream);
+ break;
+ case "%%scan_name":
+ scanName = ReadString(stream, key);
+ break;
+ case "%%scanner_name":
+ scannerName = ReadString(stream, key);
+ break;
+ case "%%scanner_model":
+ scannerModel = ReadString(stream, key);
+ break;
+ case "%%sw_name":
+ softwareName = ReadString(stream, key);
+ break;
+ case "%%creation_date":
+ creationDate = ReadString(stream, key);
+ break;
+ case "%%creation_time":
+ creationTime = ReadString(stream, key);
+ break;
+ default:
+ throw FormatError.Unsupported($"PTG header key '{key}'.");
}
}
if (!numRows.HasValue)
- throw FormatError.Corrupted("Missing NumRows in PTG header.");
+ throw FormatError.Corrupted("Missing %%rows in PTG header.");
if (!numCols.HasValue)
- throw FormatError.Corrupted("Missing NumCols in PTG header.");
+ throw FormatError.Corrupted("Missing %%cols in PTG header.");
if (!properties.HasValue)
- throw FormatError.Corrupted("Missing properties in PTG header.");
+ throw FormatError.Corrupted("Missing %%properties in PTG header.");
int rows = numRows.Value;
int cols = numCols.Value;
@@ -238,29 +182,73 @@ public static PtgHeader Parse(Stream stream)
if ((pVal & ~0x0F) != 0)
throw FormatError.Corrupted($"Unsupported PTG property bits: 0x{pVal:X}.");
- PclTransform transform = matrix != null ? new PclTransform { Matrix4x4 = matrix.ToArray() } : PclTransform.Identity;
+ // PTG stores a row-vector matrix (translation in the last row); PclTransform applies a column-vector one
+ // (translation in the last column), so the matrix is transposed on load.
+ PclTransform transform = PclTransform.Identity;
+ if (matrix != null)
+ {
+ double[] m = new double[16];
+ for (int r = 0; r < 4; r++)
+ for (int c = 0; c < 4; c++)
+ m[r * 4 + c] = matrix[c * 4 + r];
+ transform = new PclTransform { Matrix4x4 = m };
+ }
+
+ return new PtgHeader(rows, cols, pVal, transform, stream.Position,
+ scanName, scannerName, scannerModel, softwareName, version, creationDate, creationTime);
+ }
- return new PtgHeader(rows, cols, pVal, transform, columnPositionsOffset, scanName, scannerModel, softwareName, version);
+ private static void ReadExactly(Stream stream, Span buffer, string what)
+ {
+ try
+ {
+ stream.ReadExactly(buffer);
+ }
+ catch (EndOfStreamException)
+ {
+ throw FormatError.Truncated(what);
+ }
+ }
+
+ private static uint ReadUInt32(Stream stream)
+ {
+ Span buf = stackalloc byte[4];
+ ReadExactly(stream, buf, "PTG header uint32");
+ return BinaryPrimitives.ReadUInt32LittleEndian(buf);
+ }
+
+ private static int ReadCount(Stream stream, string key)
+ {
+ uint value = ReadUInt32(stream);
+ if (value > int.MaxValue)
+ throw FormatError.Corrupted($"PTG {key} value {value} exceeds the supported range.");
+ return (int)value;
}
- private static string ExtractValue(string line)
+ private static string ReadString(Stream stream, string key)
{
- int i = 0;
- while (i < line.Length && !char.IsWhiteSpace(line[i]) && line[i] != ':' && line[i] != '=') i++;
- while (i < line.Length && (char.IsWhiteSpace(line[i]) || line[i] == ':' || line[i] == '=')) i++;
- return i < line.Length ? line[i..].Trim() : string.Empty;
+ uint length = ReadUInt32(stream);
+ if (length == 0 || length > MaxHeaderBytes)
+ throw FormatError.Corrupted($"Invalid PTG {key} string length {length}.");
+
+ byte[] buf = new byte[length];
+ ReadExactly(stream, buf, $"PTG {key} string");
+ int textLength = buf[length - 1] == 0 ? (int)length - 1 : (int)length;
+ return Encoding.UTF8.GetString(buf, 0, textLength);
}
- private static void AddDoubles(string text, List values)
+ private static double[] ReadTransform(Stream stream)
{
- string[] parts = text.Split([' ', '\t', ','], StringSplitOptions.RemoveEmptyEntries);
- foreach (var part in parts)
+ byte[] buf = new byte[128];
+ ReadExactly(stream, buf, "PTG transform matrix");
+ double[] values = new double[16];
+ for (int i = 0; i < 16; i++)
{
- if (!double.TryParse(part, NumberStyles.Float, CultureInfo.InvariantCulture, out double val))
- throw FormatError.Corrupted($"Invalid numeric value in PTG transform: '{part}'.");
+ double val = BinaryPrimitives.ReadDoubleLittleEndian(buf.AsSpan(i * 8, 8));
if (!double.IsFinite(val))
throw FormatError.Corrupted("Non-finite numeric value in PTG transform.");
- values.Add(val);
+ values[i] = val;
}
+ return values;
}
}
diff --git a/src/PclIO/Formats/Ptg/PtgScan.cs b/src/PclIO/Formats/Ptg/PtgScan.cs
index ab61d8b..8fcf6e6 100644
--- a/src/PclIO/Formats/Ptg/PtgScan.cs
+++ b/src/PclIO/Formats/Ptg/PtgScan.cs
@@ -55,8 +55,11 @@ internal PtgScan(string filePath, string id, string name, PtgHeader header, long
_properties["HasColors"] = header.HasColors ? "true" : "false";
if (!string.IsNullOrEmpty(header.Version)) _properties["Version"] = header.Version;
+ if (!string.IsNullOrEmpty(header.ScannerName)) _properties["ScannerName"] = header.ScannerName;
if (!string.IsNullOrEmpty(header.ScannerModel)) _properties["ScannerModel"] = header.ScannerModel;
if (!string.IsNullOrEmpty(header.SoftwareName)) _properties["SoftwareName"] = header.SoftwareName;
+ if (!string.IsNullOrEmpty(header.CreationDate)) _properties["CreationDate"] = header.CreationDate;
+ if (!string.IsNullOrEmpty(header.CreationTime)) _properties["CreationTime"] = header.CreationTime;
}
internal static PtgScan Create(string filePath, string id, string? defaultName = null)
diff --git a/tests/PclIO.Tests/FormatTests.cs b/tests/PclIO.Tests/FormatTests.cs
index c5e2036..c3e3514 100644
--- a/tests/PclIO.Tests/FormatTests.cs
+++ b/tests/PclIO.Tests/FormatTests.cs
@@ -6140,12 +6140,13 @@ public void Read_Ptg_Binary_With_Transform()
{
using var dir = new TempDirectory();
var points = new[] { new SyntheticFixtures.PtgSamplePoint(1, 2, 3) };
+ // PTG stores a row-vector matrix: the translation lives in the last row.
double[] matrix =
[
- 1, 0, 0, 10,
- 0, 1, 0, 20,
- 0, 0, 1, 30,
- 0, 0, 0, 1
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 10, 20, 30, 1
];
byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary(
numCols: 1, numRows: 1, properties: 0x01, points: points, transformMatrix: matrix);
@@ -6167,6 +6168,49 @@ public void Read_Ptg_Binary_With_Transform()
Assert.Equal(3, ptRaw.Z, 3);
}
+ [Fact]
+ public void Read_Ptg_Binary_Rotation_Transform_Convention()
+ {
+ using var dir = new TempDirectory();
+ var points = new[] { new SyntheticFixtures.PtgSamplePoint(1, 0, 0) };
+ // A +90 degree rotation about Z in the PTG row-vector convention, plus a translation.
+ // The local X axis maps to +Y, so (1,0,0) becomes (10,21,30).
+ double[] matrix =
+ [
+ 0, 1, 0, 0,
+ -1, 0, 0, 0,
+ 0, 0, 1, 0,
+ 10, 20, 30, 1
+ ];
+ byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary(
+ numCols: 1, numRows: 1, properties: 0x01, points: points, transformMatrix: matrix);
+
+ string path = dir.Write("rotated.ptg", ptgBytes);
+ using var doc = PtgDocument.Open(path);
+ var pt = Assert.Single(doc.Scans[0].ReadPoints());
+ Assert.Equal(10, pt.X, 3);
+ Assert.Equal(21, pt.Y, 3);
+ Assert.Equal(30, pt.Z, 3);
+ }
+
+ [Fact]
+ public void Read_Ptg_Binary_Metadata_Properties()
+ {
+ using var dir = new TempDirectory();
+ byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary(scanName: "StationA");
+ string path = dir.Write("meta.ptg", ptgBytes);
+ using var doc = PtgDocument.Open(path);
+ var scan = (PtgScan)doc.Scans[0];
+
+ Assert.Equal("StationA", scan.Name);
+ Assert.Equal("1", scan.Properties["Version"]);
+ Assert.Equal("Scanner", scan.Properties["ScannerName"]);
+ Assert.Equal("Model", scan.Properties["ScannerModel"]);
+ Assert.Equal("SyntheticSoftware", scan.Properties["SoftwareName"]);
+ Assert.Equal("2000-01-01-0000", scan.Properties["CreationDate"]);
+ Assert.Equal("2000-01-01-0000", scan.Properties["CreationTime"]);
+ }
+
[Fact]
public void Read_Ptg_Binary_Subsampling_And_MaxPoints()
{
@@ -6259,9 +6303,14 @@ public void Ptg_Rejects_Corrupt_Magic_Or_Signature()
public void Ptg_Rejects_Missing_Header_End()
{
using var dir = new TempDirectory();
- string customHeader = "%%header_begin\nNumRows 1\nNumCols 1\n%%properties 1\n";
- byte[] badHeader = SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: customHeader);
- string path = dir.Write("no_end.ptg", badHeader);
+ // Records stop before %%header_end and the file ends: the next record length cannot be read.
+ byte[] records = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%rows", 1),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 1));
+ byte[] file = [0x50, 0x54, 0x47, 0x00, 0xC7, 0xA3, 0x8F, 0x92, .. records];
+ string path = dir.Write("no_end.ptg", file);
Assert.Throws(() => PtgScan.Create(path, "scan-0"));
}
@@ -6270,18 +6319,32 @@ public void Ptg_Rejects_Missing_Header_End()
public void Ptg_Rejects_Missing_Or_Invalid_Dimensions()
{
using var dir = new TempDirectory();
- // Missing NumRows
- string noRows = "%%header_begin\nNumCols 1\n%%properties 1\n%%header_end\n";
+ // Missing %%rows
+ byte[] noRows = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 1),
+ SyntheticFixtures.PtgTlvRecord("%%header_end", []));
string path1 = dir.Write("no_rows.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: noRows));
Assert.Throws(() => PtgScan.Create(path1, "scan-0"));
- // Zero or negative rows
- string zeroRows = "%%header_begin\nNumRows 0\nNumCols 1\n%%properties 1\n%%header_end\n";
+ // Zero rows
+ byte[] zeroRows = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%rows", 0),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 1),
+ SyntheticFixtures.PtgTlvRecord("%%header_end", []));
string path2 = dir.Write("zero_rows.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: zeroRows));
Assert.Throws(() => PtgScan.Create(path2, "scan-0"));
// Oversized dimensions
- string huge = "%%header_begin\nNumRows 200000\nNumCols 1\n%%properties 1\n%%header_end\n";
+ byte[] huge = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%rows", 200000),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 1),
+ SyntheticFixtures.PtgTlvRecord("%%header_end", []));
string path3 = dir.Write("huge.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: huge));
Assert.Throws(() => PtgScan.Create(path3, "scan-0"));
}
@@ -6291,21 +6354,82 @@ public void Ptg_Rejects_Invalid_Properties()
{
using var dir = new TempDirectory();
// Both float (0x1) and double (0x2)
- string both = "%%header_begin\nNumRows 1\nNumCols 1\n%%properties 3\n%%header_end\n";
+ byte[] both = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%rows", 1),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 3),
+ SyntheticFixtures.PtgTlvRecord("%%header_end", []));
string path1 = dir.Write("both.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: both));
Assert.Throws(() => PtgScan.Create(path1, "scan-0"));
// Neither float nor double (only intensity 0x4)
- string neither = "%%header_begin\nNumRows 1\nNumCols 1\n%%properties 4\n%%header_end\n";
+ byte[] neither = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%rows", 1),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 4),
+ SyntheticFixtures.PtgTlvRecord("%%header_end", []));
string path2 = dir.Write("neither.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: neither));
Assert.Throws(() => PtgScan.Create(path2, "scan-0"));
// Unsupported property bits
- string unsupported = "%%header_begin\nNumRows 1\nNumCols 1\n%%properties 0x21\n%%header_end\n";
+ byte[] unsupported = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%rows", 1),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 0x21),
+ SyntheticFixtures.PtgTlvRecord("%%header_end", []));
string path3 = dir.Write("unsupported.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: unsupported));
Assert.Throws(() => PtgScan.Create(path3, "scan-0"));
}
+ [Fact]
+ public void Ptg_Rejects_Unknown_Header_Key_Or_Version()
+ {
+ using var dir = new TempDirectory();
+ byte[] unknownKey = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgStringRecord("%%mystery", "value"),
+ SyntheticFixtures.PtgU32Record("%%rows", 1),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 1),
+ SyntheticFixtures.PtgTlvRecord("%%header_end", []));
+ string path1 = dir.Write("unknown_key.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: unknownKey));
+ Assert.Throws(() => PtgScan.Create(path1, "scan-0"));
+
+ byte[] badVersion = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%version", 2),
+ SyntheticFixtures.PtgU32Record("%%rows", 1),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 1),
+ SyntheticFixtures.PtgTlvRecord("%%header_end", []));
+ string path2 = dir.Write("bad_version.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: badVersion));
+ Assert.Throws(() => PtgScan.Create(path2, "scan-0"));
+ }
+
+ [Fact]
+ public void Ptg_Rejects_Oversized_Name_Or_Truncated_Transform()
+ {
+ using var dir = new TempDirectory();
+ // A record name length beyond the 256-byte bound.
+ byte[] hugeName = [0x50, 0x54, 0x47, 0x00, 0xC7, 0xA3, 0x8F, 0x92, 0xFF, 0xFF, 0xFF, 0xFF];
+ string path1 = dir.Write("huge_name.ptg", hugeName);
+ Assert.Throws(() => PtgScan.Create(path1, "scan-0"));
+
+ // A %%transform record whose value is cut short; the file ends inside the matrix.
+ byte[] records = SyntheticFixtures.PtgHeaderRecords(
+ SyntheticFixtures.PtgTlvRecord("%%header_begin", []),
+ SyntheticFixtures.PtgU32Record("%%rows", 1),
+ SyntheticFixtures.PtgU32Record("%%cols", 1),
+ SyntheticFixtures.PtgU32Record("%%properties", 1),
+ SyntheticFixtures.PtgTlvRecord("%%transform", new byte[64]));
+ byte[] file = [0x50, 0x54, 0x47, 0x00, 0xC7, 0xA3, 0x8F, 0x92, .. records];
+ string path2 = dir.Write("short_transform.ptg", file);
+ Assert.Throws(() => PtgScan.Create(path2, "scan-0"));
+ }
+
[Fact]
public void Ptg_Rejects_Corrupt_Offsets_Or_Truncated_Data()
{
diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs
index a720e94..6413dcf 100644
--- a/tests/PclIO.Tests/SyntheticFixtures.cs
+++ b/tests/PclIO.Tests/SyntheticFixtures.cs
@@ -2780,6 +2780,10 @@ public record PtgSamplePoint(double X, double Y, double Z, float? Intensity = nu
new(7.0, 8.0, 9.0, 0.2f, new PclColor(100, 150, 200)),
];
+ /// Creates a synthetic Leica PTG binary scan file. The header is a sequence of TLV records
+ /// (see ); is in the PTG row-vector convention
+ /// with the translation in the last row. replaces the whole record block
+ /// after the 8-byte signature, for malformed-input tests.
public static byte[] CreateSyntheticPtgBinary(
int numCols = 3,
int numRows = 1,
@@ -2787,7 +2791,7 @@ public static byte[] CreateSyntheticPtgBinary(
IReadOnlyList? points = null,
double[]? transformMatrix = null,
string? scanName = "SyntheticScan",
- string? customHeader = null,
+ byte[]? customHeader = null,
bool corruptMagic = false,
bool corruptOffsets = false)
{
@@ -2806,30 +2810,32 @@ public static byte[] CreateSyntheticPtgBinary(
byte[] headerBytes;
if (customHeader != null)
{
- headerBytes = Encoding.ASCII.GetBytes(customHeader);
+ headerBytes = customHeader;
}
else
{
- var sb = new StringBuilder();
- sb.AppendLine("%%header_begin");
- sb.AppendLine("version 1");
- sb.AppendLine(string.Create(CultureInfo.InvariantCulture, $"NumRows {numRows}"));
- sb.AppendLine(string.Create(CultureInfo.InvariantCulture, $"NumCols {numCols}"));
- sb.AppendLine(string.Create(CultureInfo.InvariantCulture, $"%%properties {properties}"));
+ using var hdr = new MemoryStream();
+ hdr.Write(PtgTlvRecord("%%header_begin", []));
+ hdr.Write(PtgU32Record("%%version", 1));
+ hdr.Write(PtgStringRecord("%%sw_name", "SyntheticSoftware"));
if (!string.IsNullOrEmpty(scanName))
- sb.AppendLine($"%%scan_name {scanName}");
-
+ hdr.Write(PtgStringRecord("%%scan_name", scanName));
+ hdr.Write(PtgStringRecord("%%scanner_name", "Scanner"));
+ hdr.Write(PtgStringRecord("%%scanner_model", "Model"));
+ hdr.Write(PtgStringRecord("%%creation_date", "2000-01-01-0000"));
+ hdr.Write(PtgStringRecord("%%creation_time", "2000-01-01-0000"));
+ hdr.Write(PtgU32Record("%%cols", (uint)numCols));
+ hdr.Write(PtgU32Record("%%rows", (uint)numRows));
if (transformMatrix is { Length: 16 } m)
{
- sb.AppendLine("%%transform");
- sb.AppendLine(string.Create(CultureInfo.InvariantCulture, $"{m[0]} {m[1]} {m[2]} {m[3]}"));
- sb.AppendLine(string.Create(CultureInfo.InvariantCulture, $"{m[4]} {m[5]} {m[6]} {m[7]}"));
- sb.AppendLine(string.Create(CultureInfo.InvariantCulture, $"{m[8]} {m[9]} {m[10]} {m[11]}"));
- sb.AppendLine(string.Create(CultureInfo.InvariantCulture, $"{m[12]} {m[13]} {m[14]} {m[15]}"));
+ byte[] matrixBytes = new byte[128];
+ for (int i = 0; i < 16; i++)
+ BinaryPrimitives.WriteDoubleLittleEndian(matrixBytes.AsSpan(i * 8, 8), m[i]);
+ hdr.Write(PtgTlvRecord("%%transform", matrixBytes));
}
-
- sb.AppendLine("%%header_end");
- headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
+ hdr.Write(PtgU32Record("%%properties", (uint)properties));
+ hdr.Write(PtgTlvRecord("%%header_end", []));
+ headerBytes = hdr.ToArray();
}
ms.Write(headerBytes);
@@ -2925,6 +2931,45 @@ public static byte[] CreateSyntheticPtgBinary(
return ms.ToArray();
}
+ /// One PTG header record: uint32 name length, the name with a trailing NUL, then the raw value bytes.
+ public static byte[] PtgTlvRecord(string key, byte[] value)
+ {
+ byte[] name = Encoding.ASCII.GetBytes(key + "\0");
+ using var ms = new MemoryStream();
+ Span len = stackalloc byte[4];
+ BinaryPrimitives.WriteUInt32LittleEndian(len, (uint)name.Length);
+ ms.Write(len);
+ ms.Write(name);
+ ms.Write(value);
+ return ms.ToArray();
+ }
+
+ /// A PTG header record whose value is a bare uint32 (%%version, %%cols, %%rows, %%properties).
+ public static byte[] PtgU32Record(string key, uint value)
+ {
+ byte[] buf = new byte[4];
+ BinaryPrimitives.WriteUInt32LittleEndian(buf, value);
+ return PtgTlvRecord(key, buf);
+ }
+
+ /// A PTG header record whose value is a length-prefixed string with a trailing NUL.
+ public static byte[] PtgStringRecord(string key, string value)
+ {
+ byte[] text = Encoding.UTF8.GetBytes(value + "\0");
+ byte[] buf = new byte[4 + text.Length];
+ BinaryPrimitives.WriteUInt32LittleEndian(buf, (uint)text.Length);
+ text.CopyTo(buf, 4);
+ return PtgTlvRecord(key, buf);
+ }
+
+ /// Concatenates PTG header records into a custom header block for malformed-input tests.
+ public static byte[] PtgHeaderRecords(params byte[][] records)
+ {
+ using var ms = new MemoryStream();
+ foreach (var record in records) ms.Write(record);
+ return ms.ToArray();
+ }
+
public static byte[] CreateSyntheticPtgIndex(
IEnumerable scanRelativePaths,
string? headerLine = "PTG index file")