diff --git a/CHANGELOG.md b/CHANGELOG.md index b37a3cf..0fff96e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Read legacy Leica LGS octree points with source RGB and intensity. + +### Changed + +- Identify Leica LGS and LGSx from their container footer and report unsupported legacy point encoding explicitly. + ## [0.1.2] - 2026-11-26 ### Added diff --git a/README.md b/README.md index 5af9aa1..755d25b 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,8 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies | ASTM E57 | `.e57` | Points decoded for a defined subset: uncompressed bit-packed streams with single or double precision Cartesian coordinates or scaled-integer coordinates (raw value times scale plus offset), or spherical range, azimuth and elevation converted to Cartesian points, with 8-bit colour and 8-bit intensity, or colour with a wider Integer range from zero and intensity as a wider Integer, a Float or a scaled integer. Pose translation and rotation are applied. Only plain bit-packing is decoded: a scan whose codecs vector names another codec lists normally and fails when its points are read, and the message names it. Per-point validity flags skip invalid points and clear invalid channels when their streams hold one flag byte per record; other shapes are not interpreted. Registered image blobs can be read explicitly through the format API. Page checksums are verified. | | ReCap scan | `.rcs` | Experimental support for container version 3.2. The reader validates section and leaf ranges before returning points. Stored positions use a millimetre grid, with RGB, intensity and normals according to the header flags. `PointCount` reports stored points. The header count is available as `DeclaredPointCount`. When `ApplyTransform` is enabled, the reader applies scale and translation. Rotation values are metadata. | | ReCap project | `.rcp` | Lists scan nodes and opens referenced `.rcs` files next to the project. Channel availability comes from the referenced scan header. With transforms enabled, the reader uses the node translation and scale when stated, and otherwise uses the scan file's transform. Rotation values are metadata. | -| Leica scan container | `.lgsx`, `.lgs` | Experimental. Version 22 point blocks decode differential Morton coordinates, RGB and intensity. Normals are unavailable for that block version. When the container assigns its points to its setups, there is one scan per setup, named after the setup, with the pose and the bounds of the setup when its record holds them; the pose is applied unless `ApplyTransform` is false. When the container does not assign its points, all points of the container form one scan and a warning says so. The point count is taken from the container when it states one; otherwise it is found by decoding the data, which is slow on large files. `PclReadOptions.Blocks` reads only the blocks of the scan in that file-order range (per scan, so a setup scan ranges over its own blocks); `PclReadOptions.MaxDegreeOfParallelism` above 1 decodes those blocks in parallel and still yields the points in file order with consecutive `Index` values. | +| Leica scan container | `.lgsx` | Experimental. Version 22 point blocks decode differential Morton coordinates, RGB and intensity. Normals are unavailable for that block version. When the container assigns its points to its setups, there is one scan per setup, named after the setup, with the pose and the bounds of the setup when its record holds them; the pose is applied unless `ApplyTransform` is false. When the container does not assign its points, all points of the container form one scan and a warning says so. The point count is taken from the container when it states one; otherwise it is found by decoding the data, which is slow on large files. `PclReadOptions.Blocks` reads only the blocks of the scan in that file-order range (per scan, so a setup scan ranges over its own blocks); `PclReadOptions.MaxDegreeOfParallelism` above 1 decodes those blocks in parallel and still yields the points in file order with consecutive `Index` values. | +| Leica legacy container | `.lgs` | Streams position, RGB and intensity from the supported octree layout as one scan in project coordinates. Convert unsupported variants to LGSx. | | FARO scan | `.fls`, or a FARO scan folder | Experimental. Single-file containers with distance mode 26 decode both halves of the range grid and their optional RGB and intensity planes. The scan grid and angles are read from the stored parameters and points are projected from the range grid; a file without them fails to open. The point count is the number of valid returns, which is counted on the first access; `FaroScan.GridSize` is the size of the scan grid. For a scan folder the layout of the samples is derived from the size of the data stream and the size of the grid, and the scale of the intensity from the values that are stored; when the sizes do not fit, the layout is assumed and a warning says so. | | PinPoint project | `.srf`, `.smf`, or a folder with `ScanProject.json` or `.smf`/`.srf` files | Experimental. The manifest (scan names, ids, poses, counts) is read. Points come from the referenced `.bin` files, in either of two layouts: a table of named channels, or numbered sections with a property table and Snappy-compressed channels, which PclIO decodes itself. Colour, intensity and normals are reported only when the file has that channel; in the second layout positions, colours, intensities, normals (`Normals`, three float32 components per point) and the per-point flags (`FilterBits`, one byte per point) are read, while the grid indices stored beside them are not interpreted, so by default every stored point that passes the plausibility rule below is returned. With `PclReadOptions.ExcludeFilteredPoints` the points with a non-zero flag are not returned. A manifest with a scan position list takes the point count from the manifest, else from the data file; a manifest with a data object list takes it from the data file the object refers to, and every location that shares one file reports its full count, because the shares are not recorded. A project shell whose data files are absent lists no scans, and a manifest whose referenced data files are missing reads no points; neither is a readable fixture. | | EdgeWise | `.c3db`, `.c3ptx` | Experimental. A `.c3db` point database lists the scan clusters and a `.c3ptx` is one cluster file; the cluster files give positions only, as three 16-bit offsets from the cluster centre per point. The scale of the offsets is not stored in the files, so the reader assumes 32768 units = 0.128 m unless the caller states it with `PclReadOptions.EdgeWiseCoordinateScale`. | @@ -70,8 +71,8 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies `PclFileKind.Unknown` for anything else; `PclFile.Open` then throws `NotSupportedException`. Extensions are compared without 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. +- E57, ReCap scan and Leica files are recognised by content with any extension. The Leica footer distinguishes LGS from LGSx, + with the extension as a fallback when no recognised footer is present. EdgeWise can also be recognised by content. 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 CC BIN file is recognised by the `CCB2` signature and entity header structure with any extension; a recognised Potree manifest in an ancestor directory takes precedence for `.bin` files. - 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`. diff --git a/docs/getting-started.md b/docs/getting-started.md index 5473800..b0d977f 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -86,7 +86,8 @@ reading), `NotSupportedException` (unrecognised format or unsupported feature) o | ASTM E57 | `.e57` | Points decoded for a defined subset (uncompressed bit-packed streams, single or double precision Cartesian coordinates, 8-bit colour and intensity). The format API also reads image blobs with checksum verification. | | ReCap scan | `.rcs` | Experimental support for container version 3.2. Reads positions, intensity, colour and normals. Rotation values are metadata. | | ReCap project | `.rcp` | Opens referenced `.rcs` files next to the project. With transforms enabled, uses the node's translation and scale when stated, and otherwise uses the scan file's transform. Rotation values are metadata. | -| Leica scan container | `.lgsx`, `.lgs` | Experimental. Version 22 blocks provide geometry, RGB and intensity. Containers without setup assignments open as one scan in container coordinates. | +| Leica scan container | `.lgsx` | Experimental. Version 22 blocks provide geometry, RGB and intensity. Containers without setup assignments open as one scan in container coordinates. | +| Leica legacy container | `.lgs` | Reads the supported octree layout as one scan with source RGB and intensity. Convert unrecognized variants to LGSx. | | FARO scan | `.fls`, or a FARO scan folder | Experimental. Single-file distance mode 26 reconstructs both halves of the scan grid. A folder scan is read with an assumed layout and carries a warning. | | PinPoint project | `.srf`, `.smf`, or a folder with `ScanProject.json` or `.smf`/`.srf` files | Experimental; manifest plus point data files in one of two layouts (named channels, or sections with Snappy-compressed channels); a data file in neither layout is not read. | | EdgeWise | `.c3db`, `.c3ptx` | Experimental; positions only, with a coordinate scale that is an assumption of the reader. | diff --git a/docs/public-api.md b/docs/public-api.md index 90bd7ce..5775c8b 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -30,8 +30,8 @@ Detection finds the kind from the content of the file, its extension or the layo `PclFileKind.Unknown` for anything else. Extensions are compared without regard to case; for the stream overload the extension is the argument, which may also be a file name. -- `E57`, `RecapScan` and the Leica kinds are recognised by content and accepted with any extension; `LeicaLgs` is chosen for the - extension `.lgs` and `LeicaLgsx` for any other. `EdgeWise` is also recognised by content in a file with another extension. +- `E57`, `RecapScan` and the Leica kinds are recognised by content with any extension. A recognised Leica footer determines + `LeicaLgs` or `LeicaLgsx`, with the extension as a fallback. `EdgeWise` can also be recognised by content. `Las` is recognised by the `LASF` signature with any extension except `.laz` and `.copc.laz`. `Laz` is recognised by the `LASF` signature, a valid LASzip VLR and the `.laz` extension. `Copc` is recognised by the LAS 1.4 header and the `copc` info VLR with `.copc.laz` or any extension. @@ -102,8 +102,9 @@ request. An unresolved reference reports false for the channel properties. A res ## Format documents -For sampling plans, `LgsxDocument.GetEncodedPointCount` reads the declared counts in version 22 point block headers without -decompressing the point data. It returns null when the file uses another block layout or has no point blocks. +For sampling plans, `LgsxDocument.GetEncodedPointCount` reads the declared counts from native LGS point metadata or +version 22 LGSx point block headers without decoding the points. It returns null when the count is unavailable. +Legacy LGS returns one scan in project coordinates. Its dependent blocks are traversed together in spatial order. `PclSceneOptions.PointObserver` receives retained points in scene geometry order, including their source attributes. `PclSceneOptions.MaxDegreeOfParallelism` passes the requested concurrency to formats that support block decoding. diff --git a/src/PclIO.Cli/Program.cs b/src/PclIO.Cli/Program.cs index 91bbe26..b251f23 100644 --- a/src/PclIO.Cli/Program.cs +++ b/src/PclIO.Cli/Program.cs @@ -76,7 +76,7 @@ Input formats (detected from the file signature, the extension or the folder lay ASTM E57 by signature, any extension ReCap scan by signature (.rcs) ReCap project a ZIP archive with the extension .rcp - Leica scan by signature; .lgs selects the older container, any other extension .lgsx + Leica scan by signature and footer; extension used when the footer is unrecognised FARO scan an OLE2 compound file with the extension .fls, or a folder with a FARO scan layout PinPoint a JSON text file with the extension .smf or .srf, or a folder that holds ScanProject.json, a .smf file or a .srf file diff --git a/src/PclIO/Formats/Leica/LegacyLgsScan.cs b/src/PclIO/Formats/Leica/LegacyLgsScan.cs new file mode 100644 index 0000000..893fed3 --- /dev/null +++ b/src/PclIO/Formats/Leica/LegacyLgsScan.cs @@ -0,0 +1,423 @@ +using System.Globalization; +using System.Numerics; +using System.Text; +using PclIO.Internal; + +namespace PclIO.Formats.Leica; + +internal sealed class LegacyLgsScan : PclScan +{ + private static ReadOnlySpan Signature => "UDS4\u0007\0\0\0"u8; + private const int MaskSize = 1024; + private const int MaskSearchBytes = 16 * 1024 * 1024; + private const int MaxMetadataBytes = 64 * 1024; + private const int MaxBlocks = 1_000_000; + private const int MaxGeometryBytes = 512 * 1024 * 1024; + private const int AttributePagePoints = 4096; + + private readonly string _path; + private readonly long _offset; + private readonly long _length; + private readonly byte[] _mask; + private readonly Header _header; + + private sealed record Header(int Count, int Depth, PclVector3 Origin, PclVector3 Size, + PclBounds Bounds, int[] Widths, int Color, int Intensity, int Blocks, int Groups, int DirectoryEnd); + private readonly record struct Block(int FirstRecord, int Records, long GeometryOffset, int GeometryLength, + long ColorOffset, long IntensityOffset, uint Children); + + private LegacyLgsScan(string path, long offset, long length, byte[] mask, Header header) + { + (_path, _offset, _length, _mask, _header) = (path, offset, length, mask, header); + Name = Path.GetFileNameWithoutExtension(path); + Bounds = header.Bounds; + } + + public override string Id => "unified-cloud"; + public override string Name { get; } + public override long PointCount => _header.Count; + public override bool HasColors => _header.Color >= 0; + public override bool HasIntensities => _header.Intensity >= 0; + + internal static LegacyLgsScan? TryOpen(FileStream stream, LgsxEntry entry) + { + long offset = (long)entry.Offset; + long length = (long)entry.Size; + int prefixLength = (int)Math.Min(length, MaskSearchBytes); + if (prefixLength < 156) return null; + var prefix = new byte[prefixLength]; + stream.Position = offset; + stream.ReadExactly(prefix); + byte[]? mask = FindMask(prefix); + if (mask == null) return null; + + Xor(prefix.AsSpan(0, 156), mask, 0); + uint metadataSize = Bytes.ReadUInt32LE(prefix.AsSpan(8)); + if (metadataSize is < 148 or > MaxMetadataBytes || metadataSize + 8 > prefix.Length - 32) + throw FormatError.Corrupted("invalid point metadata size."); + int directory = (int)metadataSize + 8; + Xor(prefix.AsSpan(156, directory + 32 - 156), mask, 156); + Header header = ParseHeader(prefix, directory, length); + return new LegacyLgsScan(stream.Name, offset, length, mask, header); + } + + private static byte[]? FindMask(ReadOnlySpan data) + { + if (data.StartsWith(Signature)) return new byte[MaskSize]; + Span tag = stackalloc byte[8]; + for (int i = 0; i < tag.Length; i++) tag[i] = (byte)(data[i] ^ Signature[i]); + ReadOnlySpan match = []; + // Two identical aligned padding sectors disambiguate the mask from a partial zero run. + for (int offset = MaskSize; offset <= data.Length - 2 * MaskSize; offset += MaskSize) + { + var sector = data.Slice(offset, MaskSize); + if (!sector.StartsWith(tag) || !sector.SequenceEqual(data.Slice(offset + MaskSize, MaskSize))) continue; + if (!match.IsEmpty && !sector.SequenceEqual(match)) return null; + match = sector; + } + return match.IsEmpty ? null : match.ToArray(); + } + + private static Header ParseHeader(ReadOnlySpan data, int directory, long length) + { + double edge = Bytes.ReadDoubleLE(data[12..]); + uint levels = Bytes.ReadUInt32LE(data[28..]); + PclVector3 scale = ReadVector(data[32..]), origin = ReadVector(data[56..]); + var size = scale * edge; + if (!double.IsFinite(edge) || edge <= 0 || levels is < 2 or > 30 || + !Finite(origin) || !Finite(size) || !Finite(origin + size) || + size.X <= 0 || size.Y <= 0 || size.Z <= 0) + throw FormatError.Corrupted("invalid point grid transform."); + + uint pairs = Bytes.ReadUInt32LE(data[152..]); + if (pairs > 256) throw FormatError.Corrupted("too many point metadata fields."); + var metadata = data[156..directory]; + int count = 0; + string? modelAttributes = null; + for (int i = 0; i < pairs; i++) + { + string key = ReadString(ref metadata); + string value = ReadString(ref metadata); + if (key == "UniquePointCount") + _ = int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out count); + else if (key == "ModelAttributes") + modelAttributes = value; + } + if (!metadata.IsEmpty || count <= 0 || modelAttributes == null) + throw FormatError.Corrupted("missing point count or attribute metadata."); + + string[] attributes = modelAttributes.Split(' ', StringSplitOptions.RemoveEmptyEntries); + var table = data[directory..]; + uint blocks = Bytes.ReadUInt32LE(table[24..]), groups = Bytes.ReadUInt32LE(table[28..]); + if (Bytes.ReadUInt32LE(table) != 2 || Bytes.ReadUInt32LE(table[4..]) != 256 || + attributes.Length is < 1 or > 64 || Bytes.ReadUInt32LE(table[12..]) != attributes.Length) + throw FormatError.Unsupported("unrecognized Leica LGS point directory."); + if (groups == 0 || groups > blocks || blocks > MaxBlocks || blocks > count) + throw FormatError.Corrupted("invalid point block count."); + + var widths = new int[attributes.Length]; + for (int i = 0; i < widths.Length; i++) + { + widths[i] = attributes[i][(attributes[i].LastIndexOf(':') + 1)..] switch + { + "u8" => 1, + "u16" => 2, + "u32" => 4, + _ => throw FormatError.Unsupported("unrecognized Leica LGS point attribute type."), + }; + } + if ((long)count * widths.Sum() > length) + throw FormatError.Corrupted("the declared points exceed the point section."); + int color = Array.IndexOf(attributes, "udRGB:u32"); + int intensity = Array.IndexOf(attributes, "udIntensity:u16"); + int directoryEnd = directory + 32 + 8 * widths.Length; + var center = ReadVector(data[104..]); + var half = ReadVector(data[128..]); + var min = ToWorld(center - half, origin, size); + var max = ToWorld(center + half, origin, size); + PclBounds bounds = Finite(min) && Finite(max) ? new(min, max) : PclBounds.Empty; + return new(count, (int)levels - 1, origin, size, bounds, widths, color, intensity, (int)blocks, (int)groups, directoryEnd); + } + + private static string ReadString(ref ReadOnlySpan bytes) + { + if (bytes.Length < 2) throw FormatError.Truncated("point metadata"); + int size = Bytes.ReadUInt16LE(bytes); + if (size == 0 || size > bytes.Length - 2 || bytes[size + 1] != 0) + throw FormatError.Corrupted("invalid point metadata string."); + string value = Encoding.ASCII.GetString(bytes.Slice(2, size - 1)); + bytes = bytes[(2 + size)..]; + return value; + } + + private static PclVector3 ReadVector(ReadOnlySpan data) => + new(Bytes.ReadDoubleLE(data), Bytes.ReadDoubleLE(data[8..]), Bytes.ReadDoubleLE(data[16..])); + + private static bool Finite(PclVector3 p) => double.IsFinite(p.X) && double.IsFinite(p.Y) && double.IsFinite(p.Z); + + private static PclVector3 ToWorld(PclVector3 position, PclVector3 origin, PclVector3 size) => + new(origin.X + size.X * position.X, origin.Y + size.Y * position.Y, origin.Z + size.Z * position.Z); + + private static void Xor(Span data, byte[] mask, long offset) + { + int phase = (int)(offset & (MaskSize - 1)); + int first = Math.Min(data.Length, MaskSize - phase); + for (int i = 0; i < first; i++) data[i] ^= mask[phase + i]; + for (int start = first; start < data.Length;) + { + int n = Math.Min(MaskSize, data.Length - start); + int i = 0; + for (; i + Vector.Count <= n; i += Vector.Count) + { + var decoded = new Vector(data[(start + i)..]) ^ new Vector(mask.AsSpan(i)); + decoded.CopyTo(data[(start + i)..]); + } + for (; i < n; i++) data[start + i] ^= mask[i]; + start += n; + } + } + + private void Read(FileStream stream, long offset, Span data) + { + if (offset < 0 || offset > _length - data.Length) + throw FormatError.Truncated("legacy point section"); + stream.Position = _offset + offset; + stream.ReadExactly(data); + Xor(data, _mask, offset); + } + + private Block[] ReadBlocks(FileStream stream, out int geometryBytes) + { + int descriptorSize = (2 + _header.Widths.Length) * sizeof(uint); + var descriptions = new byte[checked(_header.Blocks * descriptorSize)]; + var known = new bool[_header.Blocks]; + var blockOffsets = new long[_header.Blocks]; + var blocks = new Block[_header.Blocks]; + long position = _header.DirectoryEnd; + Read(stream, position, descriptions.AsSpan(0, descriptorSize)); + position += descriptorSize; + known[0] = true; + long blocksStart = position; + int firstRecord = 0, groups = 0; + geometryBytes = 0; + Span groupHeader = stackalloc byte[20]; + Span descriptorBuffer = stackalloc byte[264]; + var newDescriptor = descriptorBuffer[..descriptorSize]; + + for (int i = 0; i < blocks.Length; i++) + { + if (!known[i] || (blockOffsets[i] != 0 && blockOffsets[i] != position)) + throw FormatError.Corrupted("missing or inconsistent point block entry."); + var description = descriptions.AsSpan(i * descriptorSize, descriptorSize); + long end = position + Bytes.ReadUInt32LE(description); + int records = CountRecords(description); + long attributes = (long)records * _header.Widths.Sum(); + long geometryEnd = end - attributes; + if (records > _header.Count - firstRecord || geometryEnd < position || end > _length) + throw FormatError.Corrupted("invalid point block size."); + + uint children = 0; + if (geometryEnd != position) + { + if (geometryEnd - position < groupHeader.Length) throw FormatError.Truncated("point geometry header"); + Read(stream, position, groupHeader); + ulong nextOffset = Bytes.ReadUInt64LE(groupHeader); + uint next = Bytes.ReadUInt32LE(groupHeader[8..]); + children = Bytes.ReadUInt32LE(groupHeader[12..]); + uint flags = Bytes.ReadUInt32LE(groupHeader[16..]); + int n = (int)(flags & 0xffff); + position += groupHeader.Length; + if (n == 0 || next > blocks.Length - n || nextOffset > (ulong)(_length - blocksStart) || + (long)n * descriptorSize > geometryEnd - position) + throw FormatError.Corrupted("invalid child block range."); + long childOffset = blocksStart + (long)nextOffset; + long childRecords = 0; + for (int j = (int)next; j < (int)next + n; j++) + { + Read(stream, position, newDescriptor); + var target = descriptions.AsSpan(j * descriptorSize, descriptorSize); + if ((known[j] && !newDescriptor.SequenceEqual(target)) || + (blockOffsets[j] != 0 && blockOffsets[j] != childOffset)) + throw FormatError.Corrupted("contradictory point block entries."); + newDescriptor.CopyTo(target); + known[j] = true; + blockOffsets[j] = childOffset; + childOffset += Bytes.ReadUInt32LE(newDescriptor); + childRecords += CountRecords(newDescriptor); + position += descriptorSize; + } + if (childRecords != children - (geometryEnd - position) + ((flags & 0x10000) != 0 ? 1 : 0)) + throw FormatError.Corrupted("point attributes do not match their geometry group."); + groups++; + } + + long geometryLength = geometryEnd - position; + if (geometryLength > MaxGeometryBytes - geometryBytes) + throw FormatError.Unsupported("the Leica LGS point grid exceeds the supported size."); + geometryBytes += (int)geometryLength; + blocks[i] = new(firstRecord, records, position, (int)geometryLength, + AttributeOffset(geometryEnd, records, _header.Color), + AttributeOffset(geometryEnd, records, _header.Intensity), children); + firstRecord += records; + position = end; + } + if (groups != _header.Groups || firstRecord != _header.Count) + throw FormatError.Corrupted("the point directory disagrees with its declared counts."); + return blocks; + } + + private int CountRecords(ReadOnlySpan descriptor) + { + uint bytes = Bytes.ReadUInt32LE(descriptor[8..]); + int width = _header.Widths[0]; + if (bytes % width != 0 || bytes / width > int.MaxValue) + throw FormatError.Corrupted("invalid point attribute length."); + int records = (int)(bytes / width); + for (int i = 1; i < _header.Widths.Length; i++) + if (Bytes.ReadUInt32LE(descriptor[(8 + 4 * i)..]) != (long)records * _header.Widths[i]) + throw FormatError.Corrupted("inconsistent point attribute lengths."); + return records; + } + + private long AttributeOffset(long start, int records, int channel) + { + if (channel < 0) return -1; + for (int i = 0; i < channel; i++) start += (long)records * _header.Widths[i]; + return start; + } + + private (int[] Start, int[] Count) ReadLevels(FileStream stream, Block[] blocks, byte[] masks) + { + int offset = 0; + foreach (var block in blocks) + { + if (block.GeometryLength == 0) continue; + var bytes = masks.AsSpan(offset, block.GeometryLength); + Read(stream, block.GeometryOffset, bytes); + long children = 0; + foreach (byte value in bytes) children += BitOperations.PopCount(value); + if (children != block.Children) + throw FormatError.Corrupted("point occupancy disagrees with a geometry group."); + offset += bytes.Length; + } + var starts = new int[_header.Depth]; + var counts = new int[_header.Depth]; + offset = 0; + int count = 1; + for (int depth = 0; depth < starts.Length; depth++) + { + if (count == 0 || count > masks.Length - offset) + throw FormatError.Corrupted("the point grid is missing an occupancy level."); + starts[depth] = offset; + counts[depth] = count; + long children = 0; + foreach (byte value in masks.AsSpan(offset, count)) + { + if (value == 0) throw FormatError.Corrupted("an internal voxel has no children."); + children += BitOperations.PopCount(value); + } + if (children > _header.Count) + throw FormatError.Corrupted("an occupancy level exceeds the declared point count."); + offset += count; + count = (int)children; + } + if (offset != masks.Length || count != _header.Count) + throw FormatError.Corrupted("the point grid disagrees with its declared leaf count."); + return (starts, counts); + } + + public override IEnumerable ReadPoints(PclReadOptions? options = null) + { + options ??= PclReadOptions.Default; + if (options.MaxPoints == 0) yield break; + using var stream = File.OpenRead(_path); + var blocks = ReadBlocks(stream, out int geometryBytes); + var masks = new byte[geometryBytes]; + var (positions, nextRecords) = ReadLevels(stream, blocks, masks); + var nodes = new Node[_header.Depth]; + var pages = new AttributePage[_header.Depth + 1]; + int depth = 0, index = 0, skip = 0; + ulong yielded = 0; + double resolution = 1.0 / (1 << _header.Depth); + nodes[0].Remaining = masks[positions[0]++]; + nodes[0].First = true; + + // Visiting each level in the same order as its masks avoids holding an entire voxel frontier. + while (depth >= 0) + { + Node node = nodes[depth]; + if (node.Remaining == 0) + { + depth--; + continue; + } + int slot = BitOperations.TrailingZeroCount(node.Remaining); + nodes[depth].Remaining &= node.Remaining - 1; + nodes[depth].First = false; + int x = (node.X << 1) | (slot & 1); + int y = (node.Y << 1) | ((slot >> 1) & 1); + int z = (node.Z << 1) | (slot >> 2); + // The first occupied child retains the parent attributes. + int record = node.First ? node.Record : nextRecords[depth]++; + int recordDepth = node.First ? node.RecordDepth : depth + 1; + + if (depth + 1 < nodes.Length) + { + depth++; + nodes[depth] = new Node(x, y, z, masks[positions[depth]++], true, record, recordDepth); + continue; + } + index++; + if (skip-- > 0) continue; + skip = options.SubsampleStep - 1; + var position = ToWorld(new((x + .5) * resolution, (y + .5) * resolution, (z + .5) * resolution), + _header.Origin, _header.Size); + var (color, intensity) = ReadAttributes(stream, blocks, ref pages[recordDepth], record); + yield return new PclPoint(position, color, intensity, Index: yielded++); + if (yielded >= (ulong)(options.MaxPoints ?? long.MaxValue)) yield break; + } + if (index != _header.Count) throw FormatError.Corrupted("point traversal ended early."); + } + + private record struct Node(int X, int Y, int Z, int Remaining, bool First, int Record, int RecordDepth); + + private struct AttributePage + { + internal int Start, End, Block; + internal byte[]? Color, Intensity; + } + + private (PclColor?, float?) ReadAttributes(FileStream stream, Block[] blocks, ref AttributePage page, int record) + { + if (!HasColors && !HasIntensities) return (null, null); + if (record < page.Start || record >= page.End) + { + int low = page.Block, high = blocks.Length - 1; + while (low < high) + { + int mid = low + (high - low) / 2; + if (record < blocks[mid].FirstRecord + blocks[mid].Records) high = mid; + else low = mid + 1; + } + var block = blocks[low]; + int within = record - block.FirstRecord; + int begin = within / AttributePagePoints * AttributePagePoints; + int count = Math.Min(AttributePagePoints, block.Records - begin); + if (HasColors) + { + page.Color ??= new byte[4 * AttributePagePoints]; + Read(stream, block.ColorOffset + 4L * begin, page.Color.AsSpan(0, 4 * count)); + } + if (HasIntensities) + { + page.Intensity ??= new byte[2 * AttributePagePoints]; + Read(stream, block.IntensityOffset + 2L * begin, page.Intensity.AsSpan(0, 2 * count)); + } + (page.Start, page.End, page.Block) = (block.FirstRecord + begin, block.FirstRecord + begin + count, low); + } + int index = record - page.Start; + PclColor? color = page.Color is { } bgra ? new PclColor(bgra[4 * index + 2], bgra[4 * index + 1], bgra[4 * index]) : null; + float? intensity = page.Intensity is { } shorts ? Bytes.ReadUInt16LE(shorts.AsSpan(2 * index)) / 65535.0f : null; + return (color, intensity); + } +} diff --git a/src/PclIO/Formats/Leica/LgsxDocument.cs b/src/PclIO/Formats/Leica/LgsxDocument.cs index 12bfbe1..4ebcd1b 100644 --- a/src/PclIO/Formats/Leica/LgsxDocument.cs +++ b/src/PclIO/Formats/Leica/LgsxDocument.cs @@ -58,6 +58,10 @@ public sealed class LgsxDocument : PclDocument private readonly List _setups = []; private readonly bool _isLgsLegacy; + internal bool HasUnsupportedLegacyPoints { get; private set; } + internal const string UnsupportedLegacyPointsMessage = + "The Leica LGS point encoding or data mask is unsupported. Convert the project to LGSx to read its points."; + private LgsxDocument(string path, long fileSize, string guid, string version, bool isLegacy) : base(path, fileSize) { @@ -83,13 +87,14 @@ internal void AddWarning(string message) } /// - /// Returns the sum of the declared point counts in the version 22 block headers, or null for other layouts. - /// This reads the block headers and does not decompress their data. + /// Returns the declared point count of a supported native point section, or null when unavailable. + /// This reads metadata without decoding the points. /// public long? GetEncodedPointCount() { + if (_scans.FirstOrDefault() is LegacyLgsScan legacy) return legacy.PointCount; var entry = Entries.FirstOrDefault(e => e.Name.Equals("PointCloud", StringComparison.OrdinalIgnoreCase)); - if (entry == null) return null; + if (entry == null || HasUnsupportedLegacyPoints) return null; using var stream = File.OpenRead(FilePath); var chain = ReadBlockChain(stream, entry); if (chain.Count == 0) return null; @@ -110,6 +115,33 @@ internal void AddWarning(string message) return total; } + // Both containers share the leading signature. Published files distinguish their format in the footer. + internal static PclFileKind? DetectFooterKind(Stream stream) + { + ReadOnlySpan signature = "Leica Project File "u8; + Span footer = stackalloc byte[signature.Length + 1 + sizeof(uint) + sizeof(ulong)]; + long origin = stream.Position; + if (stream.Length - origin < ContainerMagic.Length + footer.Length) return null; + try + { + stream.Position = stream.Length - footer.Length; + if (stream.ReadAtLeast(footer, footer.Length, throwOnEndOfStream: false) != footer.Length || + !footer.StartsWith(signature)) + return null; + + return footer[signature.Length] switch + { + (byte)'*' => PclFileKind.LeicaLgs, + (byte)'X' => PclFileKind.LeicaLgsx, + _ => null, + }; + } + finally + { + stream.Position = origin; + } + } + /// Opens a Leica container and reads its table of contents. /// Path of the .lgsx or .lgs file. /// Read options; currently unused when opening. @@ -127,7 +159,9 @@ public static LgsxDocument Open(string path, PclReadOptions? options = null) if (fs.ReadAtLeast(magic, magic.Length, throwOnEndOfStream: false) < magic.Length || !magic.AsSpan().SequenceEqual(ContainerMagic)) throw FormatError.Corrupted("not a Leica LGSx file, container signature mismatch."); - bool isLegacy = path.EndsWith(".lgs", StringComparison.OrdinalIgnoreCase); + PclFileKind? footerKind = DetectFooterKind(fs); + bool isLegacy = footerKind == PclFileKind.LeicaLgs || + (footerKind == null && path.EndsWith(".lgs", StringComparison.OrdinalIgnoreCase)); // The last 8 bytes hold the offset of the table of contents. fs.Seek(-8, SeekOrigin.End); @@ -235,8 +269,8 @@ public static LgsxDocument Open(string path, PclReadOptions? options = null) var setup = new LgsxSetup(setupId, name, payloadOffset, payloadLength); - // The payload of a setup entry holds its record: the pose, the bounds and the range of its points. - var record = ReadSetupRecord(fs, setup); + // Only the LGSx setup record layout is known. + var record = footerKind != PclFileKind.LeicaLgs ? ReadSetupRecord(fs, setup) : null; if (record != null) { setup = setup with @@ -256,12 +290,24 @@ public static LgsxDocument Open(string path, PclReadOptions? options = null) // The points are assigned to the setups when the container says which part of the point data belongs to // each of them; otherwise all points stay in one scan. - var assignments = pointCloudEntry != null + if (footerKind == PclFileKind.LeicaLgs && + pointCloudEntry is { Size: >= 4 } && !HasReadablePointHeader(fs, pointCloudEntry)) + { + if (LegacyLgsScan.TryOpen(fs, pointCloudEntry) is { } scan) + { + document._scans.Add(scan); + return document; + } + document.HasUnsupportedLegacyPoints = true; + } + var assignments = pointCloudEntry != null && !document.HasUnsupportedLegacyPoints ? AssignBlocksToSetups(path, pointCloudEntry, document._setups) : null; // The number of points is read from the container when it states it; otherwise it is counted by decoding. - long? declaredCount = pointCloudEntry != null ? ReadDeclaredPointCount(fs, pointCloudEntry) : null; + long? declaredCount = pointCloudEntry != null && !document.HasUnsupportedLegacyPoints + ? ReadDeclaredPointCount(fs, pointCloudEntry) + : null; if (assignments != null) { @@ -296,11 +342,13 @@ public static LgsxDocument Open(string path, PclReadOptions? options = null) document: document)); } - if (scanSetups.Count > 0) + if (scanSetups.Count > 0 && !document.HasUnsupportedLegacyPoints) document._warnings.Add($"The container lists {scanSetups.Count} setup entries; points are not assigned to them and are returned as one scan."); } - if (document._scans.Count > 0) + if (document.HasUnsupportedLegacyPoints) + document._warnings.Add(UnsupportedLegacyPointsMessage); + else if (document._scans.Count > 0) { if (pointCloudEntry == null) document._warnings.Add("No point data entry was found; scans have no readable points."); @@ -365,6 +413,14 @@ private sealed record SetupRecord(PclVector3 Translation, PclBounds Bounds, ulon pointCount > long.MaxValue ? -1 : (long)pointCount); } + private static bool HasReadablePointHeader(FileStream fs, LgsxEntry entry) + { + Span header = stackalloc byte[4]; + fs.Position = (long)entry.Offset; + fs.ReadExactly(header); + return header.SequenceEqual(PointDataMagic); + } + /// /// Reads the number of points that the header of the point data declares, or null when it declares none. /// A damaged header yields no count, so that the points are counted by decoding them. @@ -603,6 +659,7 @@ private sealed class ReadState /// first access decodes the whole point data and caches the result, which can be slow for large files. /// /// The point data is malformed; the exception is thrown by the first access. + /// The container uses an unsupported legacy point encoding. public override long PointCount => _declaredPointCount ?? (_pointCount >= 0 ? _pointCount : _pointCount = CountPoints()); @@ -641,7 +698,7 @@ private sealed record NativeLayout(int PointCount, int Intensity, int Color); private (bool, bool, bool) DetectChannels() { - if (_entry == null) return (false, false, false); + if (_entry == null || _document?.HasUnsupportedLegacyPoints == true) return (false, false, false); using var fs = File.OpenRead(_filePath); foreach (var (start, length) in LgsxDocument.ReadBlockChain(fs, _entry)) @@ -679,6 +736,7 @@ private sealed record NativeLayout(int PointCount, int Intensity, int Color); /// /// Read options; null uses defaults. /// The point data is malformed, declares oversized data or is incomplete in strict mode. + /// The container uses an unsupported legacy point encoding. public override IEnumerable ReadPoints(PclReadOptions? options = null) { options ??= PclReadOptions.Default; @@ -686,6 +744,8 @@ public override IEnumerable ReadPoints(PclReadOptions? options = null) long targetCount = options.MaxPoints ?? long.MaxValue; if (targetCount <= 0) yield break; + if (_document?.HasUnsupportedLegacyPoints == true) + throw FormatError.Unsupported(LgsxDocument.UnsupportedLegacyPointsMessage); int step = Math.Max(1, options.SubsampleStep); long yielded = 0; diff --git a/src/PclIO/Internal/KindDetector.cs b/src/PclIO/Internal/KindDetector.cs index c4e9011..8690b7a 100644 --- a/src/PclIO/Internal/KindDetector.cs +++ b/src/PclIO/Internal/KindDetector.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Text; using System.Text.Json; +using PclIO.Formats.Leica; namespace PclIO.Internal; @@ -139,7 +140,7 @@ public static PclFileKind Detect(Stream stream, string? extension = null) return PclFileKind.E57; if (head.StartsWith(LeicaMagic)) - return extension == ".lgs" ? PclFileKind.LeicaLgs : PclFileKind.LeicaLgsx; + return LgsxDocument.DetectFooterKind(stream) ?? (extension == ".lgs" ? PclFileKind.LeicaLgs : PclFileKind.LeicaLgsx); if (head.StartsWith(RcsMagic)) return PclFileKind.RecapScan; diff --git a/src/PclIO/PclReadOptions.cs b/src/PclIO/PclReadOptions.cs index 2c572fc..7b29105 100644 --- a/src/PclIO/PclReadOptions.cs +++ b/src/PclIO/PclReadOptions.cs @@ -104,7 +104,7 @@ public double EdgeWiseCoordinateScale /// /// Blocks of a scan to read, in file order; null reads all of the scan's blocks. A range that runs past the last /// block simply ends there. Only readers whose points come in independent blocks use this option; the others read - /// the whole scan and ignore it. Currently only the Leica reader honours it. + /// the whole scan and ignore it. Currently only the Leica LGSx block reader honours it. /// public BlockRange? Blocks { get; init; } @@ -149,7 +149,7 @@ public double TextCoordinateScale /// /// How many blocks a reader may decode at once. The points keep file order whatever the value is. /// Only readers with independent blocks use this option; the others read sequentially and ignore it. - /// Currently only the Leica reader decodes in parallel, holding the decoded points of the blocks in flight. + /// Currently only the Leica LGSx block reader decodes in parallel, holding the decoded points of the blocks in flight. /// The default is 1: sequential decoding with constant memory besides the block being read. /// /// The value is less than 1. diff --git a/tests/PclIO.Tests/KindDetectionTests.cs b/tests/PclIO.Tests/KindDetectionTests.cs index 6212be6..c8e1796 100644 --- a/tests/PclIO.Tests/KindDetectionTests.cs +++ b/tests/PclIO.Tests/KindDetectionTests.cs @@ -33,6 +33,18 @@ public void Detects_Leica_Lgsx_Signature() => public void Detects_Leica_Lgs_By_Extension() => Assert.Equal(PclFileKind.LeicaLgs, Detect(SyntheticFixtures.CreateSyntheticLgsx(), "site.lgs")); + [Theory] + [InlineData((byte)'*', "renamed.lgsx", PclFileKind.LeicaLgs)] + [InlineData((byte)'X', "renamed.lgs", PclFileKind.LeicaLgsx)] + [InlineData((byte)'*', "renamed.dat", PclFileKind.LeicaLgs)] + public void Leica_Footer_Distinguishes_The_Container_Regardless_Of_Extension(byte marker, string name, PclFileKind expected) + { + byte[] bytes = SyntheticFixtures.CreateSyntheticLgsx(containerMarker: marker); + using var stream = new MemoryStream(bytes); + Assert.Equal(expected, PclFile.DetectKind(stream, name)); + Assert.Equal(0, stream.Position); + } + [Theory] [InlineData("project.smf")] [InlineData("project.srf")] diff --git a/tests/PclIO.Tests/LegacyLgsTests.cs b/tests/PclIO.Tests/LegacyLgsTests.cs new file mode 100644 index 0000000..7229c87 --- /dev/null +++ b/tests/PclIO.Tests/LegacyLgsTests.cs @@ -0,0 +1,110 @@ +using System.Text; +using PclIO.Formats.Leica; +using Xunit; + +namespace PclIO.Tests; + +public sealed class LegacyLgsTests +{ + [Fact] + public void Opens_Masked_Grid_And_Assigns_Progressive_Colors_To_Their_Voxels() + { + using var dir = new TempDirectory(); + using var doc = Assert.IsType(PclFile.Open(dir.Write("old.lgs", CreateContainer()))); + Assert.Equal(PclFileKind.LeicaLgs, doc.Kind); + Assert.Equal(4, doc.GetEncodedPointCount()); + var scan = Assert.Single(doc.Scans); + Assert.True(scan.HasColors); + Assert.True(scan.HasIntensities); + var points = scan.ReadPoints().ToArray(); + Assert.Equal( + new[] { new PclVector3(-2.5, 2.5, .5), new(-2.5, 2.5, 1.5), new(-1.5, 5.5, 2.5), new(-.5, 5.5, 2.5) }, + points.Select(p => p.Position)); + Assert.Equal(new byte[] { 10, 30, 20, 40 }, points.Select(p => p.Color!.Value.R)); + Assert.Equal(new int[] { 1000, 3000, 2000, 4000 }.Select(v => (float?)(v / 65535.0f)), points.Select(p => p.Intensity)); + Assert.Equal(new[] { points[0], points[2] with { Index = 1 } }, + scan.ReadPoints(new PclReadOptions { SubsampleStep = 2, MaxPoints = 2 }).ToArray()); + } + + [Fact] + public void Rejects_Occupancy_That_Disagrees_With_The_Directory() + { + using var dir = new TempDirectory(); + using var doc = PclFile.Open(dir.Write("invalid.lgs", CreateContainer(invalid: true))); + Assert.Throws(() => Assert.Single(doc.Scans).ReadPoints().First()); + } + + private static byte[] CreateContainer(bool invalid = false) + { + using var memory = new MemoryStream(); + using var writer = new BinaryWriter(memory); + writer.Write("wild::geosystems"u8); + long payloadStart = memory.Position; + writer.Write("UDS4\u0007\0\0\0"u8); + writer.Write(0u); + writer.Write(4.0); + writer.Write(1.0); + writer.Write(3u); + foreach (double value in new double[] { 1, 1, 1, -4, 2, 0, .5, .5, .5, .5, .5, .5, .5, .5, .5 }) + writer.Write(value); + writer.Write(2u); + WriteField("UniquePointCount"); + WriteField("4"); + WriteField("ModelAttributes"); + WriteField("udIntensity:u16 udRGB:u32"); + long metadataEnd = memory.Position; + memory.Position = payloadStart + 8; + writer.Write((uint)(metadataEnd - payloadStart - 8)); + memory.Position = metadataEnd; + foreach (uint value in new uint[] { 2, 256, 0, 2, 3, 4, 1, 1 }) writer.Write(value); + writer.Write(new byte[16]); + + const int descriptorBytes = 16; + const int blockBytes = 20 + descriptorBytes + 3 + 4 * 6; + WriteDescriptor(); + writer.Write(0UL); + writer.Write(0u); + writer.Write(6u); + writer.Write(0x10001u); + WriteDescriptor(); + writer.Write(new byte[] { 0x81, 0x22, invalid ? (byte)0x1c : (byte)0x0c }); + for (int i = 1; i <= 4; i++) writer.Write((ushort)(i * 1000)); + for (int i = 1; i <= 4; i++) writer.Write(new byte[] { 55, 70, (byte)(i * 10), 255 }); + memory.SetLength(payloadStart + 3 * 1024); + memory.Position = memory.Length; + long descriptor = memory.Position; + writer.Write(new byte[10]); + writer.Write((ushort)11); + writer.Write("PointCloud\0"u8); + writer.Write((byte)3); + writer.Write((ulong)payloadStart); + writer.Write((ulong)(descriptor - payloadStart)); + writer.Write(new byte[96]); + long toc = memory.Position; + writer.Write(1u); + writer.Write((ulong)descriptor); + writer.Write("Leica Project File *"u8); + writer.Write(0u); + writer.Write((ulong)toc); + byte[] result = memory.ToArray(); + var key = new byte[1024]; + new Random(42).NextBytes(key); + for (int i = (int)payloadStart; i < descriptor; i++) result[i] ^= key[(i - (int)payloadStart) % key.Length]; + return result; + + void WriteField(string value) + { + writer.Write((ushort)(value.Length + 1)); + writer.Write(Encoding.ASCII.GetBytes(value)); + writer.Write((byte)0); + } + + void WriteDescriptor() + { + writer.Write(blockBytes); + writer.Write(0u); + writer.Write(8u); + writer.Write(16u); + } + } +} diff --git a/tests/PclIO.Tests/NativeScanCodecTests.cs b/tests/PclIO.Tests/NativeScanCodecTests.cs index 111ce71..f517e36 100644 --- a/tests/PclIO.Tests/NativeScanCodecTests.cs +++ b/tests/PclIO.Tests/NativeScanCodecTests.cs @@ -65,6 +65,36 @@ public void Lgsx_Morton96_Rejects_A_Count_That_Does_Not_Match_Its_Planes() Assert.Throws(() => doc.ReadAllPoints().ToArray()); } + [Theory] + [InlineData((byte)'*')] + [InlineData((byte)'X')] + public void Leica_Unknown_Point_Payload_Reports_An_Error_For_Its_Container(byte marker) + { + using var dir = new TempDirectory(); + byte[] bytes = SyntheticFixtures.CreateSyntheticLgsx(containerMarker: marker, assignPointsToSetups: true); + int pointData = bytes.AsSpan().IndexOf("mMPK"u8); + Assert.True(pointData > 0); + bytes.AsSpan(pointData, 4).Clear(); + using var doc = LgsxDocument.Open(dir.Write("scan.lgsx", bytes)); + Assert.Contains(doc.Entries, entry => entry.Name == "PointCloud"); + var scan = Assert.Single(doc.Scans); + if (marker == (byte)'*') + { + Assert.Equal(PclFileKind.LeicaLgs, doc.Kind); + Assert.Null(doc.GetEncodedPointCount()); + Assert.Null(Assert.Single(doc.Setups).Translation); + Assert.False(scan.HasColors); + Assert.Throws(() => scan.PointCount); + var error = Assert.Throws(() => scan.ReadPoints().First()); + Assert.Contains("Convert the project to LGSx", error.Message); + } + else + { + Assert.Equal(PclFileKind.LeicaLgsx, doc.Kind); + Assert.Throws(() => scan.ReadPoints().First()); + } + } + [Fact] public void E57_Image_Blob_Checks_Header_And_Each_Page() { diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs index d39b7c2..7b2a9cc 100644 --- a/tests/PclIO.Tests/SyntheticFixtures.cs +++ b/tests/PclIO.Tests/SyntheticFixtures.cs @@ -174,7 +174,7 @@ public static byte[] CreateSyntheticLgsx(IReadOnlyList? points IReadOnlyList? extraPlanes = null, int setupCount = 1, bool assignPointsToSetups = false, bool overlappingSetupRanges = false, bool collidingSetupNames = false, bool damagedSetupRecord = false, bool damagedPointData = false, bool withPointCount = true, bool oversizedFrame = false, bool unknownBlock = false, bool unknownFirstBlock = false, bool truncatedFrameList = false, bool fewPlanes = false, - int blockCount = 0, int damagedBlock = -1, bool nativeLeicaBlock = false) + int blockCount = 0, int damagedBlock = -1, bool nativeLeicaBlock = false, byte? containerMarker = null) { points ??= DefaultLeicaPoints; using var ms = new MemoryStream(); @@ -238,6 +238,12 @@ public static byte[] CreateSyntheticLgsx(IReadOnlyList? points if (withPointData) bw.Write((ulong)pointEntry); bw.Write(Encoding.ASCII.GetBytes("build 2024.1.0 {12345678-1234-1234-1234-123456789abc}")); + if (containerMarker is { } marker) + { + bw.Write("Leica Project File "u8); + bw.Write(marker); + bw.Write(205u); + } bw.Write((ulong)tocOffset); return ms.ToArray(); }