diff --git a/CHANGELOG.md b/CHANGELOG.md index d0bfcfc..5c1d25b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- 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`. - 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 976ea95..eac2670 100644 --- a/README.md +++ b/README.md @@ -54,6 +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. | ### Format detection @@ -63,7 +64,7 @@ regard to case. - E57, ReCap scan and Leica files are recognised by their content and accepted with any extension; for Leica, `.lgs` selects the older container and any other extension `.lgsx`. EdgeWise files are also recognised by content when the extension is none of its own. - A LAS file is recognised by the `LASF` signature with any extension except `.laz` and `.copc.laz`. A LAZ file is recognised by the `LASF` signature, a valid LASzip VLR and the `.laz` extension. A COPC file is recognised by the LAS 1.4 header and the `copc` info variable length record with `.copc.laz` or any extension. A PCD file is recognised by its header structure with any extension. A PLY file is recognised by its magic word and header structure with any extension. A PTS file is recognised by an integer point count header line followed by coordinate lines with any extension, or coordinate lines with the `.pts` extension. A PTX file is recognised by its 10-line header structure (grid dimensions, scanner pose, 4x4 matrix) with any extension. An XYZ / delimited text file is recognised by an explicit column header containing X, Y, Z in any extension, or by numeric coordinate lines with a recognised extension (`.xyz`, `.asc`, `.txt`, `.csv`). An SBF file is recognised by its companion `[SBF]` header structure with any extension, or by the binary signature `0x2A, 0x2A` (`**`) and record size formula (`.sbf`, `.sbf.data`, `.data`). A 3D Tiles `.pnts` tile is recognised by the `pnts` signature, version 1, and matching byte lengths. A glTF `.glb` point cloud is recognised by the `glTF` signature, version 2, and mesh primitive mode 0 (POINTS). A 3D Tiles tileset is recognised by JSON containing `asset` and `root` objects (`tileset.json`). A Potree dataset is recognised by `cloud.js` (with `octreeDir` and attribute descriptors) or `metadata.json` (version 2.x and point attributes) in `.js` or `.json`, by `.hrc` hierarchy files with 5-byte node records, or by ancestor `cloud.js`/`metadata.json` next to a `.bin` file. An EPT dataset is recognised by `ept.json` manifest structure (bounds, dataType, schema) or by companion `ept.json` next to octree tiles. + A LAS file is recognised by the `LASF` signature with any extension except `.laz` and `.copc.laz`. A LAZ file is recognised by the `LASF` signature, a valid LASzip VLR and the `.laz` extension. A COPC file is recognised by the LAS 1.4 header and the `copc` info variable length record with `.copc.laz` or any extension. A PCD file is recognised by its header structure with any extension. A PLY file is recognised by its magic word and header structure with any extension. A PTS file is recognised by an integer point count header line followed by coordinate lines with any extension, or coordinate lines with the `.pts` extension. A PTX file is recognised by its 10-line header structure (grid dimensions, scanner pose, 4x4 matrix) with any extension. An XYZ / delimited text file is recognised by an explicit column header containing X, Y, Z in any extension, or by numeric coordinate lines with a recognised extension (`.xyz`, `.asc`, `.txt`, `.csv`). An SBF file is recognised by its companion `[SBF]` header structure with any extension, or by the binary signature `0x2A, 0x2A` (`**`) and record size formula (`.sbf`, `.sbf.data`, `.data`). A 3D Tiles `.pnts` tile is recognised by the `pnts` signature, version 1, and matching byte lengths. A glTF `.glb` point cloud is recognised by the `glTF` signature, version 2, and mesh primitive mode 0 (POINTS). A 3D Tiles tileset is recognised by JSON containing `asset` and `root` objects (`tileset.json`). A Potree dataset is recognised by `cloud.js` (with `octreeDir` and attribute descriptors) or `metadata.json` (version 2.x and point attributes) in `.js` or `.json`, by `.hrc` hierarchy files with 5-byte node records, or by ancestor `cloud.js`/`metadata.json` next to a `.bin` file. An EPT dataset is recognised by `ept.json` manifest structure (bounds, dataType, schema) or by companion `ept.json` next to octree tiles. A Leica PTG binary scan file is recognised by the `PTG\0` tag and magic number `0x928FA3C7` with any extension; a top-level ASCII index file is recognised by the `PTG index` header and the `.ptg` extension. - A FARO file must be an OLE2 compound file with the extension `.fls`. A ReCap project must be a ZIP archive with the extension `.rcp`. A PinPoint file must be a JSON text file with the extension `.smf` or `.srf`. - The extensions `.c3db` and `.c3ptx` select EdgeWise without a content check. A `.c3ptx` file is read as one cluster file and any @@ -92,6 +93,7 @@ Where the readers look for the files a project refers to: - EdgeWise database: each cluster file is named relative to the database's folder; a missing one is skipped with a warning. - SBF: when opening a `.sbf` header file, the reader looks for a companion `.sbf.data` or `.data` binary file in the same directory. When opening a `.sbf.data` or `.data` file, it looks for a companion `.sbf` header file. - 3D Tiles tileset: referenced tile contents (`.pnts`, `.glb`, or external `.json` tilesets) are resolved relative to the directory of `tileset.json`; missing content files are reported with a warning. +- Leica PTG index: relative scan paths referenced by an index file are resolved inside the index file's directory; path traversal outside the directory is rejected. ### Data filters @@ -117,6 +119,7 @@ These readers drop data without an error or a warning, so a scan can yield fewer - PLY: a vertex with a NaN or infinite coordinate is not returned; colour that is not stored as 8-bit integers is left unread, with a warning. - PTS: a point with a NaN or infinite coordinate is not returned. - PTX: empty grid cells (0, 0, 0) and points with a NaN or infinite coordinate are not returned. +- Leica PTG: invalid grid cells (flagged 0 in the column bitmask) and points with a NaN or infinite coordinate are not returned. - XYZ / text: a point with a NaN or infinite coordinate is not returned; comment lines are skipped. ### Limits @@ -144,6 +147,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. | | 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/docs/public-api.md b/docs/public-api.md index 7d06e07..3cbbebb 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -14,7 +14,7 @@ format-specific members can change when the support for that format changes. | Type | Use | |---|---| | `PclFile` | Static entry point. `DetectKind(path)` and `DetectKind(stream, extension)` return a `PclFileKind`; `Open(path, options)` detects the format and returns a `PclDocument`. | -| `PclFileKind` | `Unknown`, `E57`, `RecapProject`, `RecapScan`, `LeicaLgsx`, `LeicaLgs`, `FaroFls`, `PinPoint`, `EdgeWise`, `Las`, `Pcd`, `Ply`, `Pts`, `Ptx`, `Xyz`, `Sbf`, `Tiles3d`, `Potree`, `Laz`, `Copc` and `Ept`. | +| `PclFileKind` | `Unknown`, `E57`, `RecapProject`, `RecapScan`, `LeicaLgsx`, `LeicaLgs`, `FaroFls`, `PinPoint`, `EdgeWise`, `Las`, `Pcd`, `Ply`, `Pts`, `Ptx`, `Xyz`, `Sbf`, `Tiles3d`, `Potree`, `Laz`, `Copc`, `Ept` and `LeicaPtg`. | | `PclReadOptions` | `MaxPoints` (limit of one read call, null for all, 0 for none), `MaxCoordinateMagnitude` (default 5000, null for no limit; NaN and infinite coordinates are never returned; currently only PinPoint applies it), `EdgeWiseCoordinateScale` (default 0.128 / 32768 metres per unit; the files do not declare it), `SubsampleStep` (1 keeps every point, N keeps about one in N), `Blocks` (range of the scan's blocks in file order, null for all; currently only Leica honours it), `MaxDegreeOfParallelism` (default 1: sequential; above 1 decodes the selected Leica blocks in parallel, keeping file order), `ApplyTransform` (default true), `Strict` (default false: a reader that finds incomplete data fails with `InvalidDataException` instead of adding a warning), `ExcludeFilteredPoints` (default false: points the file marks as filtered are excluded; currently the `FilterBits` channel of the PinPoint sectioned layout), `TextColumns` (explicit column names or layout for delimited text point clouds), `TextDelimiter` (explicit delimiter character for delimited text), `TextCommentPrefix` (prefix for comment lines in delimited text, default `#`) and `TextCoordinateScale` (coordinate scale factor for delimited text, default 1.0). Negative `MaxPoints`, a negative magnitude limit, a negative block start or count, a non-positive or non-finite EdgeWise scale or text coordinate scale, and a step or parallelism below 1 throw `ArgumentOutOfRangeException`. `PclReadOptions.Default` has no limit. | | `BlockRange` | `StartBlock` (zero-based index of the first block to read) and `BlockCount` (how many blocks at most, null for all from the start on; a range past the last block yields no points, 0 yields none). | @@ -44,6 +44,7 @@ is the argument, which may also be a file name. `Tiles3d` is recognised by the `pnts` signature, version 1 and matching byte lengths (`.pnts`), the `glTF` signature, version 2 and mesh primitive mode 0 (`.glb`), or JSON containing `asset` and `root` objects (`tileset.json`). `Potree` is recognised by `cloud.js` (with `octreeDir` and attribute descriptors) or `metadata.json` (version 2.x and point attributes) in `.js` or `.json`, by `.hrc` hierarchy files with 5-byte node records, or by ancestor `cloud.js`/`metadata.json` next to a `.bin` file. `Ept` is recognised by `ept.json` manifest structure (bounds, dataType, schema) or by companion `ept.json` next to octree tiles. + `LeicaPtg` is recognised by the `PTG\0` tag and magic number `0x928FA3C7` with any extension, or by the `PTG index` header with the `.ptg` extension. - `FaroFls` needs an OLE2 compound file with the extension `.fls`, `RecapProject` a ZIP archive with the extension `.rcp`, and `PinPoint` a JSON text file with the extension `.smf` or `.srf`. - The extensions `.c3db` and `.c3ptx` select `EdgeWise` without a content check, so a damaged file with one of these extensions is @@ -91,6 +92,7 @@ drop points that fail a plausibility rule (see the README), so a scan can yield | LAZ | The header count (the extended 1.4 count when it states one). It is not checked against the chunk data until read. | | COPC | The header count (the extended 1.4 count when it states one). It is not checked against the chunk data until read. | | EPT | The point count declared in the manifest, or the sum of points across discovered octree nodes. | +| Leica PTG | Total valid returns across all gridded scans, determined by decoding the column validity bitmasks. | `HasColors`, `HasIntensities` and `HasNormals` follow what the file contains, except for the scans of a ReCap project, where all three are true when the `.rcs` file was found and false otherwise, without the file being opened. A ReCap scan reads the channels @@ -100,7 +102,7 @@ no colour. ## Format documents `E57Document`/`E57Scan`, `RcsScanDocument`/`RcsScan`, `RcpProjectDocument`/`RcpScan`, `LgsxDocument`/`LgsxScan`/`LgsxEntry`/`LgsxSetup`, -`FaroFlsDocument`/`FaroScan`, `PinPointDocument`/`PinPointScan`, `EdgeWiseDocument`/`EdgeWiseScan`, `LasDocument`/`LasScan`, `LazDocument`/`LazScan`, `CopcDocument`/`CopcScan`, `PcdDocument`/`PcdScan`, `PlyDocument`/`PlyScan`, `PtsDocument`/`PtsScan`, `PtxDocument`/`PtxScan`, `XyzDocument`/`XyzScan`, `SbfDocument`/`SbfScan`, `Tiles3dDocument`/`PntsScan`/`GlbScan`, `PotreeDocument`/`PotreeScan` and `EptDocument`/`EptScan` are the readers behind +`FaroFlsDocument`/`FaroScan`, `PinPointDocument`/`PinPointScan`, `EdgeWiseDocument`/`EdgeWiseScan`, `LasDocument`/`LasScan`, `LazDocument`/`LazScan`, `CopcDocument`/`CopcScan`, `PcdDocument`/`PcdScan`, `PlyDocument`/`PlyScan`, `PtsDocument`/`PtsScan`, `PtxDocument`/`PtxScan`, `XyzDocument`/`XyzScan`, `SbfDocument`/`SbfScan`, `Tiles3dDocument`/`PntsScan`/`GlbScan`, `PotreeDocument`/`PotreeScan`, `EptDocument`/`EptScan` and `PtgDocument`/`PtgScan` are the readers behind `PclFile.Open`. Each has a static `Open` method and format-specific properties (for example the E57 version or the FARO scanner model). Their XML documentation states what each reader supports. Prefer `PclFile.Open`, which detects the format and chooses the reader. diff --git a/src/PclIO/Formats/Ptg/PtgDocument.cs b/src/PclIO/Formats/Ptg/PtgDocument.cs new file mode 100644 index 0000000..4fd1d01 --- /dev/null +++ b/src/PclIO/Formats/Ptg/PtgDocument.cs @@ -0,0 +1,92 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; +using PclIO.Internal; + +namespace PclIO.Formats.Ptg; + +/// Represents a Leica Cyclone gridded point cloud file or index dataset (.ptg). +public sealed class PtgDocument : PclDocument +{ + /// + public override PclFileKind Kind => PclFileKind.LeicaPtg; + + /// + public override IReadOnlyList Scans => _scans; + private readonly List _scans = []; + + private PtgDocument(string path, long fileSize) + : base(path, fileSize) + { + } + + /// Opens a PTG binary scan file or ASCII index file. + /// Path to the .ptg file. + /// Read options (currently unused during open; accepted for symmetry). + /// The file or a referenced scan does not exist. + /// The file is malformed, truncated or contains invalid data. + public static PtgDocument Open(string path, PclReadOptions? options = null) + { + var fi = new FileInfo(path); + if (!fi.Exists) throw new FileNotFoundException("PTG file not found.", path); + + var doc = new PtgDocument(path, fi.Length); + + using (var fs = File.OpenRead(path)) + { + Span head = stackalloc byte[8]; + int read = fs.ReadAtLeast(head, 8, throwOnEndOfStream: false); + if (read >= 8 && + head[0] == 0x50 && head[1] == 0x54 && head[2] == 0x47 && head[3] == 0x00 && + BinaryPrimitives.ReadUInt32LittleEndian(head[4..8]) == 0x928FA3C7) + { + var scan = PtgScan.Create(path, "scan-0", Path.GetFileNameWithoutExtension(path)); + doc._scans.Add(scan); + doc._metadata["Format"] = "Leica Cyclone PTG"; + doc._metadata["Scans"] = "1"; + doc._metadata["TotalPoints"] = scan.PointCount.ToString(CultureInfo.InvariantCulture); + return doc; + } + } + + string baseDir = Path.GetDirectoryName(Path.GetFullPath(path))!; + List scanPaths = []; + + using (var reader = new StreamReader(path, Encoding.UTF8)) + { + string? line; + while ((line = reader.ReadLine()) != null) + { + line = line.Trim(); + if (line.Length == 0) continue; + if (line.StartsWith("PTG index", StringComparison.OrdinalIgnoreCase) || + line.StartsWith("---") || line.StartsWith("#") || line.StartsWith("//")) + { + continue; + } + + string scanPath = SafePath.Combine(baseDir, line); + scanPaths.Add(scanPath); + } + } + + if (scanPaths.Count == 0) + throw FormatError.Corrupted("PTG index file contains no scan references."); + + for (int i = 0; i < scanPaths.Count; i++) + { + string sp = scanPaths[i]; + if (!File.Exists(sp)) + throw new FileNotFoundException($"Referenced PTG scan file not found: {sp}", sp); + + var scan = PtgScan.Create(sp, $"scan-{i}", Path.GetFileNameWithoutExtension(sp)); + doc._scans.Add(scan); + } + + doc._metadata["Format"] = "Leica Cyclone PTG"; + doc._metadata["Scans"] = doc._scans.Count.ToString(CultureInfo.InvariantCulture); + doc._metadata["TotalPoints"] = doc.TotalPointCount.ToString(CultureInfo.InvariantCulture); + + return doc; + } +} diff --git a/src/PclIO/Formats/Ptg/PtgHeader.cs b/src/PclIO/Formats/Ptg/PtgHeader.cs new file mode 100644 index 0000000..9b9d9ca --- /dev/null +++ b/src/PclIO/Formats/Ptg/PtgHeader.cs @@ -0,0 +1,266 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; +using PclIO.Internal; + +namespace PclIO.Formats.Ptg; + +/// Parsed metadata and layout information from a Leica PTG binary scan header. +internal sealed class PtgHeader +{ + internal static readonly byte[] Tag = [0x50, 0x54, 0x47, 0x00]; + internal const uint MagicNumber = 0x928FA3C7; + + 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? ScannerModel { get; } + public string? SoftwareName { get; } + public string? Version { get; } + + public bool HasFloatCoordinates => (Properties & 0x01) != 0; + public bool HasDoubleCoordinates => (Properties & 0x02) != 0; + public bool HasIntensity => (Properties & 0x04) != 0; + public bool HasColors => (Properties & 0x08) != 0; + + public int RecordSize => (HasFloatCoordinates ? 12 : 24) + (HasIntensity ? 4 : 0) + (HasColors ? 3 : 0); + + internal PtgHeader( + int numRows, + int numCols, + int properties, + PclTransform transform, + long columnPositionsOffset, + string? scanName, + string? scannerModel, + string? softwareName, + string? version) + { + NumRows = numRows; + NumCols = numCols; + Properties = properties; + Transform = transform; + ColumnPositionsOffset = columnPositionsOffset; + ScanName = scanName; + ScannerModel = scannerModel; + SoftwareName = softwareName; + Version = version; + } + + 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) + throw FormatError.Truncated("PTG 8-byte signature"); + + if (!head[..4].SequenceEqual(Tag)) + throw FormatError.Corrupted("Invalid PTG file tag."); + + 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; + int? numRows = null; + int? numCols = null; + int? properties = null; + List? matrix = null; + string? scanName = null; + string? scannerModel = null; + string? softwareName = null; + string? version = null; + + while ((line = reader.ReadLine()) != null) + { + line = line.Trim(); + if (line.Length == 0) continue; + if (line.StartsWith("%%header_begin", StringComparison.OrdinalIgnoreCase) || + line.StartsWith("header_begin", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + 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; + } + + if (line.StartsWith("%%scanner_model", StringComparison.OrdinalIgnoreCase) || + line.StartsWith("scanner_model", StringComparison.OrdinalIgnoreCase)) + { + scannerModel = ExtractValue(line); + continue; + } + + if (line.StartsWith("%%sw_name", StringComparison.OrdinalIgnoreCase) || + line.StartsWith("sw_name", StringComparison.OrdinalIgnoreCase)) + { + softwareName = ExtractValue(line); + continue; + } + } + + if (!numRows.HasValue) + throw FormatError.Corrupted("Missing NumRows in PTG header."); + if (!numCols.HasValue) + throw FormatError.Corrupted("Missing NumCols in PTG header."); + if (!properties.HasValue) + throw FormatError.Corrupted("Missing properties in PTG header."); + + int rows = numRows.Value; + int cols = numCols.Value; + if (rows <= 0 || cols <= 0) + throw FormatError.Corrupted("PTG dimensions must be positive."); + + if (rows > 100_000 || cols > 100_000 || (long)rows * cols > 1_000_000_000) + throw FormatError.Corrupted("PTG dimensions exceed supported limits."); + + int pVal = properties.Value; + bool hasFloat = (pVal & 0x1) != 0; + bool hasDouble = (pVal & 0x2) != 0; + if (hasFloat == hasDouble) + throw FormatError.Corrupted("PTG properties must specify exactly one of float (0x1) or double (0x2) coordinates."); + + 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; + + return new PtgHeader(rows, cols, pVal, transform, columnPositionsOffset, scanName, scannerModel, softwareName, version); + } + + private static string ExtractValue(string line) + { + 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; + } + + private static void AddDoubles(string text, List values) + { + string[] parts = text.Split([' ', '\t', ','], StringSplitOptions.RemoveEmptyEntries); + foreach (var part in parts) + { + if (!double.TryParse(part, NumberStyles.Float, CultureInfo.InvariantCulture, out double val)) + throw FormatError.Corrupted($"Invalid numeric value in PTG transform: '{part}'."); + if (!double.IsFinite(val)) + throw FormatError.Corrupted("Non-finite numeric value in PTG transform."); + values.Add(val); + } + } +} diff --git a/src/PclIO/Formats/Ptg/PtgScan.cs b/src/PclIO/Formats/Ptg/PtgScan.cs new file mode 100644 index 0000000..ab61d8b --- /dev/null +++ b/src/PclIO/Formats/Ptg/PtgScan.cs @@ -0,0 +1,256 @@ +using System.Buffers.Binary; +using System.Globalization; +using PclIO.Internal; + +namespace PclIO.Formats.Ptg; + +/// Represents a point scan inside a Leica PTG file. +public sealed class PtgScan : PclScan +{ + private readonly string _filePath; + private readonly PtgHeader _header; + private readonly long[] _columnOffsets; + private readonly long _validPointCount; + + /// + public override string Id { get; } + + /// + public override string Name { get; } + + /// + public override long PointCount => _validPointCount; + + /// + public override bool HasColors => _header.HasColors; + + /// + public override bool HasIntensities => _header.HasIntensity; + + /// Number of rows in the scan grid. + public int Rows => _header.NumRows; + + /// Number of columns in the scan grid. + public int Columns => _header.NumCols; + + /// Total number of cells in the scan grid (Rows * Columns). + public long GridSize => (long)_header.NumRows * _header.NumCols; + + internal PtgScan(string filePath, string id, string name, PtgHeader header, long[] columnOffsets, long validPointCount) + { + _filePath = filePath; + _header = header; + _columnOffsets = columnOffsets; + _validPointCount = validPointCount; + Id = id; + Name = name; + Transform = header.Transform; + + _properties["Columns"] = header.NumCols.ToString(CultureInfo.InvariantCulture); + _properties["Rows"] = header.NumRows.ToString(CultureInfo.InvariantCulture); + _properties["GridSize"] = GridSize.ToString(CultureInfo.InvariantCulture); + _properties["ValidPoints"] = validPointCount.ToString(CultureInfo.InvariantCulture); + _properties["CoordinateType"] = header.HasDoubleCoordinates ? "double" : "float"; + _properties["HasIntensity"] = header.HasIntensity ? "true" : "false"; + _properties["HasColors"] = header.HasColors ? "true" : "false"; + + if (!string.IsNullOrEmpty(header.Version)) _properties["Version"] = header.Version; + if (!string.IsNullOrEmpty(header.ScannerModel)) _properties["ScannerModel"] = header.ScannerModel; + if (!string.IsNullOrEmpty(header.SoftwareName)) _properties["SoftwareName"] = header.SoftwareName; + } + + internal static PtgScan Create(string filePath, string id, string? defaultName = null) + { + using var fs = File.OpenRead(filePath); + long fileLength = fs.Length; + if (fileLength < 8) + throw FormatError.Truncated("PTG file signature"); + + var header = PtgHeader.Parse(fs); + + int cols = header.NumCols; + int rows = header.NumRows; + long colTableOffset = header.ColumnPositionsOffset; + long colTableSize = (long)cols * 8; + if (colTableOffset + colTableSize > fileLength) + throw FormatError.Truncated("PTG column offset table"); + + fs.Position = colTableOffset; + byte[] colTableBytes = new byte[colTableSize]; + fs.ReadExactly(colTableBytes); + + long[] colOffsets = new long[cols]; + int maskSize = (rows + 7) / 8; + int recordSize = header.RecordSize; + byte[] maskBuf = new byte[maskSize]; + long totalValid = 0; + + for (int c = 0; c < cols; c++) + { + long off = BinaryPrimitives.ReadInt64LittleEndian(colTableBytes.AsSpan(c * 8, 8)); + if (off < colTableOffset + colTableSize || off > fileLength - maskSize) + throw FormatError.Corrupted($"PTG column {c} offset {off} is invalid."); + + colOffsets[c] = off; + } + + for (int c = 0; c < cols; c++) + { + fs.Position = colOffsets[c]; + fs.ReadExactly(maskBuf); + + int validInCol = 0; + for (int r = 0; r < rows; r++) + { + int bIdx = r >> 3; + int bit = 7 - (r & 7); + if ((maskBuf[bIdx] & (1 << bit)) != 0) + validInCol++; + } + + long dataSize = (long)validInCol * recordSize; + if (colOffsets[c] + maskSize + dataSize > fileLength) + throw FormatError.Truncated($"PTG column {c} data"); + + totalValid += validInCol; + } + + string name = !string.IsNullOrWhiteSpace(header.ScanName) + ? header.ScanName + : (defaultName ?? Path.GetFileNameWithoutExtension(filePath)); + + return new PtgScan(filePath, id, name, header, colOffsets, totalValid); + } + + /// + public override IEnumerable ReadPoints(PclReadOptions? options = null) + { + options ??= PclReadOptions.Default; + long targetCount = options.MaxPoints ?? long.MaxValue; + if (targetCount <= 0 || _validPointCount == 0) yield break; + int step = Math.Max(1, options.SubsampleStep); + + using var fs = File.OpenRead(_filePath); + int rows = _header.NumRows; + int cols = _header.NumCols; + int maskSize = (rows + 7) / 8; + int recordSize = _header.RecordSize; + bool isDouble = _header.HasDoubleCoordinates; + bool hasIntensity = _header.HasIntensity; + bool hasColors = _header.HasColors; + + byte[] maskBuffer = new byte[maskSize]; + byte[]? dataBuffer = null; + + long yielded = 0; + long validPointIndex = 0; + + for (int c = 0; c < cols; c++) + { + long colOffset = _columnOffsets[c]; + fs.Position = colOffset; + + int maskRead = fs.ReadAtLeast(maskBuffer, maskSize, throwOnEndOfStream: false); + if (maskRead < maskSize) + throw FormatError.Truncated($"PTG column {c} bitmask"); + + int validInCol = 0; + for (int r = 0; r < rows; r++) + { + int bIdx = r >> 3; + int bit = 7 - (r & 7); + if ((maskBuffer[bIdx] & (1 << bit)) != 0) + validInCol++; + } + + if (validInCol == 0) continue; + + int colDataBytes = validInCol * recordSize; + if (dataBuffer == null || dataBuffer.Length < colDataBytes) + { + dataBuffer = new byte[colDataBytes]; + } + + int dataRead = fs.Read(dataBuffer, 0, colDataBytes); + if (dataRead < colDataBytes) + throw FormatError.Truncated($"PTG column {c} point records"); + + int recordOffset = 0; + + for (int r = 0; r < rows; r++) + { + int bIdx = r >> 3; + int bit = 7 - (r & 7); + if ((maskBuffer[bIdx] & (1 << bit)) == 0) + continue; + + validPointIndex++; + if ((validPointIndex - 1) % step != 0) + { + recordOffset += recordSize; + continue; + } + + ParseRecord(dataBuffer, recordOffset, isDouble, hasIntensity, hasColors, + out double x, out double y, out double z, out float? intensity, out PclColor? color); + recordOffset += recordSize; + + if (!double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(z)) + continue; + + PclVector3 position = new(x, y, z); + if (options.ApplyTransform && !Transform.IsIdentity) + { + position = Transform.TransformPoint(position); + } + + yield return new PclPoint(position, Color: color, Intensity: intensity, Index: (ulong)yielded); + yielded++; + if (yielded >= targetCount) yield break; + } + } + } + + private static void ParseRecord( + byte[] data, + int offset, + bool isDouble, + bool hasIntensity, + bool hasColors, + out double x, + out double y, + out double z, + out float? intensity, + out PclColor? color) + { + ReadOnlySpan rec = data.AsSpan(offset); + int pos = 0; + if (isDouble) + { + x = BinaryPrimitives.ReadDoubleLittleEndian(rec[pos..]); + y = BinaryPrimitives.ReadDoubleLittleEndian(rec[(pos + 8)..]); + z = BinaryPrimitives.ReadDoubleLittleEndian(rec[(pos + 16)..]); + pos += 24; + } + else + { + x = BinaryPrimitives.ReadSingleLittleEndian(rec[pos..]); + y = BinaryPrimitives.ReadSingleLittleEndian(rec[(pos + 4)..]); + z = BinaryPrimitives.ReadSingleLittleEndian(rec[(pos + 8)..]); + pos += 12; + } + + intensity = null; + if (hasIntensity) + { + intensity = BinaryPrimitives.ReadSingleLittleEndian(rec[pos..]); + pos += 4; + } + + color = null; + if (hasColors) + { + color = new PclColor(rec[pos], rec[pos + 1], rec[pos + 2]); + } + } +} diff --git a/src/PclIO/Internal/KindDetector.cs b/src/PclIO/Internal/KindDetector.cs index 926b3dd..1b645a7 100644 --- a/src/PclIO/Internal/KindDetector.cs +++ b/src/PclIO/Internal/KindDetector.cs @@ -25,6 +25,9 @@ internal static class KindDetector // 3D Tiles point cloud (.pnts) and glTF binary (.glb) signatures. private static readonly byte[] PntsMagic = "pnts"u8.ToArray(); private static readonly byte[] GlbMagic = "glTF"u8.ToArray(); + // Leica PTG binary scan signature and magic number. + private static readonly byte[] PtgTag = [0x50, 0x54, 0x47, 0x00]; + private const uint PtgMagicNumber = 0x928FA3C7; public static PclFileKind Detect(string path) { @@ -119,6 +122,12 @@ public static PclFileKind Detect(Stream stream, string? extension = null) if (read < 4) return extension is ".c3db" or ".c3ptx" ? PclFileKind.EdgeWise : PclFileKind.Unknown; ReadOnlySpan head = buffer[..read]; + if (head.Length >= 8 && head.StartsWith(PtgTag) && BinaryPrimitives.ReadUInt32LittleEndian(head[4..8]) == PtgMagicNumber) + return PclFileKind.LeicaPtg; + + if (extension == ".ptg") + return IsPtgIndexHeader(stream, origin) ? PclFileKind.LeicaPtg : PclFileKind.Unknown; + if (head.StartsWith(E57Magic)) return PclFileKind.E57; @@ -1229,4 +1238,71 @@ private static bool IsEptJsonHeader(Stream stream, long origin, string? extensio stream.Position = origin; } } + + // True when a stream with .ptg extension is an ASCII PTG index file. + private static bool IsPtgIndexHeader(Stream stream, long origin) + { + const int maxProbeBytes = 4096; + long length = stream.CanSeek ? stream.Length : long.MaxValue; + int toRead = (int)Math.Min(maxProbeBytes, Math.Max(0, length - origin)); + if (toRead < 4) return false; + + byte[] buffer = new byte[toRead]; + stream.Position = origin; + try + { + int got = 0; + while (got < toRead) + { + int n = stream.Read(buffer, got, toRead - got); + if (n == 0) break; + got += n; + } + + if (got < 4) return false; + + // Reject binary files (containing NUL bytes) + ReadOnlySpan headSpan = buffer.AsSpan(0, got); + if (headSpan.Contains((byte)0)) return false; + + using var reader = new StreamReader(new MemoryStream(buffer, 0, got), Encoding.UTF8); + string? line; + int lineCount = 0; + bool hasValidIndicator = false; + + while ((line = reader.ReadLine()) != null && lineCount < 32) + { + lineCount++; + line = line.Trim(); + if (line.Length == 0) continue; + + if (line.StartsWith("PTG index", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (line.StartsWith("---") || line.StartsWith("#") || line.StartsWith("//")) + continue; + + if (line.EndsWith(".ptg", StringComparison.OrdinalIgnoreCase)) + { + hasValidIndicator = true; + } + else + { + return false; + } + } + + return hasValidIndicator; + } + catch + { + return false; + } + finally + { + stream.Position = origin; + } + } } diff --git a/src/PclIO/PclFile.cs b/src/PclIO/PclFile.cs index 4eea3bb..387986c 100644 --- a/src/PclIO/PclFile.cs +++ b/src/PclIO/PclFile.cs @@ -10,6 +10,7 @@ using PclIO.Formats.PinPoint; using PclIO.Formats.Ply; using PclIO.Formats.Potree; +using PclIO.Formats.Ptg; using PclIO.Formats.Pts; using PclIO.Formats.Ptx; using PclIO.Formats.Recap; @@ -72,6 +73,7 @@ public static PclDocument Open(string path, PclReadOptions? options = null) PclFileKind.Laz => LazDocument.Open(path, options), PclFileKind.Copc => CopcDocument.Open(path, options), PclFileKind.Ept => EptDocument.Open(path, options), + PclFileKind.LeicaPtg => PtgDocument.Open(path, options), _ => throw new NotSupportedException($"Unsupported or unrecognized point cloud file: '{path}'"), }; } diff --git a/src/PclIO/PclFileKind.cs b/src/PclIO/PclFileKind.cs index aa415c8..4133ee9 100644 --- a/src/PclIO/PclFileKind.cs +++ b/src/PclIO/PclFileKind.cs @@ -65,4 +65,7 @@ public enum PclFileKind /// Entwine Point Tile dataset (ept.json). Ept = 20, + + /// Leica gridded point cloud (.ptg). + LeicaPtg = 21, } diff --git a/tests/PclIO.Tests/FormatTests.cs b/tests/PclIO.Tests/FormatTests.cs index bb8c88e..5049945 100644 --- a/tests/PclIO.Tests/FormatTests.cs +++ b/tests/PclIO.Tests/FormatTests.cs @@ -11,6 +11,7 @@ using PclIO.Formats.PinPoint; using PclIO.Formats.Ply; using PclIO.Formats.Potree; +using PclIO.Formats.Ptg; using PclIO.Formats.Pts; using PclIO.Formats.Ptx; using PclIO.Formats.Recap; @@ -6035,4 +6036,303 @@ public void Ept_Rejects_Truncated_Binary_Tile() using var doc = EptDocument.Open(eptPath); Assert.Throws(() => doc.ReadAllPoints().ToList()); } + + [Fact] + public void Read_Ptg_Binary_Float_With_Intensity_And_Color() + { + using var dir = new TempDirectory(); + var points = new[] + { + new SyntheticFixtures.PtgSamplePoint(1.25, 2.5, 3.75, 0.5f, new PclColor(10, 20, 30)), + new SyntheticFixtures.PtgSamplePoint(4.0, 5.0, 6.0, 0.8f, new PclColor(100, 150, 200)), + }; + byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary( + numCols: 2, numRows: 1, properties: 0x01 | 0x04 | 0x08, points: points, scanName: "StationA"); + + string path = dir.Write("scan.ptg", ptgBytes); + using var doc = PtgDocument.Open(path); + + Assert.Equal(PclFileKind.LeicaPtg, doc.Kind); + Assert.Single(doc.Scans); + var scan = (PtgScan)doc.Scans[0]; + Assert.Equal("StationA", scan.Name); + Assert.Equal(2, scan.Columns); + Assert.Equal(1, scan.Rows); + Assert.Equal(2, scan.GridSize); + Assert.Equal(2, scan.PointCount); + Assert.True(scan.HasColors); + Assert.True(scan.HasIntensities); + + var readPts = scan.ReadPoints().ToList(); + Assert.Equal(2, readPts.Count); + + Assert.Equal(1.25, readPts[0].X, 3); + Assert.Equal(2.5, readPts[0].Y, 3); + Assert.Equal(3.75, readPts[0].Z, 3); + Assert.Equal(0.5f, readPts[0].Intensity); + Assert.Equal(new PclColor(10, 20, 30), readPts[0].Color); + Assert.Equal(0UL, readPts[0].Index); + + Assert.Equal(4.0, readPts[1].X, 3); + Assert.Equal(5.0, readPts[1].Y, 3); + Assert.Equal(6.0, readPts[1].Z, 3); + Assert.Equal(0.8f, readPts[1].Intensity); + Assert.Equal(new PclColor(100, 150, 200), readPts[1].Color); + Assert.Equal(1UL, readPts[1].Index); + } + + [Fact] + public void Read_Ptg_Binary_Double_Coordinates() + { + using var dir = new TempDirectory(); + var points = new[] + { + new SyntheticFixtures.PtgSamplePoint(1234567.89012345, -987654.32109876, 5555.55555555), + }; + byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary( + numCols: 1, numRows: 1, properties: 0x02, points: points); + + string path = dir.Write("double.ptg", ptgBytes); + using var doc = PtgDocument.Open(path); + + var scan = (PtgScan)doc.Scans[0]; + Assert.False(scan.HasColors); + Assert.False(scan.HasIntensities); + Assert.Equal("double", scan.Properties["CoordinateType"]); + + var pt = Assert.Single(scan.ReadPoints()); + Assert.Equal(1234567.89012345, pt.X, 8); + Assert.Equal(-987654.32109876, pt.Y, 8); + Assert.Equal(5555.55555555, pt.Z, 8); + Assert.Null(pt.Intensity); + Assert.Null(pt.Color); + } + + [Fact] + public void Read_Ptg_Binary_With_Missing_Returns() + { + using var dir = new TempDirectory(); + // 2 cols x 2 rows = 4 cells; row 1 of col 0 and row 0 of col 1 are missing + var points = new[] + { + new SyntheticFixtures.PtgSamplePoint(1, 2, 3, IsValid: true), + new SyntheticFixtures.PtgSamplePoint(0, 0, 0, IsValid: false), + new SyntheticFixtures.PtgSamplePoint(0, 0, 0, IsValid: false), + new SyntheticFixtures.PtgSamplePoint(4, 5, 6, IsValid: true), + }; + byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary( + numCols: 2, numRows: 2, properties: 0x01, points: points); + + string path = dir.Write("missing.ptg", ptgBytes); + using var doc = PtgDocument.Open(path); + var scan = doc.Scans[0]; + + Assert.Equal(2, scan.PointCount); + var readPts = scan.ReadPoints().ToList(); + Assert.Equal(2, readPts.Count); + Assert.Equal(1, readPts[0].X); + Assert.Equal(4, readPts[1].X); + } + + [Fact] + public void Read_Ptg_Binary_With_Transform() + { + using var dir = new TempDirectory(); + var points = new[] { new SyntheticFixtures.PtgSamplePoint(1, 2, 3) }; + double[] matrix = + [ + 1, 0, 0, 10, + 0, 1, 0, 20, + 0, 0, 1, 30, + 0, 0, 0, 1 + ]; + byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary( + numCols: 1, numRows: 1, properties: 0x01, points: points, transformMatrix: matrix); + + string path = dir.Write("transformed.ptg", ptgBytes); + using var doc = PtgDocument.Open(path); + var scan = doc.Scans[0]; + + // ApplyTransform = true (default) + var ptTransformed = Assert.Single(scan.ReadPoints()); + Assert.Equal(11, ptTransformed.X, 3); + Assert.Equal(22, ptTransformed.Y, 3); + Assert.Equal(33, ptTransformed.Z, 3); + + // ApplyTransform = false + var ptRaw = Assert.Single(scan.ReadPoints(new PclReadOptions { ApplyTransform = false })); + Assert.Equal(1, ptRaw.X, 3); + Assert.Equal(2, ptRaw.Y, 3); + Assert.Equal(3, ptRaw.Z, 3); + } + + [Fact] + public void Read_Ptg_Binary_Subsampling_And_MaxPoints() + { + using var dir = new TempDirectory(); + var points = new[] + { + new SyntheticFixtures.PtgSamplePoint(1, 0, 0), + new SyntheticFixtures.PtgSamplePoint(2, 0, 0), + new SyntheticFixtures.PtgSamplePoint(3, 0, 0), + new SyntheticFixtures.PtgSamplePoint(4, 0, 0), + }; + byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary( + numCols: 4, numRows: 1, properties: 0x01, points: points); + + string path = dir.Write("options.ptg", ptgBytes); + using var doc = PtgDocument.Open(path); + var scan = doc.Scans[0]; + + // MaxPoints + var limited = scan.ReadPoints(new PclReadOptions { MaxPoints = 2 }).ToList(); + Assert.Equal(2, limited.Count); + Assert.Equal(1, limited[0].X); + Assert.Equal(2, limited[1].X); + + // SubsampleStep + var subsampled = scan.ReadPoints(new PclReadOptions { SubsampleStep = 2 }).ToList(); + Assert.Equal(2, subsampled.Count); + Assert.Equal(1, subsampled[0].X); + Assert.Equal(3, subsampled[1].X); + } + + [Fact] + public void Read_Ptg_Index_MultiScan() + { + using var dir = new TempDirectory(); + byte[] ptg1 = SyntheticFixtures.CreateSyntheticPtgBinary( + numCols: 2, numRows: 1, properties: 0x01, + points: [new(1, 1, 1), new(2, 2, 2)], scanName: "ScanOne"); + byte[] ptg2 = SyntheticFixtures.CreateSyntheticPtgBinary( + numCols: 1, numRows: 1, properties: 0x01, + points: [new(3, 3, 3)], scanName: "ScanTwo"); + + string scanFolder = Path.Combine(dir.Root, "Scans"); + Directory.CreateDirectory(scanFolder); + File.WriteAllBytes(Path.Combine(scanFolder, "scan1.ptg"), ptg1); + File.WriteAllBytes(Path.Combine(scanFolder, "scan2.ptg"), ptg2); + + byte[] idxBytes = SyntheticFixtures.CreateSyntheticPtgIndex( + [@"Scans\scan1.ptg", @"Scans\scan2.ptg"]); + string indexPath = dir.Write("project.ptg", idxBytes); + + using var doc = PtgDocument.Open(indexPath); + Assert.Equal(2, doc.Scans.Count); + Assert.Equal(3, doc.TotalPointCount); + + Assert.Equal("ScanOne", doc.Scans[0].Name); + Assert.Equal(2, doc.Scans[0].PointCount); + + Assert.Equal("ScanTwo", doc.Scans[1].Name); + Assert.Equal(1, doc.Scans[1].PointCount); + + var allPts = doc.ReadAllPoints().ToList(); + Assert.Equal(3, allPts.Count); + Assert.Equal(1, allPts[0].X); + Assert.Equal(2, allPts[1].X); + Assert.Equal(3, allPts[2].X); + } + + [Fact] + public void Read_Ptg_Index_Path_Traversal_Rejected() + { + using var dir = new TempDirectory(); + byte[] idxBytes = SyntheticFixtures.CreateSyntheticPtgIndex(["../../outside.ptg"]); + string indexPath = dir.Write("escape.ptg", idxBytes); + + Assert.Throws(() => PtgDocument.Open(indexPath)); + } + + [Fact] + public void Ptg_Rejects_Corrupt_Magic_Or_Signature() + { + using var dir = new TempDirectory(); + byte[] corruptMagic = SyntheticFixtures.CreateSyntheticPtgBinary(corruptMagic: true); + string path = dir.Write("corrupt.ptg", corruptMagic); + + Assert.Throws(() => PtgScan.Create(path, "scan-0")); + } + + [Fact] + 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); + + Assert.Throws(() => PtgScan.Create(path, "scan-0")); + } + + [Fact] + 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"; + 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"; + 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"; + string path3 = dir.Write("huge.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: huge)); + Assert.Throws(() => PtgScan.Create(path3, "scan-0")); + } + + [Fact] + 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"; + 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"; + 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"; + string path3 = dir.Write("unsupported.ptg", SyntheticFixtures.CreateSyntheticPtgBinary(customHeader: unsupported)); + Assert.Throws(() => PtgScan.Create(path3, "scan-0")); + } + + [Fact] + public void Ptg_Rejects_Corrupt_Offsets_Or_Truncated_Data() + { + using var dir = new TempDirectory(); + // Corrupt offset (points to offset 0) + byte[] badOffset = SyntheticFixtures.CreateSyntheticPtgBinary(corruptOffsets: true); + string path1 = dir.Write("bad_offset.ptg", badOffset); + Assert.Throws(() => PtgScan.Create(path1, "scan-0")); + + // Truncated data + byte[] normal = SyntheticFixtures.CreateSyntheticPtgBinary(); + byte[] truncated = normal[..(normal.Length - 10)]; + string path2 = dir.Write("truncated.ptg", truncated); + Assert.Throws(() => PtgScan.Create(path2, "scan-0")); + } + + [Fact] + public void Ptg_Index_Rejects_Empty_References_Or_Missing_Files() + { + using var dir = new TempDirectory(); + // Empty index + byte[] emptyIdx = SyntheticFixtures.CreateSyntheticPtgIndex([]); + string emptyPath = dir.Write("empty.ptg", emptyIdx); + Assert.Throws(() => PtgDocument.Open(emptyPath)); + + // Missing referenced scan + byte[] missingScanIdx = SyntheticFixtures.CreateSyntheticPtgIndex(["nonexistent.ptg"]); + string missingPath = dir.Write("missing_ref.ptg", missingScanIdx); + Assert.Throws(() => PtgDocument.Open(missingPath)); + } } diff --git a/tests/PclIO.Tests/KindDetectionTests.cs b/tests/PclIO.Tests/KindDetectionTests.cs index 49d4e7c..a79390e 100644 --- a/tests/PclIO.Tests/KindDetectionTests.cs +++ b/tests/PclIO.Tests/KindDetectionTests.cs @@ -491,6 +491,50 @@ public void Detects_Files_On_Disk_The_Same_Way() string badEptFile = eptDir.WriteText("sub/ept.json", "{}"); Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(badEptFile)); Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(Path.GetDirectoryName(badEptFile)!)); + + // PTG binary and index + using var ptgDir = new TempDirectory(); + string ptgBin = ptgDir.Write("scan.ptg", SyntheticFixtures.CreateSyntheticPtgBinary()); + Assert.Equal(PclFileKind.LeicaPtg, PclFile.DetectKind(ptgBin)); + string ptgIdx = ptgDir.Write("index.ptg", SyntheticFixtures.CreateSyntheticPtgIndex(["scan.ptg"])); + Assert.Equal(PclFileKind.LeicaPtg, PclFile.DetectKind(ptgIdx)); + string badPtg = ptgDir.WriteText("bad.ptg", "Not a ptg file"); + Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(badPtg)); + } + + [Fact] + public void Detects_Binary_Ptg_In_Various_Extensions_And_Streams() + { + byte[] ptgBytes = SyntheticFixtures.CreateSyntheticPtgBinary(); + Assert.Equal(PclFileKind.LeicaPtg, Detect(ptgBytes, "scan.ptg")); + Assert.Equal(PclFileKind.LeicaPtg, Detect(ptgBytes, "scan.dat")); + using var ms = new MemoryStream(ptgBytes); + Assert.Equal(PclFileKind.LeicaPtg, PclFile.DetectKind(ms)); + } + + [Fact] + public void Detects_Ascii_Ptg_Index_With_Ptg_Extension() + { + byte[] idxBytes = SyntheticFixtures.CreateSyntheticPtgIndex(["scan1.ptg", "scan2.ptg"]); + Assert.Equal(PclFileKind.LeicaPtg, Detect(idxBytes, "project.ptg")); + // Without .ptg extension, an index file is not LeicaPtg + Assert.NotEqual(PclFileKind.LeicaPtg, Detect(idxBytes, "project.txt")); + } + + [Fact] + public void Rejects_Invalid_Content_With_Ptg_Extension() + { + // Corrupt magic + byte[] corruptMagic = SyntheticFixtures.CreateSyntheticPtgBinary(corruptMagic: true); + Assert.Equal(PclFileKind.Unknown, Detect(corruptMagic, "scan.ptg")); + + // Random binary data + byte[] randomBin = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]; + Assert.Equal(PclFileKind.Unknown, Detect(randomBin, "random.ptg")); + + // Plain text that is not a PTG index + byte[] plainText = "Hello world\nThis is not a ptg"u8.ToArray(); + Assert.Equal(PclFileKind.Unknown, Detect(plainText, "text.ptg")); } private sealed class NonSeekableStream(byte[] bytes) : MemoryStream(bytes) diff --git a/tests/PclIO.Tests/RealFileTests.cs b/tests/PclIO.Tests/RealFileTests.cs index be43c77..06aa577 100644 --- a/tests/PclIO.Tests/RealFileTests.cs +++ b/tests/PclIO.Tests/RealFileTests.cs @@ -95,6 +95,9 @@ private static void AssertReadsPoints(string extension, PclFileKind kind) [SkippableFact] public void Read_Real_Ptx_Points() => AssertReadsPoints(".ptx", PclFileKind.Ptx); + [SkippableFact] + public void Read_Real_Ptg_Points() => AssertReadsPoints(".ptg", PclFileKind.LeicaPtg); + [SkippableFact] public void Read_Real_Xyz_Points() => AssertReadsPoints(".xyz", PclFileKind.Xyz); diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs index dc1094d..9c35ef8 100644 --- a/tests/PclIO.Tests/SyntheticFixtures.cs +++ b/tests/PclIO.Tests/SyntheticFixtures.cs @@ -2764,4 +2764,175 @@ public static (string manifestJson, string hierarchyJson, byte[] dataBytes, stri return (manifestJson, hierarchyJson, tileBytes, ext); } + + public record PtgSamplePoint(double X, double Y, double Z, float? Intensity = null, PclColor? Color = null, bool IsValid = true); + + public static readonly IReadOnlyList DefaultPtgPoints = + [ + new(1.0, 2.0, 3.0, 0.5f, new PclColor(10, 20, 30)), + new(-4.5, 5.25, 6.125, 1.0f, new PclColor(255, 255, 255)), + new(7.0, 8.0, 9.0, 0.2f, new PclColor(100, 150, 200)), + ]; + + public static byte[] CreateSyntheticPtgBinary( + int numCols = 3, + int numRows = 1, + int properties = 0x01 | 0x04 | 0x08, + IReadOnlyList? points = null, + double[]? transformMatrix = null, + string? scanName = "SyntheticScan", + string? customHeader = null, + bool corruptMagic = false, + bool corruptOffsets = false) + { + points ??= DefaultPtgPoints; + + using var ms = new MemoryStream(); + + byte[] tag = corruptMagic ? [0x58, 0x59, 0x5A, 0x00] : [0x50, 0x54, 0x47, 0x00]; + ms.Write(tag); + + uint magic = corruptMagic ? 0x12345678 : 0x928FA3C7; + Span magicBytes = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(magicBytes, magic); + ms.Write(magicBytes); + + byte[] headerBytes; + if (customHeader != null) + { + headerBytes = Encoding.ASCII.GetBytes(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}")); + if (!string.IsNullOrEmpty(scanName)) + sb.AppendLine($"%%scan_name {scanName}"); + + 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]}")); + } + + sb.AppendLine("%%header_end"); + headerBytes = Encoding.ASCII.GetBytes(sb.ToString()); + } + ms.Write(headerBytes); + + int maskSize = (numRows + 7) / 8; + bool isDouble = (properties & 0x02) != 0; + bool hasIntensity = (properties & 0x04) != 0; + bool hasColors = (properties & 0x08) != 0; + + List columnBlocks = []; + long[] colOffsets = new long[numCols]; + + long tableStartOffset = ms.Position; + long tableSize = (long)numCols * 8; + long currentDataOffset = tableStartOffset + tableSize; + + int pointIdx = 0; + Span recordBuf = stackalloc byte[32]; + + for (int c = 0; c < numCols; c++) + { + colOffsets[c] = corruptOffsets ? (c == 0 ? 0 : currentDataOffset) : currentDataOffset; + + byte[] mask = new byte[maskSize]; + using var colDataMs = new MemoryStream(); + + for (int r = 0; r < numRows; r++) + { + var pt = points.Count > 0 ? points[pointIdx % points.Count] : new PtgSamplePoint(0, 0, 0); + pointIdx++; + + if (pt.IsValid) + { + int bIdx = r >> 3; + int bit = 7 - (r & 7); + mask[bIdx] |= (byte)(1 << bit); + + int recPos = 0; + + if (isDouble) + { + BinaryPrimitives.WriteDoubleLittleEndian(recordBuf[recPos..], pt.X); + BinaryPrimitives.WriteDoubleLittleEndian(recordBuf[(recPos + 8)..], pt.Y); + BinaryPrimitives.WriteDoubleLittleEndian(recordBuf[(recPos + 16)..], pt.Z); + recPos += 24; + } + else + { + BinaryPrimitives.WriteSingleLittleEndian(recordBuf[recPos..], (float)pt.X); + BinaryPrimitives.WriteSingleLittleEndian(recordBuf[(recPos + 4)..], (float)pt.Y); + BinaryPrimitives.WriteSingleLittleEndian(recordBuf[(recPos + 8)..], (float)pt.Z); + recPos += 12; + } + + if (hasIntensity) + { + BinaryPrimitives.WriteSingleLittleEndian(recordBuf[recPos..], pt.Intensity ?? 0f); + recPos += 4; + } + + if (hasColors) + { + recordBuf[recPos] = pt.Color?.R ?? 255; + recordBuf[recPos + 1] = pt.Color?.G ?? 255; + recordBuf[recPos + 2] = pt.Color?.B ?? 255; + recPos += 3; + } + + colDataMs.Write(recordBuf[..recPos]); + } + } + + byte[] colBlock = new byte[maskSize + colDataMs.Length]; + Buffer.BlockCopy(mask, 0, colBlock, 0, maskSize); + byte[] ptBytes = colDataMs.ToArray(); + Buffer.BlockCopy(ptBytes, 0, colBlock, maskSize, ptBytes.Length); + + columnBlocks.Add(colBlock); + currentDataOffset += colBlock.Length; + } + + Span offsetBuf = stackalloc byte[8]; + for (int c = 0; c < numCols; c++) + { + BinaryPrimitives.WriteInt64LittleEndian(offsetBuf, colOffsets[c]); + ms.Write(offsetBuf); + } + + foreach (var block in columnBlocks) + { + ms.Write(block); + } + + return ms.ToArray(); + } + + public static byte[] CreateSyntheticPtgIndex( + IEnumerable scanRelativePaths, + string? headerLine = "PTG index file") + { + var sb = new StringBuilder(); + if (headerLine != null) + { + sb.AppendLine(headerLine); + sb.AppendLine("--------------"); + } + foreach (var path in scanRelativePaths) + { + sb.AppendLine(path); + } + return Encoding.UTF8.GetBytes(sb.ToString()); + } }