From 5879ac9a2a0f21ddfa1c9780a39e72b04cce7705 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:08:00 +0000 Subject: [PATCH] Format: EPT (ept.json) (#34) --- CHANGELOG.md | 4 + README.md | 5 +- docs/public-api.md | 8 +- src/PclIO/Formats/Ept/EptDocument.cs | 309 ++++++++++++++++++++++++ src/PclIO/Formats/Ept/EptHierarchy.cs | 95 ++++++++ src/PclIO/Formats/Ept/EptModels.cs | 62 +++++ src/PclIO/Formats/Ept/EptScan.cs | 251 +++++++++++++++++++ src/PclIO/Internal/KindDetector.cs | 76 ++++++ src/PclIO/PclFile.cs | 2 + src/PclIO/PclFileKind.cs | 3 + tests/PclIO.Tests/FormatTests.cs | 277 +++++++++++++++++++++ tests/PclIO.Tests/KindDetectionTests.cs | 40 +++ tests/PclIO.Tests/RealFileTests.cs | 28 +++ tests/PclIO.Tests/SyntheticFixtures.cs | 139 +++++++++++ tests/PclIO.Tests/TestFiles.cs | 4 +- 15 files changed, 1297 insertions(+), 6 deletions(-) create mode 100644 src/PclIO/Formats/Ept/EptDocument.cs create mode 100644 src/PclIO/Formats/Ept/EptHierarchy.cs create mode 100644 src/PclIO/Formats/Ept/EptModels.cs create mode 100644 src/PclIO/Formats/Ept/EptScan.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 09c9e8b..d0bfcfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- 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 - Leica containers that assign their points to their setups now open as one scan per setup, with the id and the name of the diff --git a/README.md b/README.md index 2beabfc..976ea95 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies | Potree | `cloud.js`, `metadata.json`, `.hrc`, `.bin` | Potree octree point cloud datasets: Potree 1.x (`cloud.js` manifest) with Cartesian scaled integer or float coordinates, 8-bit or 16-bit RGB/RGBA colours, float32, spheremapped or oct16p normals, intensities and classifications across node files (`.bin`) and hierarchy (`.hrc`). Potree 2.x (`metadata.json` manifest and `octree.bin` stream) with custom attribute schema layouts. Opening supported from manifest, hierarchy, individual node files, or dataset folders. | | 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. | ### Format detection @@ -62,12 +63,12 @@ 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. + 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 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 other EdgeWise file as a point database. -- A folder is a FARO scan folder, a PinPoint project folder (it holds `ScanProject.json`, or a `.smf` or `.srf` file), a 3D Tiles dataset (it holds `tileset.json`), or a Potree dataset (it holds `cloud.js` or `metadata.json`) by its layout. +- A folder is a FARO scan folder, a PinPoint project folder (it holds `ScanProject.json`, or a `.smf` or `.srf` file), a 3D Tiles dataset (it holds `tileset.json`), a Potree dataset (it holds `cloud.js` or `metadata.json`), or an EPT dataset (it holds `ept.json`) by its layout. So a wrong or damaged file with a recognised extension is reported as unknown, except `.c3db` and `.c3ptx`: those are reported as EdgeWise and fail with `InvalidDataException` when they are opened. A path that is neither a file nor a folder throws diff --git a/docs/public-api.md b/docs/public-api.md index ec599a6..7d06e07 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` and `Copc`. | +| `PclFileKind` | `Unknown`, `E57`, `RecapProject`, `RecapScan`, `LeicaLgsx`, `LeicaLgs`, `FaroFls`, `PinPoint`, `EdgeWise`, `Las`, `Pcd`, `Ply`, `Pts`, `Ptx`, `Xyz`, `Sbf`, `Tiles3d`, `Potree`, `Laz`, `Copc` and `Ept`. | | `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). | @@ -43,12 +43,13 @@ is the argument, which may also be a file name. `Sbf` 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`). `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. - `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 detected as `EdgeWise` and fails with `InvalidDataException` when it is opened. - A folder is `FaroFls` for a FARO scan folder, `PinPoint` when it holds `ScanProject.json`, or a `.smf` or `.srf` file directly - inside it, `Tiles3d` when it holds `tileset.json`, or `Potree` when it holds `cloud.js` or `metadata.json`. + inside it, `Tiles3d` when it holds `tileset.json`, `Potree` when it holds `cloud.js` or `metadata.json`, or `Ept` when it holds `ept.json`. `Open` throws `NotSupportedException` for `Unknown`. For `EdgeWise`, the extension `.c3ptx` selects the single cluster file reader and any other extension the point database reader. @@ -89,6 +90,7 @@ drop points that fail a plausibility rule (see the README), so a scan can yield | Potree | Sum of points across all discovered octree node binary files, or declared in metadata.json. | | 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. | `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 @@ -98,7 +100,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` and `PotreeDocument`/`PotreeScan` 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` and `EptDocument`/`EptScan` 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/Ept/EptDocument.cs b/src/PclIO/Formats/Ept/EptDocument.cs new file mode 100644 index 0000000..8a36e77 --- /dev/null +++ b/src/PclIO/Formats/Ept/EptDocument.cs @@ -0,0 +1,309 @@ +using System.Globalization; +using System.Text.Json; +using PclIO.Internal; + +namespace PclIO.Formats.Ept; + +/// Represents an Entwine Point Tile (EPT) point cloud dataset (ept.json). +public sealed class EptDocument : PclDocument +{ + private const int MaxManifestBytes = 16 * 1024 * 1024; // 16 MB + + /// + public override PclFileKind Kind => PclFileKind.Ept; + + /// Root bounding box of the octree space. + public PclBounds Bounds { get; } + + /// Conforming bounding box tightly encapsulating the points. + public PclBounds BoundsConforming { get; } + + /// Storage data type of the point tiles ("laszip", "binary", or "zstandard"). + public string DataType { get; } + + /// Format of the hierarchy pages ("json"). + public string HierarchyType { get; } + + /// Total point count declared in the manifest. + public long DeclaredPoints { get; } + + /// Voxel tile side dimension in units of points per axis (e.g. 128, 256). + public int Span { get; } + + /// Spatial reference system string (e.g. WKT or EPSG), or null when omitted. + public string? Srs { get; } + + /// EPT specification version string. + public string Version { get; } + + /// Point attribute dimensions declared in the dataset schema. + public IReadOnlyList Schema => _schema; + private readonly List _schema; + + /// Resolved octree nodes containing point records. + public IReadOnlyList Nodes => _nodes; + private readonly List _nodes; + + /// + public override IReadOnlyList Scans => _scans; + private readonly List _scans = []; + private readonly EptScan _primaryScan; + + private EptDocument( + string path, + long fileSize, + string version, + PclBounds bounds, + PclBounds boundsConforming, + string dataType, + string hierarchyType, + long declaredPoints, + int span, + string? srs, + List schema, + List nodes, + long pointCount) + : base(path, fileSize) + { + Version = version; + Bounds = bounds; + BoundsConforming = boundsConforming; + DataType = dataType; + HierarchyType = hierarchyType; + DeclaredPoints = declaredPoints; + Span = span; + Srs = srs; + _schema = schema; + _nodes = nodes; + + _primaryScan = new EptScan( + id: "ept_root", + name: "EPT Octree", + pointCount: pointCount, + bounds: boundsConforming.IsEmpty ? bounds : boundsConforming, + filePath: path, + nodes: nodes, + schema: schema, + dataType: dataType); + _scans.Add(_primaryScan); + + _metadata["Format"] = "Entwine Point Tile (EPT)"; + _metadata["Version"] = version; + _metadata["DataType"] = dataType; + _metadata["HierarchyType"] = hierarchyType; + _metadata["NodeCount"] = nodes.Count.ToString(CultureInfo.InvariantCulture); + _metadata["Span"] = span.ToString(CultureInfo.InvariantCulture); + _metadata["TotalPoints"] = pointCount.ToString(CultureInfo.InvariantCulture); + if (srs != null) _metadata["CoordinateSystem"] = srs; + } + + /// Opens an EPT dataset from a folder, an ept.json manifest, or a file within ept-data. + /// Path to the dataset directory or manifest file. + /// Read options (accepted for symmetry). + /// The path or ept.json cannot be found. + /// The manifest or hierarchy is malformed or truncated. + /// The dataset uses an unsupported data type or feature. + public static EptDocument Open(string path, PclReadOptions? options = null) + { + string manifestPath; + if (Directory.Exists(path)) + { + manifestPath = Path.Combine(path, "ept.json"); + if (!File.Exists(manifestPath)) + throw new FileNotFoundException($"EPT directory does not contain 'ept.json': '{path}'.", manifestPath); + } + else if (File.Exists(path)) + { + string filename = Path.GetFileName(path); + if (string.Equals(filename, "ept.json", StringComparison.OrdinalIgnoreCase) || + string.Equals(Path.GetExtension(path), ".json", StringComparison.OrdinalIgnoreCase)) + { + manifestPath = path; + } + else + { + // Search ancestor directories for companion ept.json + string? dir = Path.GetDirectoryName(Path.GetFullPath(path)); + string? found = null; + for (int depth = 0; depth < 5 && dir != null; depth++) + { + string candidate = Path.Combine(dir, "ept.json"); + if (File.Exists(candidate)) + { + found = candidate; + break; + } + string? parent = Path.GetDirectoryName(dir); + if (parent == dir) break; + dir = parent; + } + + if (found == null) + throw new FileNotFoundException($"Could not find companion 'ept.json' for '{path}'.", path); + manifestPath = found; + } + } + else + { + throw new FileNotFoundException($"EPT file or directory not found: '{path}'.", path); + } + + var fi = new FileInfo(manifestPath); + if (fi.Length > MaxManifestBytes) + throw FormatError.Unsupported($"EPT manifest ({fi.Length} bytes) exceeds safety limit of {MaxManifestBytes} bytes."); + + byte[] jsonBytes = File.ReadAllBytes(manifestPath); + JsonDocument doc; + try + { + doc = JsonDocument.Parse(jsonBytes); + } + catch (JsonException ex) + { + throw FormatError.Corrupted($"Failed to parse EPT manifest JSON: {ex.Message}"); + } + + using (doc) + { + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) + throw FormatError.Corrupted("EPT manifest root must be a JSON object."); + + string version = root.TryGetProperty("version", out var vElem) ? (vElem.GetString() ?? "1.0.0") : "1.0.0"; + + if (!root.TryGetProperty("dataType", out var dtElem) || dtElem.ValueKind != JsonValueKind.String) + throw FormatError.Corrupted("EPT manifest is missing 'dataType' property."); + string dataType = dtElem.GetString() ?? "laszip"; + + if (dataType is not ("laszip" or "binary" or "zstandard")) + throw FormatError.Unsupported($"EPT data type '{dataType}' is not supported; only 'laszip', 'binary', and 'zstandard' are read."); + + string hierarchyType = root.TryGetProperty("hierarchyType", out var htElem) ? (htElem.GetString() ?? "json") : "json"; + long declaredPoints = root.TryGetProperty("points", out var pElem) ? pElem.GetInt64() : 0; + int span = root.TryGetProperty("span", out var spElem) ? spElem.GetInt32() : 256; + + if (!root.TryGetProperty("bounds", out var bElem) || bElem.ValueKind != JsonValueKind.Array || bElem.GetArrayLength() != 6) + throw FormatError.Corrupted("EPT manifest is missing 6-element 'bounds' array."); + + double[] b = new double[6]; + int bIdx = 0; + foreach (var elem in bElem.EnumerateArray()) + { + if (elem.ValueKind != JsonValueKind.Number || !elem.TryGetDouble(out b[bIdx])) + throw FormatError.Corrupted("EPT bounding box coordinates must be finite numbers."); + bIdx++; + } + + var bounds = new PclBounds(new PclVector3(b[0], b[1], b[2]), new PclVector3(b[3], b[4], b[5])); + if (bounds.IsEmpty || !double.IsFinite(bounds.Min.X) || !double.IsFinite(bounds.Min.Y) || !double.IsFinite(bounds.Min.Z) || + !double.IsFinite(bounds.Max.X) || !double.IsFinite(bounds.Max.Y) || !double.IsFinite(bounds.Max.Z)) + throw FormatError.Corrupted("EPT bounding box coordinates must be finite."); + + PclBounds boundsConforming = bounds; + if (root.TryGetProperty("boundsConforming", out var bcElem) && bcElem.ValueKind == JsonValueKind.Array && bcElem.GetArrayLength() == 6) + { + double[] bc = new double[6]; + int bcIdx = 0; + bool valid = true; + foreach (var elem in bcElem.EnumerateArray()) + { + if (elem.ValueKind != JsonValueKind.Number || !elem.TryGetDouble(out bc[bcIdx++])) + { + valid = false; + break; + } + } + if (valid) + { + var cBounds = new PclBounds(new PclVector3(bc[0], bc[1], bc[2]), new PclVector3(bc[3], bc[4], bc[5])); + if (!cBounds.IsEmpty) boundsConforming = cBounds; + } + } + + if (!root.TryGetProperty("schema", out var sElem) || sElem.ValueKind != JsonValueKind.Array) + throw FormatError.Corrupted("EPT manifest is missing 'schema' array."); + + var schema = new List(); + foreach (var dimElem in sElem.EnumerateArray()) + { + if (dimElem.ValueKind != JsonValueKind.Object) continue; + string name = dimElem.TryGetProperty("name", out var nElem) ? (nElem.GetString() ?? "") : ""; + string type = dimElem.TryGetProperty("type", out var tElem) ? (tElem.GetString() ?? "unsigned") : "unsigned"; + int size = dimElem.TryGetProperty("size", out var szElem) ? szElem.GetInt32() : 4; + double scale = dimElem.TryGetProperty("scale", out var scElem) ? scElem.GetDouble() : 1.0; + double offset = dimElem.TryGetProperty("offset", out var offElem) ? offElem.GetDouble() : 0.0; + if (!string.IsNullOrEmpty(name)) + schema.Add(new EptDimension(name, type, size, scale, offset)); + } + + if (!schema.Any(d => d.Name.Equals("X", StringComparison.OrdinalIgnoreCase)) || + !schema.Any(d => d.Name.Equals("Y", StringComparison.OrdinalIgnoreCase)) || + !schema.Any(d => d.Name.Equals("Z", StringComparison.OrdinalIgnoreCase))) + { + throw FormatError.Corrupted("EPT schema must declare X, Y, and Z dimensions."); + } + + string? srs = null; + if (root.TryGetProperty("srs", out var srsElem)) + { + if (srsElem.ValueKind == JsonValueKind.String) + srs = srsElem.GetString(); + else if (srsElem.ValueKind == JsonValueKind.Object) + { + if (srsElem.TryGetProperty("wkt", out var wktElem) && wktElem.ValueKind == JsonValueKind.String) + srs = wktElem.GetString(); + else if (srsElem.TryGetProperty("horizontal", out var hElem) && hElem.ValueKind == JsonValueKind.String) + srs = hElem.GetString(); + } + } + + string datasetDir = Path.GetDirectoryName(Path.GetFullPath(manifestPath)) ?? ""; + var nodes = EptHierarchy.ReadHierarchy(datasetDir, bounds, dataType); + + long pointCount = declaredPoints > 0 ? declaredPoints : nodes.Where(n => n.PointCount > 0).Sum(n => n.PointCount); + + return new EptDocument( + manifestPath, + fi.Length, + version, + bounds, + boundsConforming, + dataType, + hierarchyType, + declaredPoints, + span, + srs, + schema, + nodes, + pointCount); + } + } + + /// Finds octree nodes whose voxel bounding box intersects the given spatial bounds. + /// Query bounding box. + /// Optional maximum octree depth to include. + public IReadOnlyList FindNodes(PclBounds bounds, int? maxDepth = null) + { + if (bounds.IsEmpty) return Array.Empty(); + return _nodes + .Where(n => (maxDepth == null || n.Key.Depth <= maxDepth.Value) && n.Bounds.Intersects(bounds)) + .ToList(); + } + + /// Streams points from a single octree node. + /// The octree node to read points from. + /// Read options (subsampling, limits, transforms). + public IEnumerable ReadPoints(EptNode node, PclReadOptions? options = null) + { + return _primaryScan.ReadPointsFromNodes([node], options); + } + + /// Streams points from octree nodes intersecting the given bounding box. + /// Spatial bounding box filter. + /// Read options (subsampling, limits, transforms). + public IEnumerable ReadPoints(PclBounds bounds, PclReadOptions? options = null) + { + var matchingNodes = FindNodes(bounds); + return _primaryScan.ReadPointsFromNodes(matchingNodes, options); + } +} diff --git a/src/PclIO/Formats/Ept/EptHierarchy.cs b/src/PclIO/Formats/Ept/EptHierarchy.cs new file mode 100644 index 0000000..43fb303 --- /dev/null +++ b/src/PclIO/Formats/Ept/EptHierarchy.cs @@ -0,0 +1,95 @@ +using System.Text.Json; +using PclIO.Internal; + +namespace PclIO.Formats.Ept; + +/// Discovers and traverses the octree hierarchy of an Entwine Point Tile dataset. +internal static class EptHierarchy +{ + private const int MaxHierarchyPages = 10000; + private const int MaxPageBytes = 16 * 1024 * 1024; // 16 MB max per hierarchy JSON + + public static List ReadHierarchy(string datasetDir, PclBounds rootBounds, string dataType) + { + string ext = dataType.ToLowerInvariant() switch + { + "laszip" => ".laz", + "binary" => ".bin", + "zstandard" => ".zst", + _ => ".laz" + }; + + var nodes = new List(); + string hierDir = Path.Combine(datasetDir, "ept-hierarchy"); + string dataDir = Path.Combine(datasetDir, "ept-data"); + + if (Directory.Exists(hierDir)) + { + string rootHierFile = Path.Combine(hierDir, "0-0-0-0.json"); + if (File.Exists(rootHierFile)) + { + var pagesToRead = new Queue(); + var visited = new HashSet(StringComparer.Ordinal); + pagesToRead.Enqueue("0-0-0-0"); + + while (pagesToRead.Count > 0) + { + string pageKey = pagesToRead.Dequeue(); + if (!visited.Add(pageKey)) + throw FormatError.Corrupted($"Cyclic EPT hierarchy reference detected at node '{pageKey}'."); + + if (visited.Count > MaxHierarchyPages) + throw FormatError.Corrupted($"EPT hierarchy exceeds safety limit of {MaxHierarchyPages} pages."); + + string pagePath = Path.Combine(hierDir, pageKey + ".json"); + if (!File.Exists(pagePath)) continue; + + var fi = new FileInfo(pagePath); + if (fi.Length > MaxPageBytes) + throw FormatError.Corrupted($"EPT hierarchy file '{pageKey}.json' exceeds size limit of {MaxPageBytes} bytes."); + + byte[] pageBytes = File.ReadAllBytes(pagePath); + using var doc = JsonDocument.Parse(pageBytes); + if (doc.RootElement.ValueKind != JsonValueKind.Object) + throw FormatError.Corrupted($"EPT hierarchy page '{pageKey}.json' must be a JSON object."); + + foreach (var prop in doc.RootElement.EnumerateObject()) + { + string nodeKeyStr = prop.Name; + long count = prop.Value.GetInt64(); + + if (!EptKey.TryParse(nodeKeyStr, out var nodeKey)) continue; + + if (count > 0) + { + var bounds = nodeKey.GetBounds(rootBounds); + string tilePath = Path.Combine(dataDir, nodeKeyStr + ext); + nodes.Add(new EptNode(nodeKey, bounds, File.Exists(tilePath) ? tilePath : null, count)); + } + else if (count == -1) + { + pagesToRead.Enqueue(nodeKeyStr); + } + } + } + } + } + + // If no nodes discovered from ept-hierarchy, fall back to enumerating tiles in ept-data + if (nodes.Count == 0 && Directory.Exists(dataDir)) + { + var files = Directory.EnumerateFiles(dataDir, "*" + ext, SearchOption.AllDirectories); + foreach (string file in files) + { + string baseName = Path.GetFileNameWithoutExtension(file); + if (EptKey.TryParse(baseName, out var nodeKey)) + { + var bounds = nodeKey.GetBounds(rootBounds); + nodes.Add(new EptNode(nodeKey, bounds, file, -1)); + } + } + } + + return nodes; + } +} diff --git a/src/PclIO/Formats/Ept/EptModels.cs b/src/PclIO/Formats/Ept/EptModels.cs new file mode 100644 index 0000000..52ad9a3 --- /dev/null +++ b/src/PclIO/Formats/Ept/EptModels.cs @@ -0,0 +1,62 @@ +using System.Globalization; + +namespace PclIO.Formats.Ept; + +/// Identifies an octree node in an Entwine Point Tile hierarchy by depth and 3D integer indices. +/// Octree tree depth (0 is root). +/// Voxel integer X index at this depth. +/// Voxel integer Y index at this depth. +/// Voxel integer Z index at this depth. +public readonly record struct EptKey(int Depth, int X, int Y, int Z) +{ + /// Parses an EPT key string formatted as "depth-x-y-z". + public static bool TryParse(string s, out EptKey key) + { + key = default; + if (string.IsNullOrWhiteSpace(s)) return false; + string[] parts = s.Split('-'); + if (parts.Length != 4) return false; + + if (!int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int d) || d < 0) return false; + if (!int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int x) || x < 0) return false; + if (!int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int y) || y < 0) return false; + if (!int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int z) || z < 0) return false; + + key = new EptKey(d, x, y, z); + return true; + } + + /// Calculates the axis-aligned spatial bounding box of this voxel from the root bounding box. + public PclBounds GetBounds(PclBounds rootBounds) + { + if (Depth < 0 || rootBounds.IsEmpty) return PclBounds.Empty; + double divisor = Math.Pow(2.0, Depth); + double stepX = rootBounds.Size.X / divisor; + double stepY = rootBounds.Size.Y / divisor; + double stepZ = rootBounds.Size.Z / divisor; + + double minX = rootBounds.Min.X + (X * stepX); + double minY = rootBounds.Min.Y + (Y * stepY); + double minZ = rootBounds.Min.Z + (Z * stepZ); + + return new PclBounds(new PclVector3(minX, minY, minZ), new PclVector3(minX + stepX, minY + stepY, minZ + stepZ)); + } + + /// + public override string ToString() => $"{Depth}-{X}-{Y}-{Z}"; +} + +/// Represents a point attribute dimension declared in the EPT schema. +/// Dimension name (e.g. "X", "Y", "Z", "Intensity", "Red", "Green", "Blue"). +/// Data type ("signed", "unsigned", or "float"). +/// Byte size of the field (1, 2, 4, or 8). +/// Coordinate scale factor applied to raw values. +/// Coordinate offset added to scaled values. +public sealed record EptDimension(string Name, string Type, int Size, double Scale = 1.0, double Offset = 0.0); + +/// Represents a resolved node in an EPT octree dataset. +/// Voxel key identifying the node in the octree. +/// Spatial bounding box of the node voxel. +/// Absolute or relative file path to the node data file. +/// Number of points in this node tile. +public sealed record EptNode(EptKey Key, PclBounds Bounds, string? DataPath, long PointCount); diff --git a/src/PclIO/Formats/Ept/EptScan.cs b/src/PclIO/Formats/Ept/EptScan.cs new file mode 100644 index 0000000..0f61010 --- /dev/null +++ b/src/PclIO/Formats/Ept/EptScan.cs @@ -0,0 +1,251 @@ +using PclIO.Formats.Laz; +using PclIO.Internal; + +namespace PclIO.Formats.Ept; + +/// Streams points from an Entwine Point Tile (EPT) octree dataset. +public sealed class EptScan : PclScan +{ + private const int MaxTileMemory = 64 * 1024 * 1024; // 64 MB max per tile + + /// + public override string Id { get; } + + /// + public override string Name { get; } + + /// + public override long PointCount { get; } + + /// Path to the EPT manifest file. + public string FilePath { get; } + + /// + public override bool HasColors { get; } + + /// + public override bool HasIntensities { get; } + + /// + public override bool HasNormals { get; } + + private readonly IReadOnlyList _nodes; + private readonly IReadOnlyList _schema; + private readonly string _dataType; + + internal EptScan( + string id, + string name, + long pointCount, + PclBounds bounds, + string filePath, + IReadOnlyList nodes, + IReadOnlyList schema, + string dataType) + { + Id = id; + Name = name; + PointCount = pointCount; + Bounds = bounds; + FilePath = filePath; + _nodes = nodes; + _schema = schema; + _dataType = dataType.ToLowerInvariant(); + + HasColors = schema.Any(d => d.Name is "Red" or "COLOR_0") || _dataType == "laszip"; + HasIntensities = schema.Any(d => d.Name is "Intensity") || _dataType == "laszip"; + HasNormals = schema.Any(d => d.Name is "NormalX" or "Normal"); + } + + /// + public override IEnumerable ReadPoints(PclReadOptions? options = null) + { + return ReadPointsFromNodes(_nodes, options); + } + + /// Streams points from the specified octree nodes. + internal IEnumerable ReadPointsFromNodes(IEnumerable nodes, PclReadOptions? options = null) + { + options ??= PclReadOptions.Default; + long targetCount = options.MaxPoints ?? PointCount; + if (targetCount <= 0 || PointCount <= 0) yield break; + targetCount = Math.Min(targetCount, PointCount); + int step = Math.Max(1, options.SubsampleStep); + + long yielded = 0; + long globalIndex = 0; + + // Resolve schema layout offsets for binary / zstandard streams + int recordSize = _schema.Sum(d => d.Size); + int xOff = -1, yOff = -1, zOff = -1; + int intOff = -1, classOff = -1; + int redOff = -1, greenOff = -1, blueOff = -1; + int nxOff = -1, nyOff = -1, nzOff = -1; + + EptDimension? xDim = null, yDim = null, zDim = null; + EptDimension? intDim = null, classDim = null; + EptDimension? redDim = null, greenDim = null, blueDim = null; + EptDimension? nxDim = null, nyDim = null, nzDim = null; + + int curOff = 0; + foreach (var dim in _schema) + { + string name = dim.Name.ToLowerInvariant(); + if (name is "x" or "pos_x") { xOff = curOff; xDim = dim; } + else if (name is "y" or "pos_y") { yOff = curOff; yDim = dim; } + else if (name is "z" or "pos_z") { zOff = curOff; zDim = dim; } + else if (name is "intensity") { intOff = curOff; intDim = dim; } + else if (name is "classification") { classOff = curOff; classDim = dim; } + else if (name is "red") { redOff = curOff; redDim = dim; } + else if (name is "green") { greenOff = curOff; greenDim = dim; } + else if (name is "blue") { blueOff = curOff; blueDim = dim; } + else if (name is "normalx") { nxOff = curOff; nxDim = dim; } + else if (name is "normaly") { nyOff = curOff; nyDim = dim; } + else if (name is "normalz") { nzOff = curOff; nzDim = dim; } + + curOff += dim.Size; + } + + foreach (var node in nodes) + { + if (node.DataPath == null || !File.Exists(node.DataPath)) continue; + + if (_dataType == "laszip") + { + using var lazDoc = LazDocument.Open(node.DataPath); + foreach (var p in lazDoc.ReadAllPoints()) + { + if (globalIndex % step == 0) + { + var pt = p with { Index = (ulong)yielded }; + if (options.ApplyTransform) + pt = pt with { Position = Transform.TransformPoint(pt.Position) }; + + yield return pt; + yielded++; + if (yielded >= targetCount) yield break; + } + globalIndex++; + } + } + else + { + // Binary or Zstandard point stream + byte[] dataBytes; + if (_dataType == "zstandard") + { + byte[] zstBytes = File.ReadAllBytes(node.DataPath); + if (zstBytes.Length > MaxTileMemory) + throw FormatError.Corrupted($"EPT zstandard tile '{node.DataPath}' exceeds memory limit."); + dataBytes = ZstdDecoder.Decompress(zstBytes, MaxTileMemory); + } + else + { + var fi = new FileInfo(node.DataPath); + if (fi.Length > MaxTileMemory) + throw FormatError.Corrupted($"EPT binary tile '{node.DataPath}' exceeds memory limit."); + dataBytes = File.ReadAllBytes(node.DataPath); + } + + if (recordSize <= 0) continue; + if (dataBytes.Length % recordSize != 0) + throw FormatError.Truncated($"EPT tile '{node.DataPath}' size {dataBytes.Length} is not a multiple of point record size {recordSize}."); + + int tilePoints = dataBytes.Length / recordSize; + for (int i = 0; i < tilePoints; i++) + { + int recStart = i * recordSize; + var rec = dataBytes.AsSpan(recStart, recordSize); + + if (xDim == null || yDim == null || zDim == null) continue; + + double x = ReadDimValue(rec.Slice(xOff, xDim.Size), xDim); + double y = ReadDimValue(rec.Slice(yOff, yDim.Size), yDim); + double z = ReadDimValue(rec.Slice(zOff, zDim.Size), zDim); + + if (double.IsFinite(x) && double.IsFinite(y) && double.IsFinite(z)) + { + if (globalIndex % step == 0) + { + float? intensity = null; + if (intDim != null) + { + double rawInt = ReadDimValue(rec.Slice(intOff, intDim.Size), intDim); + intensity = (float)(rawInt / (intDim.Size == 1 ? 255.0 : 65535.0)); + } + + byte? classification = null; + if (classDim != null) + { + classification = (byte)ReadDimValue(rec.Slice(classOff, classDim.Size), classDim); + } + + PclColor? color = null; + if (redDim != null && greenDim != null && blueDim != null) + { + double rVal = ReadDimValue(rec.Slice(redOff, redDim.Size), redDim); + double gVal = ReadDimValue(rec.Slice(greenOff, greenDim.Size), greenDim); + double bVal = ReadDimValue(rec.Slice(blueOff, blueDim.Size), blueDim); + byte r = (byte)(redDim.Size == 2 ? Math.Clamp(rVal / 257.0, 0, 255) : Math.Clamp(rVal, 0, 255)); + byte g = (byte)(greenDim.Size == 2 ? Math.Clamp(gVal / 257.0, 0, 255) : Math.Clamp(gVal, 0, 255)); + byte b = (byte)(blueDim.Size == 2 ? Math.Clamp(bVal / 257.0, 0, 255) : Math.Clamp(bVal, 0, 255)); + color = new PclColor(r, g, b); + } + + PclVector3? normal = null; + if (nxDim != null && nyDim != null && nzDim != null) + { + double nx = ReadDimValue(rec.Slice(nxOff, nxDim.Size), nxDim); + double ny = ReadDimValue(rec.Slice(nyOff, nyDim.Size), nyDim); + double nz = ReadDimValue(rec.Slice(nzOff, nzDim.Size), nzDim); + normal = new PclVector3(nx, ny, nz); + } + + var pt = new PclPoint(new PclVector3(x, y, z), Color: color, Intensity: intensity, + Normal: normal, Classification: classification, Index: (ulong)yielded); + if (options.ApplyTransform) + pt = pt with { Position = Transform.TransformPoint(pt.Position) }; + + yield return pt; + yielded++; + if (yielded >= targetCount) yield break; + } + } + globalIndex++; + } + } + } + } + + private static double ReadDimValue(ReadOnlySpan span, EptDimension dim) + { + double raw = dim.Type switch + { + "signed" => dim.Size switch + { + 1 => (sbyte)span[0], + 2 => Bytes.ReadInt16LE(span), + 4 => Bytes.ReadInt32LE(span), + 8 => Bytes.ReadInt64LE(span), + _ => 0 + }, + "unsigned" => dim.Size switch + { + 1 => span[0], + 2 => Bytes.ReadUInt16LE(span), + 4 => Bytes.ReadUInt32LE(span), + 8 => Bytes.ReadUInt64LE(span), + _ => 0 + }, + "float" => dim.Size switch + { + 4 => Bytes.ReadSingleLE(span), + 8 => Bytes.ReadDoubleLE(span), + _ => 0 + }, + _ => 0 + }; + + return (raw * dim.Scale) + dim.Offset; + } +} diff --git a/src/PclIO/Internal/KindDetector.cs b/src/PclIO/Internal/KindDetector.cs index b091664..926b3dd 100644 --- a/src/PclIO/Internal/KindDetector.cs +++ b/src/PclIO/Internal/KindDetector.cs @@ -1,5 +1,6 @@ using System.Buffers.Binary; using System.Globalization; +using System.Text; using System.Text.Json; namespace PclIO.Internal; @@ -51,12 +52,27 @@ public static PclFileKind Detect(string path) return PclFileKind.Potree; } + string eptPath = Path.Combine(path, "ept.json"); + if (File.Exists(eptPath)) + { + using var s = File.OpenRead(eptPath); + if (IsEptJsonHeader(s, 0, "ept.json")) + return PclFileKind.Ept; + } + return PclFileKind.Unknown; } if (!File.Exists(path)) throw new FileNotFoundException($"Point cloud file not found: {path}", path); + string filename = Path.GetFileName(path).ToLowerInvariant(); + if (filename == "ept.json") + { + using var s = File.OpenRead(path); + return IsEptJsonHeader(s, 0, "ept.json") ? PclFileKind.Ept : PclFileKind.Unknown; + } + string ext = path.EndsWith(".copc.laz", StringComparison.OrdinalIgnoreCase) ? ".copc.laz" : Path.GetExtension(path).ToLowerInvariant(); @@ -188,6 +204,10 @@ public static PclFileKind Detect(Stream stream, string? extension = null) if (IsPotreeHrcHeader(stream, origin, extension)) return PclFileKind.Potree; + // Entwine Point Tile dataset manifest (ept.json). + if (IsEptJsonHeader(stream, origin, extension)) + return PclFileKind.Ept; + return PclFileKind.Unknown; } @@ -1153,4 +1173,60 @@ private static bool IsPotreeHrcHeader(Stream stream, long origin, string? extens stream.Position = origin; } } + + // Entwine Point Tile manifest (ept.json). + private static bool IsEptJsonHeader(Stream stream, long origin, string? extension) + { + if (extension != null && extension != ".json" && !extension.EndsWith("ept.json", StringComparison.OrdinalIgnoreCase)) + return false; + + long length = stream.CanSeek ? stream.Length : long.MaxValue; + if (length - origin < 10) return false; + + int toRead = (int)Math.Min(65536, length - origin); + byte[] buf = new byte[toRead]; + stream.Position = origin; + try + { + int got = stream.ReadAtLeast(buf, toRead, throwOnEndOfStream: false); + if (got < 10) return false; + + int start = 0; + if (got >= 3 && buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF) + start = 3; + while (start < got && char.IsWhiteSpace((char)buf[start])) + start++; + + if (start >= got || buf[start] != (byte)'{') + return false; + + if (length - origin <= toRead) + { + using var doc = JsonDocument.Parse(buf.AsMemory(start, got - start)); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return false; + + return root.TryGetProperty("bounds", out var bElem) && bElem.ValueKind == JsonValueKind.Array && bElem.GetArrayLength() == 6 && + root.TryGetProperty("dataType", out var dtElem) && dtElem.ValueKind == JsonValueKind.String && + dtElem.GetString() is "laszip" or "binary" or "zstandard" && + root.TryGetProperty("schema", out var sElem) && sElem.ValueKind == JsonValueKind.Array; + } + else + { + string text = Encoding.UTF8.GetString(buf, start, got - start); + return text.Contains("\"bounds\"") && + text.Contains("\"dataType\"") && + (text.Contains("\"laszip\"") || text.Contains("\"binary\"") || text.Contains("\"zstandard\"")) && + text.Contains("\"schema\""); + } + } + catch + { + return false; + } + finally + { + stream.Position = origin; + } + } } diff --git a/src/PclIO/PclFile.cs b/src/PclIO/PclFile.cs index 01a2909..4eea3bb 100644 --- a/src/PclIO/PclFile.cs +++ b/src/PclIO/PclFile.cs @@ -1,6 +1,7 @@ using PclIO.Formats.Copc; using PclIO.Formats.E57; using PclIO.Formats.EdgeWise; +using PclIO.Formats.Ept; using PclIO.Formats.Faro; using PclIO.Formats.Las; using PclIO.Formats.Laz; @@ -70,6 +71,7 @@ public static PclDocument Open(string path, PclReadOptions? options = null) PclFileKind.Potree => PotreeDocument.Open(path, options), PclFileKind.Laz => LazDocument.Open(path, options), PclFileKind.Copc => CopcDocument.Open(path, options), + PclFileKind.Ept => EptDocument.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 1b1b22f..aa415c8 100644 --- a/src/PclIO/PclFileKind.cs +++ b/src/PclIO/PclFileKind.cs @@ -62,4 +62,7 @@ public enum PclFileKind /// Cloud Optimized Point Cloud (clustered octree in LAZ, .copc.laz). Copc = 19, + + /// Entwine Point Tile dataset (ept.json). + Ept = 20, } diff --git a/tests/PclIO.Tests/FormatTests.cs b/tests/PclIO.Tests/FormatTests.cs index d1e33e7..bb8c88e 100644 --- a/tests/PclIO.Tests/FormatTests.cs +++ b/tests/PclIO.Tests/FormatTests.cs @@ -2,6 +2,7 @@ using PclIO.Formats.Copc; using PclIO.Formats.E57; using PclIO.Formats.EdgeWise; +using PclIO.Formats.Ept; using PclIO.Formats.Faro; using PclIO.Formats.Las; using PclIO.Formats.Laz; @@ -5758,4 +5759,280 @@ public void Copc_Rejects_Truncated_Data_With_InvalidDataException() Assert.Throws(() => CopcDocument.Open(path)); } + + // ---- Entwine Point Tile (EPT) tests ------------------------------------------------------------------- + + [Fact] + public void Ept_Opens_Lists_Scans_And_Streams_Points() + { + using var dir = new TempDirectory(); + var points = new EptSamplePoint[] + { + new(10.0, 20.0, 30.0, new PclColor(255, 0, 0), Intensity: 0.5f, Classification: 2), + new(11.0, 21.0, 31.0, new PclColor(0, 255, 0), Intensity: 0.8f, Classification: 1), + new(12.0, 22.0, 32.0, new PclColor(0, 0, 255), Intensity: 1.0f, Classification: 3), + }; + + var (manifest, hier, data, ext) = SyntheticFixtures.CreateSyntheticEpt(points, dataType: "binary"); + string eptPath = dir.WriteText("ept.json", manifest); + dir.WriteText("ept-hierarchy/0-0-0-0.json", hier); + string dataPath = dir.Write($"ept-data/0-0-0-0.{ext}", data); + + // Open via ept.json + using var docFile = EptDocument.Open(eptPath); + Assert.Equal(PclFileKind.Ept, docFile.Kind); + Assert.Equal("1.0.0", docFile.Version); + Assert.Equal("binary", docFile.DataType); + Assert.Equal(128, docFile.Span); + Assert.Equal(3, docFile.DeclaredPoints); + Assert.Single(docFile.Scans); + Assert.Single(docFile.Nodes); + Assert.Equal(3, docFile.TotalPointCount); + + // Open via directory + using var docDir = PclFile.Open(dir.Root); + Assert.Equal(PclFileKind.Ept, docDir.Kind); + Assert.Equal(3, docDir.TotalPointCount); + + // Open via tile path (ancestor search) + using var docTile = EptDocument.Open(dataPath); + Assert.Equal(PclFileKind.Ept, docTile.Kind); + + // Read points + var readPoints = docFile.ReadAllPoints().ToList(); + Assert.Equal(3, readPoints.Count); + + Assert.Equal(10.0, readPoints[0].X, Precision); + Assert.Equal(20.0, readPoints[0].Y, Precision); + Assert.Equal(30.0, readPoints[0].Z, Precision); + Assert.Equal(new PclColor(255, 0, 0), readPoints[0].Color); + Assert.Equal((byte)2, readPoints[0].Classification); + + Assert.Equal(11.0, readPoints[1].X, Precision); + Assert.Equal(21.0, readPoints[1].Y, Precision); + Assert.Equal(31.0, readPoints[1].Z, Precision); + Assert.Equal(new PclColor(0, 255, 0), readPoints[1].Color); + Assert.Equal((byte)1, readPoints[1].Classification); + } + + [Fact] + public void Ept_Reads_Laszip_Data() + { + using var dir = new TempDirectory(); + var points = new EptSamplePoint[] + { + new(5.0, 10.0, 15.0, new PclColor(128, 64, 32), Intensity: 0.5f, Classification: 1), + }; + + var (manifest, hier, data, ext) = SyntheticFixtures.CreateSyntheticEpt(points, dataType: "laszip"); + string eptPath = dir.WriteText("ept.json", manifest); + dir.WriteText("ept-hierarchy/0-0-0-0.json", hier); + dir.Write($"ept-data/0-0-0-0.{ext}", data); + + using var doc = EptDocument.Open(eptPath); + Assert.Equal("laszip", doc.DataType); + var readPoints = doc.ReadAllPoints().ToList(); + Assert.Single(readPoints); + Assert.Equal(5.0, readPoints[0].X, 0.01); + Assert.Equal(10.0, readPoints[0].Y, 0.01); + Assert.Equal(15.0, readPoints[0].Z, 0.01); + } + + [Fact] + public void Ept_Reads_Zstandard_Data() + { + using var dir = new TempDirectory(); + var points = new EptSamplePoint[] + { + new(100.0, 200.0, 300.0, new PclColor(10, 20, 30), Intensity: 0.75f, Classification: 5), + new(105.0, 205.0, 305.0, new PclColor(40, 50, 60), Intensity: 0.25f, Classification: 6), + }; + + var (manifest, hier, data, ext) = SyntheticFixtures.CreateSyntheticEpt(points, dataType: "zstandard"); + string eptPath = dir.WriteText("ept.json", manifest); + dir.WriteText("ept-hierarchy/0-0-0-0.json", hier); + dir.Write($"ept-data/0-0-0-0.{ext}", data); + + using var doc = EptDocument.Open(eptPath); + Assert.Equal("zstandard", doc.DataType); + var readPoints = doc.ReadAllPoints().ToList(); + Assert.Equal(2, readPoints.Count); + Assert.Equal(100.0, readPoints[0].X, Precision); + Assert.Equal(200.0, readPoints[0].Y, Precision); + Assert.Equal(300.0, readPoints[0].Z, Precision); + Assert.Equal(new PclColor(10, 20, 30), readPoints[0].Color); + Assert.Equal((byte)5, readPoints[0].Classification); + + Assert.Equal(105.0, readPoints[1].X, Precision); + Assert.Equal(205.0, readPoints[1].Y, Precision); + Assert.Equal(305.0, readPoints[1].Z, Precision); + Assert.Equal(new PclColor(40, 50, 60), readPoints[1].Color); + Assert.Equal((byte)6, readPoints[1].Classification); + } + + [Fact] + public void Ept_Spatial_Queries_FindNodes_And_ReadPoints() + { + using var dir = new TempDirectory(); + var rootBounds = new PclBounds(new PclVector3(0, 0, 0), new PclVector3(100, 100, 100)); + + var pts1 = new EptSamplePoint[] { new(10, 10, 10) }; + var pts2 = new EptSamplePoint[] { new(60, 60, 60) }; + + var (manifest, _, data1, ext) = SyntheticFixtures.CreateSyntheticEpt(pts1, dataType: "binary", bounds: rootBounds); + string eptPath = dir.WriteText("ept.json", manifest); + + // Two nodes in octree: 1-0-0-0 (voxel [0..50, 0..50, 0..50]) and 1-1-1-1 (voxel [50..100, 50..100, 50..100]) + string hier = "{\"1-0-0-0\": 1, \"1-1-1-1\": 1}"; + dir.WriteText("ept-hierarchy/0-0-0-0.json", hier); + dir.Write($"ept-data/1-0-0-0.{ext}", data1); + + var (_, _, data2, _) = SyntheticFixtures.CreateSyntheticEpt(pts2, dataType: "binary", bounds: rootBounds); + dir.Write($"ept-data/1-1-1-1.{ext}", data2); + + using var doc = EptDocument.Open(eptPath); + Assert.Equal(2, doc.Nodes.Count); + + // Query spatial bounds covering only the first voxel [0..20, 0..20, 0..20] + var queryBounds = new PclBounds(new PclVector3(5, 5, 5), new PclVector3(25, 25, 25)); + var matchingNodes = doc.FindNodes(queryBounds); + Assert.Single(matchingNodes); + Assert.Equal("1-0-0-0", matchingNodes[0].Key.ToString()); + + var filteredPoints = doc.ReadPoints(queryBounds).ToList(); + Assert.Single(filteredPoints); + Assert.Equal(10.0, filteredPoints[0].X, Precision); + + // Read specific node directly + var nodePoints = doc.ReadPoints(doc.Nodes[1]).ToList(); + Assert.Single(nodePoints); + Assert.Equal(60.0, nodePoints[0].X, Precision); + } + + [Fact] + public void Ept_Hierarchy_MultiPage_And_Cycle_Detection() + { + using var dir = new TempDirectory(); + var pts = new EptSamplePoint[] { new(1, 2, 3) }; + var (manifest, _, data, ext) = SyntheticFixtures.CreateSyntheticEpt(pts, dataType: "binary"); + string eptPath = dir.WriteText("ept.json", manifest); + + // 0-0-0-0.json refers to 1-0-0-0 as sub-page (-1) + dir.WriteText("ept-hierarchy/0-0-0-0.json", "{\"1-0-0-0\": -1}"); + // 1-0-0-0.json defines 1-0-0-0 as having 1 point + dir.WriteText("ept-hierarchy/1-0-0-0.json", "{\"1-0-0-0\": 1}"); + dir.Write($"ept-data/1-0-0-0.{ext}", data); + + using (var doc = EptDocument.Open(eptPath)) + { + Assert.Single(doc.Nodes); + Assert.Equal("1-0-0-0", doc.Nodes[0].Key.ToString()); + } + + // Cyclic hierarchy reference should throw InvalidDataException + dir.WriteText("ept-hierarchy/1-0-0-0.json", "{\"0-0-0-0\": -1}"); + Assert.Throws(() => EptDocument.Open(eptPath)); + } + + [Fact] + public void Ept_Applies_ReadOptions() + { + using var dir = new TempDirectory(); + var points = Enumerable.Range(0, 10) + .Select(i => new EptSamplePoint(i, i * 2, i * 3)) + .ToArray(); + + var (manifest, hier, data, ext) = SyntheticFixtures.CreateSyntheticEpt(points, dataType: "binary"); + string eptPath = dir.WriteText("ept.json", manifest); + dir.WriteText("ept-hierarchy/0-0-0-0.json", hier); + dir.Write($"ept-data/0-0-0-0.{ext}", data); + + using var doc = EptDocument.Open(eptPath); + + // MaxPoints + var limited = doc.ReadAllPoints(new PclReadOptions { MaxPoints = 4 }).ToList(); + Assert.Equal(4, limited.Count); + + // SubsampleStep + var subsampled = doc.ReadAllPoints(new PclReadOptions { SubsampleStep = 3 }).ToList(); + Assert.Equal(4, subsampled.Count); // indices 0, 3, 6, 9 + Assert.Equal(0.0, subsampled[0].X, Precision); + Assert.Equal(3.0, subsampled[1].X, Precision); + Assert.Equal(6.0, subsampled[2].X, Precision); + Assert.Equal(9.0, subsampled[3].X, Precision); + + // ApplyTransform + var transform = new PclTransform { Translation = new PclVector3(10, 20, 30) }; + typeof(PclScan).GetProperty("Transform")!.SetValue(doc.Scans[0], transform); + var transformed = doc.ReadAllPoints(new PclReadOptions { MaxPoints = 1, ApplyTransform = true }).First(); + Assert.Equal(10.0, transformed.X, Precision); + Assert.Equal(20.0, transformed.Y, Precision); + Assert.Equal(30.0, transformed.Z, Precision); + } + + [Fact] + public void Ept_Rejects_Corrupt_Manifest_Json() + { + using var dir = new TempDirectory(); + string path = dir.WriteText("ept.json", "NOT JSON"); + Assert.Throws(() => EptDocument.Open(path)); + } + + [Fact] + public void Ept_Rejects_Missing_DataType() + { + using var dir = new TempDirectory(); + string json = "{\"bounds\":[0,0,0,1,1,1],\"schema\":[{\"name\":\"X\"},{\"name\":\"Y\"},{\"name\":\"Z\"}]}"; + string path = dir.WriteText("ept.json", json); + Assert.Throws(() => EptDocument.Open(path)); + } + + [Fact] + public void Ept_Rejects_Unsupported_DataType() + { + using var dir = new TempDirectory(); + string json = "{\"bounds\":[0,0,0,1,1,1],\"dataType\":\"parquet\",\"schema\":[{\"name\":\"X\"},{\"name\":\"Y\"},{\"name\":\"Z\"}]}"; + string path = dir.WriteText("ept.json", json); + Assert.Throws(() => EptDocument.Open(path)); + } + + [Fact] + public void Ept_Rejects_Missing_Or_NonFinite_Bounds() + { + using var dir = new TempDirectory(); + string jsonMissing = "{\"dataType\":\"binary\",\"schema\":[{\"name\":\"X\"},{\"name\":\"Y\"},{\"name\":\"Z\"}]}"; + string path1 = dir.WriteText("missing_bounds/ept.json", jsonMissing); + Assert.Throws(() => EptDocument.Open(path1)); + + string jsonNaN = "{\"dataType\":\"binary\",\"bounds\":[0,0,0,\"NaN\",1,1],\"schema\":[{\"name\":\"X\"},{\"name\":\"Y\"},{\"name\":\"Z\"}]}"; + string path2 = dir.WriteText("nan_bounds/ept.json", jsonNaN); + Assert.Throws(() => EptDocument.Open(path2)); + } + + [Fact] + public void Ept_Rejects_Missing_Schema_Or_Dimensions() + { + using var dir = new TempDirectory(); + string jsonNoSchema = "{\"dataType\":\"binary\",\"bounds\":[0,0,0,1,1,1]}"; + string path1 = dir.WriteText("no_schema/ept.json", jsonNoSchema); + Assert.Throws(() => EptDocument.Open(path1)); + + string jsonNoXYZ = "{\"dataType\":\"binary\",\"bounds\":[0,0,0,1,1,1],\"schema\":[{\"name\":\"Intensity\"}]}"; + string path2 = dir.WriteText("no_xyz/ept.json", jsonNoXYZ); + Assert.Throws(() => EptDocument.Open(path2)); + } + + [Fact] + public void Ept_Rejects_Truncated_Binary_Tile() + { + using var dir = new TempDirectory(); + var (manifest, hier, _, ext) = SyntheticFixtures.CreateSyntheticEpt([new(1, 2, 3)], dataType: "binary"); + string eptPath = dir.WriteText("ept.json", manifest); + dir.WriteText("ept-hierarchy/0-0-0-0.json", hier); + // Point record size is 21 bytes. Write 10 bytes instead to simulate truncated tile. + dir.Write($"ept-data/0-0-0-0.{ext}", new byte[10]); + + using var doc = EptDocument.Open(eptPath); + Assert.Throws(() => doc.ReadAllPoints().ToList()); + } } diff --git a/tests/PclIO.Tests/KindDetectionTests.cs b/tests/PclIO.Tests/KindDetectionTests.cs index 5463345..49d4e7c 100644 --- a/tests/PclIO.Tests/KindDetectionTests.cs +++ b/tests/PclIO.Tests/KindDetectionTests.cs @@ -286,6 +286,13 @@ public void Detects_Directory_Layouts() string bySmf = Path.GetDirectoryName(dir.WriteText("pin2/project.smf", "{}"))!; Assert.Equal(PclFileKind.PinPoint, PclFile.DetectKind(bySmf)); + var (eptManifest, _, _, _) = SyntheticFixtures.CreateSyntheticEpt([new(1, 2, 3)]); + string eptDir = Path.GetDirectoryName(dir.WriteText("ept_dataset/ept.json", eptManifest))!; + Assert.Equal(PclFileKind.Ept, PclFile.DetectKind(eptDir)); + + string fakeEptDir = Path.GetDirectoryName(dir.WriteText("fake_ept/ept.json", "{}"))!; + Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(fakeEptDir)); + string empty = dir.PathOf("empty"); Directory.CreateDirectory(empty); Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(empty)); @@ -428,6 +435,29 @@ public void Potree_Rejects_Invalid_Hrc_Or_Js() Assert.Equal(PclFileKind.Unknown, Detect("var x = 42;"u8.ToArray(), "cloud.js")); } + [Theory] + [InlineData("ept.json")] + [InlineData("EPT.JSON")] + [InlineData("manifest.json")] + public void Detects_Ept_Json_By_Content(string name) + { + var (manifest, _, _, _) = SyntheticFixtures.CreateSyntheticEpt([new(1, 2, 3)]); + Assert.Equal(PclFileKind.Ept, Detect(System.Text.Encoding.UTF8.GetBytes(manifest), name)); + } + + [Fact] + public void Ept_Rejects_Invalid_Manifest() + { + // Not JSON + Assert.Equal(PclFileKind.Unknown, Detect("not json"u8.ToArray(), "ept.json")); + // Empty object + Assert.Equal(PclFileKind.Unknown, Detect("{}"u8.ToArray(), "ept.json")); + // Missing schema + Assert.Equal(PclFileKind.Unknown, Detect("{\"bounds\":[0,0,0,1,1,1],\"dataType\":\"binary\"}"u8.ToArray(), "ept.json")); + // Wrong data type + Assert.Equal(PclFileKind.Unknown, Detect("{\"bounds\":[0,0,0,1,1,1],\"dataType\":\"custom\",\"schema\":[]}"u8.ToArray(), "ept.json")); + } + [Fact] public void Detects_Files_On_Disk_The_Same_Way() { @@ -451,6 +481,16 @@ public void Detects_Files_On_Disk_The_Same_Way() Assert.Equal(PclFileKind.Potree, PclFile.DetectKind(potreeDir.Root)); Assert.Equal(PclFileKind.Potree, PclFile.DetectKind(binPath)); + + // EPT manifest and directory + using var eptDir = new TempDirectory(); + var (eptJson, _, _, _) = SyntheticFixtures.CreateSyntheticEpt([new(1, 2, 3)]); + string eptFile = eptDir.WriteText("ept.json", eptJson); + Assert.Equal(PclFileKind.Ept, PclFile.DetectKind(eptFile)); + Assert.Equal(PclFileKind.Ept, PclFile.DetectKind(eptDir.Root)); + string badEptFile = eptDir.WriteText("sub/ept.json", "{}"); + Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(badEptFile)); + Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(Path.GetDirectoryName(badEptFile)!)); } private sealed class NonSeekableStream(byte[] bytes) : MemoryStream(bytes) diff --git a/tests/PclIO.Tests/RealFileTests.cs b/tests/PclIO.Tests/RealFileTests.cs index 248bcbc..be43c77 100644 --- a/tests/PclIO.Tests/RealFileTests.cs +++ b/tests/PclIO.Tests/RealFileTests.cs @@ -152,6 +152,34 @@ public void Read_Real_Potree_CloudJs() Assert.NotNull(firstPoint.Normal); } + [SkippableFact] + public void Read_Real_Ept_Manifest() + { + string? root = TestFiles.Roots().FirstOrDefault(); + if (root == null) throw TestFiles.Missing("ept.json"); + string eptPath = Path.Combine(root, "ept", "lion_takanawa", "ept.json"); + if (!File.Exists(eptPath)) + eptPath = Path.Combine(root, "downloads", "ept", "lion_takanawa", "ept.json"); + if (!File.Exists(eptPath)) + eptPath = TestFiles.FindByExtension("ept.json"); + + Assert.Equal(PclFileKind.Ept, PclFile.DetectKind(eptPath)); + Assert.Equal(PclFileKind.Ept, PclFile.DetectKind(Path.GetDirectoryName(eptPath)!)); + + using var doc = PclFile.Open(eptPath); + Assert.Equal(PclFileKind.Ept, doc.Kind); + Assert.Single(doc.Scans); + Assert.Equal(341989, doc.TotalPointCount); + + var points = doc.ReadAllPoints(new PclReadOptions { MaxPoints = 100 }).ToList(); + Assert.Equal(100, points.Count); + var firstPoint = points[0]; + Assert.True(double.IsFinite(firstPoint.X)); + Assert.True(double.IsFinite(firstPoint.Y)); + Assert.True(double.IsFinite(firstPoint.Z)); + Assert.NotNull(firstPoint.Color); + } + [SkippableFact] public void Export_Real_File_To_Las_Matches_The_Requested_Count() { diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs index 94e0242..dc1094d 100644 --- a/tests/PclIO.Tests/SyntheticFixtures.cs +++ b/tests/PclIO.Tests/SyntheticFixtures.cs @@ -62,6 +62,14 @@ public readonly record struct PotreeSamplePoint( PclVector3? Normal = null, byte? Classification = null); +/// One point of a synthetic EPT dataset: position, colour, intensity, normal and classification. +public readonly record struct EptSamplePoint( + double X, double Y, double Z, + PclColor? Color = null, + float? Intensity = null, + PclVector3? Normal = null, + byte? Classification = null); + /// Generates small synthetic scan files for the tests. Every layout is written from what the readers implement; /// no byte of any of them comes from a real scan. internal static class SyntheticFixtures @@ -2625,4 +2633,135 @@ public static (string metadataJson, byte[] octreeBin) CreateSyntheticPotree2x( string metadataJson = JsonSerializer.Serialize(manifest, new JsonSerializerOptions { WriteIndented = true }); return (metadataJson, octreeBin); } + + /// Generates a synthetic EPT dataset (ept.json, hierarchy 0-0-0-0.json, and data tile 0-0-0-0.{ext}). + public static (string manifestJson, string hierarchyJson, byte[] dataBytes, string dataExtension) CreateSyntheticEpt( + IReadOnlyList points, + string dataType = "binary", + PclBounds? bounds = null, + int span = 128) + { + double minX = double.PositiveInfinity, minY = double.PositiveInfinity, minZ = double.PositiveInfinity; + double maxX = double.NegativeInfinity, maxY = double.NegativeInfinity, maxZ = double.NegativeInfinity; + + foreach (var pt in points) + { + minX = Math.Min(minX, pt.X); + minY = Math.Min(minY, pt.Y); + minZ = Math.Min(minZ, pt.Z); + maxX = Math.Max(maxX, pt.X); + maxY = Math.Max(maxY, pt.Y); + maxZ = Math.Max(maxZ, pt.Z); + } + + if (points.Count == 0 || !double.IsFinite(minX)) + { + minX = minY = minZ = 0; + maxX = maxY = maxZ = 100; + } + + double cubeMinX = Math.Floor(minX); + double cubeMinY = Math.Floor(minY); + double cubeMinZ = Math.Floor(minZ); + double maxSpan = Math.Max(maxX - cubeMinX, Math.Max(maxY - cubeMinY, maxZ - cubeMinZ)); + if (maxSpan <= 0) maxSpan = 1.0; + double cubeMaxX = cubeMinX + maxSpan; + double cubeMaxY = cubeMinY + maxSpan; + double cubeMaxZ = cubeMinZ + maxSpan; + + if (bounds.HasValue) + { + cubeMinX = bounds.Value.Min.X; + cubeMinY = bounds.Value.Min.Y; + cubeMinZ = bounds.Value.Min.Z; + cubeMaxX = bounds.Value.Max.X; + cubeMaxY = bounds.Value.Max.Y; + cubeMaxZ = bounds.Value.Max.Z; + } + + var schemaList = new List> + { + new() { ["name"] = "X", ["type"] = "signed", ["size"] = 4, ["scale"] = 0.001, ["offset"] = 0.0 }, + new() { ["name"] = "Y", ["type"] = "signed", ["size"] = 4, ["scale"] = 0.001, ["offset"] = 0.0 }, + new() { ["name"] = "Z", ["type"] = "signed", ["size"] = 4, ["scale"] = 0.001, ["offset"] = 0.0 }, + new() { ["name"] = "Intensity", ["type"] = "unsigned", ["size"] = 2, ["scale"] = 1.0, ["offset"] = 0.0 }, + new() { ["name"] = "Red", ["type"] = "unsigned", ["size"] = 2, ["scale"] = 1.0, ["offset"] = 0.0 }, + new() { ["name"] = "Green", ["type"] = "unsigned", ["size"] = 2, ["scale"] = 1.0, ["offset"] = 0.0 }, + new() { ["name"] = "Blue", ["type"] = "unsigned", ["size"] = 2, ["scale"] = 1.0, ["offset"] = 0.0 }, + new() { ["name"] = "Classification", ["type"] = "unsigned", ["size"] = 1, ["scale"] = 1.0, ["offset"] = 0.0 }, + }; + + var manifestObj = new Dictionary + { + ["bounds"] = new double[] { cubeMinX, cubeMinY, cubeMinZ, cubeMaxX, cubeMaxY, cubeMaxZ }, + ["boundsConforming"] = new double[] { minX, minY, minZ, maxX, maxY, maxZ }, + ["dataType"] = dataType, + ["hierarchyType"] = "json", + ["points"] = points.Count, + ["schema"] = schemaList, + ["span"] = span, + ["version"] = "1.0.0" + }; + + string manifestJson = JsonSerializer.Serialize(manifestObj, new JsonSerializerOptions { WriteIndented = true }); + + var hierObj = new Dictionary + { + ["0-0-0-0"] = points.Count + }; + string hierarchyJson = JsonSerializer.Serialize(hierObj, new JsonSerializerOptions { WriteIndented = true }); + + int recSize = 4 + 4 + 4 + 2 + 2 + 2 + 2 + 1; // 21 bytes + byte[] rawBin = new byte[points.Count * recSize]; + int offset = 0; + foreach (var pt in points) + { + int ix = (int)Math.Round(pt.X / 0.001); + int iy = (int)Math.Round(pt.Y / 0.001); + int iz = (int)Math.Round(pt.Z / 0.001); + ushort intensity = (ushort)(pt.Intensity.HasValue ? Math.Clamp((int)Math.Round(pt.Intensity.Value * 65535.0), 0, 65535) : 0); + ushort r = pt.Color.HasValue ? (ushort)(pt.Color.Value.R * 257) : (ushort)0; + ushort g = pt.Color.HasValue ? (ushort)(pt.Color.Value.G * 257) : (ushort)0; + ushort b = pt.Color.HasValue ? (ushort)(pt.Color.Value.B * 257) : (ushort)0; + byte cls = pt.Classification ?? 0; + + BinaryPrimitives.WriteInt32LittleEndian(rawBin.AsSpan(offset, 4), ix); + BinaryPrimitives.WriteInt32LittleEndian(rawBin.AsSpan(offset + 4, 4), iy); + BinaryPrimitives.WriteInt32LittleEndian(rawBin.AsSpan(offset + 8, 4), iz); + BinaryPrimitives.WriteUInt16LittleEndian(rawBin.AsSpan(offset + 12, 2), intensity); + BinaryPrimitives.WriteUInt16LittleEndian(rawBin.AsSpan(offset + 14, 2), r); + BinaryPrimitives.WriteUInt16LittleEndian(rawBin.AsSpan(offset + 16, 2), g); + BinaryPrimitives.WriteUInt16LittleEndian(rawBin.AsSpan(offset + 18, 2), b); + rawBin[offset + 20] = cls; + offset += recSize; + } + + byte[] tileBytes; + string ext; + if (dataType == "laszip") + { + ext = "laz"; + if (points.Count > 0) + { + var pt0 = points[0]; + tileBytes = CreateSyntheticLaz(pt0.X, pt0.Y, pt0.Z, pt0.Intensity ?? 0f, pt0.Color, pt0.Classification ?? 0); + } + else + { + tileBytes = CreateSyntheticLaz(); + } + } + else if (dataType == "zstandard") + { + ext = "zst"; + tileBytes = RawZstdFrame.Wrap(rawBin); + } + else + { + ext = "bin"; + tileBytes = rawBin; + } + + return (manifestJson, hierarchyJson, tileBytes, ext); + } } diff --git a/tests/PclIO.Tests/TestFiles.cs b/tests/PclIO.Tests/TestFiles.cs index 07f6201..3136d85 100644 --- a/tests/PclIO.Tests/TestFiles.cs +++ b/tests/PclIO.Tests/TestFiles.cs @@ -45,7 +45,9 @@ public static IEnumerable Roots(string? configured) string? found = Directory.EnumerateFiles(root, "*" + extension, options) .Where(f => string.Equals(extension, ".copc.laz", StringComparison.OrdinalIgnoreCase) ? f.EndsWith(".copc.laz", StringComparison.OrdinalIgnoreCase) - : string.Equals(Path.GetExtension(f), extension, StringComparison.OrdinalIgnoreCase)) + : string.Equals(extension, "ept.json", StringComparison.OrdinalIgnoreCase) + ? f.EndsWith("ept.json", StringComparison.OrdinalIgnoreCase) + : string.Equals(Path.GetExtension(f), extension, StringComparison.OrdinalIgnoreCase)) .Where(f => !string.Equals(extension, ".laz", StringComparison.OrdinalIgnoreCase) || !f.EndsWith(".copc.laz", StringComparison.OrdinalIgnoreCase)) .Order(StringComparer.Ordinal) .FirstOrDefault();