From de561857d888e4212ab7692ec72ec4e311a3bfbe Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:53:39 +0000 Subject: [PATCH] Decode the points of ReCap scans from the sections of the file The reader took the blocks of the leaves of a scan for point records of one fixed size and rejected a file whose blocks did not fit that size. A table in the header names the sections of the file: a leaves section with one record per leaf of the octree, and a points section with one block per leaf that holds the index words of the leaf followed by its 16-byte records. - A position is three 18-bit fields on a 1 mm grid, counted from the cube of the leaf. Intensity, colour and a packed normal follow the flags of the header, and a point has a normal only when its record states a plain cell code. - The sections are taken from the table whatever their order, and the file is checked as a whole before the first point is returned. - PointCount is the number of points the file stores. The count stated in the header is not that number and stays as DeclaredPointCount. --- CHANGELOG.md | 19 + README.md | 5 +- docs/getting-started.md | 4 +- docs/public-api.md | 8 +- src/PclIO/Formats/Recap/RcsScanDocument.cs | 452 +++++++++++---------- tests/PclIO.Tests/CliTests.cs | 16 +- tests/PclIO.Tests/FormatTests.cs | 362 +++++++++++++---- tests/PclIO.Tests/InputHardeningTests.cs | 204 +++++++++- tests/PclIO.Tests/RcsScanBuilder.cs | 223 ++++++++++ tests/PclIO.Tests/RealFileTests.cs | 81 ++++ tests/PclIO.Tests/SyntheticFixtures.cs | 114 ++---- 11 files changed, 1072 insertions(+), 416 deletions(-) create mode 100644 tests/PclIO.Tests/RcsScanBuilder.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index b56be58..458397f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- ReCap scans (`.rcs`) of container major version 3 are decoded. The points come from the leaves of the file and the blocks the + points section holds for them: a position on a 1 mm grid, counted from the cube of the leaf, an intensity, an 8-bit colour and + a normal packed as a code that names a cell on a cube face. The sections are taken from the table of the header whatever their + order, the other sections are skipped, and a leaf may hold more index words than its points need. A point has a normal only + when its record states a plain cell code. Before, a file whose leaf blocks were not a whole multiple of a record size was + rejected. +- A ReCap scan is checked as a whole before its first point is returned. A section table that does not fit in the file, a + missing or duplicated section, a leaf table that does not fit in its section, a leaf block that does not fit its points and + blocks that do not fill the points section are rejected with `InvalidDataException`, and nothing is returned. Before, the + records of a file were checked one at a time while its points were streamed. +- The point count of a ReCap scan is the number of points the file stores, which a full read returns. The count stated in the + header is not that number; it stays available as `RcsScanDocument.DeclaredPointCount`. A scan that states a count in its header + but holds no leaf reports 0 points. +- The channels of a ReCap scan (`HasColors`, `HasIntensities`, `HasNormals`) follow flags of the header, so they are known from + the header alone; before, they were derived from the size of a node payload. The bytes of a channel are read only when the + header states the channel. + ## [0.1.1] - 2026-11-25 ### Added diff --git a/README.md b/README.md index 018df30..9355fb9 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,8 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies | Format | Extensions | Support level | | --- | --- | --- | | 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. Images are not read, so a scan with them still lists and reads its points. Page checksums are verified. | -| ReCap scan | `.rcs` | Experimental. The header is read; point decoding covers the node layouts that are described in the code, which is the one of major version 3. A file of another version is listed with its header, but reading its points fails with a message that names the version. A further layout is described only when the files of that version may be used for the tests, so that its offsets can be verified. The channels of the points follow from the size of the payload of the nodes: colour and intensity when the records are long enough, and normals when the node holds the plane of them. A node payload whose byte count is not a whole multiple of a known record size, as in BLK360 exports (container 3.2) whose records are variable-length, is rejected with a message that names the container version instead of being guessed. | +| ReCap scan | `.rcs` | Experimental; container major version 3. The points come from the leaves of the file: a position on a 1 mm grid, an intensity, an 8-bit colour and a packed normal for each. The channels that are read follow flags of the header. The file is checked as a whole before the first point is returned, and a section, a leaf or a block that does not fit the file is rejected with `InvalidDataException` instead of being read at a guess. A file of another major version is listed with its header, but reading its points fails with a message that names the version. A further version is decoded only when files of it may be used for the tests, so that +its layout can be verified. `PointCount` is the number of points the file stores; the count stated in the header is not, and it is available as `DeclaredPointCount`. Scale and translation of the header are applied when `ApplyTransform` is set; the rotation is not. | | ReCap project | `.rcp` | Lists the scans of the project manifest and opens the `.rcs` files it finds next to the project. The transform of a scan node places the scan in the project and is applied to its points unless `ApplyTransform` is false; when the manifest states no transform, the transform of the scan file is used. | | Leica scan container | `.lgsx`, `.lgs` | Experimental. Points are decoded from the compressed point blocks: position, and colour, intensity and normals when the block has them. 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. | | FARO scan | `.fls`, or a FARO scan folder | Experimental. 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. | @@ -145,7 +146,7 @@ outside the file is fetched. | --- | --- | | E57 | XML section 32 MiB, nesting depth 64, 1,000,000 elements; declared record counts up to 2^40; at most 65535 fields in a point prototype; at most 4096 consecutive packets without points. | | ReCap project | Manifest 64 MiB (declared and real size), nesting depth 64, 1,000,000 elements, 65,536 scan nodes. | -| ReCap scan | 500,000 nodes in the node table, which must fit in the file together with the node payloads. | +| ReCap scan | 64 sections in the table; 500,000 leaves, and the table of the leaves must fit in its section; every leaf block must fit its points and the points section, and the blocks must fill the points section. | | Leica | 10,000 container entries; per point block at most 64 compressed streams, 10,000,000 compressed bytes per stream, 16 MiB per decompressed stream (checked before allocation) and 128 MiB decompressed in all; over all blocks of one read 1 GiB plus 64 times the file size decompressed. | | FARO | Parameters 1 MiB; scan grid of at most 2^27 cells (134,217,728); a distance stream too small for the declared grid is refused; each compressed data stream is held in memory (see above) and is inflated in chunks, and must not inflate beyond its grid size plus 64 KiB. Compound file: 65,536 directory entries, depth 16. | | PinPoint | Manifest 64 MiB and the default nesting depth of `System.Text.Json` (64); 100,000 scans. The parsed manifest needs memory of about 15 times its size, so a manifest at the limit needs about 1 GB. Sectioned data file: at most 16 sections, a property table of at most 1 MiB nested at most 8 levels, copies in a compressed stream at most 8 MiB back with a decoder window of at most 8 MiB per stream; the sections must be contiguous and fill the file, and the `Points`, `RGB8`, `Intensities8`, `Normals` and `FilterBits` streams must decode to exactly 12, 3, 1, 12 and 1 bytes per stored point. | diff --git a/docs/getting-started.md b/docs/getting-started.md index 133f9a7..6a36d05 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -84,7 +84,7 @@ reading), `NotSupportedException` (unrecognised format or unsupported feature) o | Format | Extensions | Support level | | --- | --- | --- | | ASTM E57 | `.e57` | Points decoded for a defined subset (uncompressed bit-packed streams, single or double precision Cartesian coordinates, 8-bit colour and intensity). Per-point validity flags and images are not read. | -| ReCap scan | `.rcs` | Experimental; layout of major version 3 only. | +| ReCap scan | `.rcs` | Experimental; layout of major version 3 only. Positions, intensity, colour and normals; rotation is not applied. | | ReCap project | `.rcp` | Lists scans; opens the `.rcs` files it finds next to the project. Node transforms are not applied. | | Leica scan container | `.lgsx`, `.lgs` | Experimental; poses and bounds are not read, and all points of a container form one scan. | | FARO scan | `.fls`, or a FARO scan folder | Experimental; the scan grid comes from the stored parameters. A folder scan is read with an assumed layout, and a warning says so. | @@ -101,7 +101,7 @@ are decided by extension alone, without a content check. A `.pcd` file is recogn and a `.ply` file by its magic word and header structure. Anything else is `PclFileKind.Unknown`. The rules are in [Public API](public-api.md#format-detection). Anything a decoder does not support fails instead of being guessed, apart from the assumptions named in the README (the FARO folder -record layout, the EdgeWise position scale and the ReCap scan channel flags). The sizes and counts a reader accepts are limited; a +record layout and the EdgeWise position scale). The sizes and counts a reader accepts are limited; a file that exceeds a limit is rejected with `InvalidDataException`, with the exceptions listed in the README. ## Limitations diff --git a/docs/public-api.md b/docs/public-api.md index 8036d0a..05fce6a 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -75,7 +75,7 @@ drop points that fail a plausibility rule (see the README), so a scan can yield | Reader | `PointCount` | |---|---| | E57 | Declared by the file. It is not checked against the point data until the points are read. Points that the validity flags mark as invalid are skipped, so a read can yield fewer points. | -| ReCap scan | Declared in the header. It is not checked against the node table. The node layout of major version 3 is decoded; a file of another version is listed but its points cannot be read (`RcsScanDocument.DecodedNodeLayoutVersions` names the decoded versions). | +| ReCap scan | The number of points the file stores, summed over its leaves; a full read returns exactly this many. The header states a count of its own, `RcsScanDocument.DeclaredPointCount`, which is not that number. The leaves are read and checked on the first access to the count or to the points, which throws `InvalidDataException` for a malformed file. The layout of major version 3 is decoded; a file of another version reports the count of the header, and its points cannot be read (`RcsScanDocument.DecodedNodeLayoutVersions` names the decoded versions). | | ReCap project | Declared by the project manifest; 0 when the manifest states none. | | Leica | The number of points the container states, when it states one; otherwise it is computed. The computed value needs the first access to decode all of the point data and caches the result, which can be slow on large files; the access throws `InvalidDataException` for corrupt data. A container that assigns its points to its setups has one scan per setup, each with the id and the name of its setup; otherwise the container is one scan with the id `unified-cloud`. The `Transform` and the `Bounds` of a setup are read from its record and are empty when the record does not hold them. `Blocks` applies per scan in file order; a truncated read (fewer points yielded than selected, via `MaxPoints`) reports no incomplete-data warning. | | FARO | The number of valid returns, which is counted on the first access by reading the distance data of the scan; `FaroScan.GridSize` is the size of the scan grid (rows times columns). For a folder scan the grid size is limited by the size of the data stream, and `FaroScan.RecordSize` is the size of one sample in bytes. | @@ -97,9 +97,9 @@ drop points that fail a plausibility rule (see the README), so a scan can yield | CC BIN | The point count declared for the entity. The reader rejects files with a truncated XYZ block or a point count that exceeds the available XYZ data. Points with non-finite coordinates are skipped. Packed point normals are decoded in file versions 41, 42 and 50. A stored zero direction is returned as `PclVector3.Zero`. | `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 -from the node table, so they are known after the node table has been read; a node whose points hold no colour gives its points -no colour. +are true when the `.rcs` file was found and false otherwise, without the file being opened. A ReCap scan reads them from the flags of +its header; the bytes of a channel are read only when the header states the channel. A point of a scan with normals has one only +when its record states a cell code. ## Format documents diff --git a/src/PclIO/Formats/Recap/RcsScanDocument.cs b/src/PclIO/Formats/Recap/RcsScanDocument.cs index 2dd7a58..c55e041 100644 --- a/src/PclIO/Formats/Recap/RcsScanDocument.cs +++ b/src/PclIO/Formats/Recap/RcsScanDocument.cs @@ -5,15 +5,16 @@ namespace PclIO.Formats.Recap; /// -/// Reads the header of a ReCap scan file (.rcs). Point decoding is experimental: only the node layouts that are -/// described in are decoded, and any other version is rejected instead of guessed. +/// Reads a ReCap scan file (.rcs). Point decoding covers the container major versions named by +/// ; a file of another version is listed with its header, and reading its points +/// fails with a message that names the version instead of guessing its layout. /// public sealed class RcsScanDocument : PclDocument { /// public override PclFileKind Kind => PclFileKind.RecapScan; - /// Major versions of the container whose node layout the reader decodes. + /// Major versions of the container whose layout the reader decodes. public static IReadOnlyList DecodedNodeLayoutVersions { get; } = [3]; /// Container major version from the header. @@ -34,20 +35,22 @@ public sealed class RcsScanDocument : PclDocument /// Octree bounding box stored in the header. public PclBounds OctreeBounds { get; } - /// Point count declared in the header; it is not cross-checked against the node table. + /// + /// Point count stated in the header. It is not the number of points the file stores, which can be fewer and is the + /// of the scan. + /// public long DeclaredPointCount { get; } - /// True when the file holds colour for its points; it is read from the node table. - public bool HasColorData => _scans.Count > 0 && _scans[0].HasColors; + /// True when the header states that the points hold a colour. + public bool HasColorData { get; } /// - /// True when the file can hold normals for its points; it is read from the node table, and a single point may still - /// have none. + /// True when the header states that the points can hold normals; a single point may still have none. /// - public bool HasNormalData => _scans.Count > 0 && _scans[0].HasNormals; + public bool HasNormalData { get; } - /// True when the file holds an intensity for its points; it is read from the node table. - public bool HasIntensityData => _scans.Count > 0 && _scans[0].HasIntensities; + /// True when the header states that the points hold an intensity. + public bool HasIntensityData { get; } /// public override IReadOnlyList Scans => _scans; @@ -63,7 +66,10 @@ private RcsScanDocument( PclTransform transform, PclBounds localBounds, PclBounds octreeBounds, - long pointCount) + long pointCount, + bool hasColor, + bool hasNormals, + bool hasIntensity) : base(path, fileSize) { MajorVersion = major; @@ -74,6 +80,9 @@ private RcsScanDocument( LocalBounds = localBounds; OctreeBounds = octreeBounds; DeclaredPointCount = pointCount; + HasColorData = hasColor; + HasNormalData = hasNormals; + HasIntensityData = hasIntensity; var scan = new RcsScan(this, path); _scans.Add(scan); @@ -142,6 +151,11 @@ public static RcsScanDocument Open(string path, PclReadOptions? options = null) if (rawPoints > long.MaxValue) throw FormatError.Corrupted("RCS point count is out of range."); long pointCount = (long)rawPoints; + // Channel flags: a non-zero byte states that the points hold the channel. + bool hasColor = header[0xE0] != 0; + bool hasNormals = header[0xE1] != 0; + bool hasIntensity = header[0xE2] != 0; + // Scan identifier text at a fixed header offset. string guid = Encoding.ASCII.GetString(header.Slice(227, 38)).Trim('\0'); @@ -171,55 +185,46 @@ public static RcsScanDocument Open(string path, PclReadOptions? options = null) transform, localBounds, octreeBounds, - pointCount); + pointCount, + hasColor, + hasNormals, + hasIntensity); } } -/// -/// The layout of the node table of a ReCap scan file, one per container major version. -/// -/// -/// A layout is described only when the files of that version may be used for the tests, so that its offsets can be -/// verified. A file of a version without a described layout is listed with its header, but its points cannot be read: -/// the reader rejects it with a message that names the version. -/// -/// Major version of the container that the layout belongs to. -/// Offset of the node table in the file, in bytes. -/// Size of one entry of the node table, in bytes. -internal sealed record RcsLayout(uint MajorVersion, long NodeTableOffset, int NodeSize) -{ - // The layout of major version 3: the node table starts at a fixed offset and the node payloads occupy the end - // of the file. - private static readonly RcsLayout Version3 = new(3, 98605, 368); - - private static readonly RcsLayout[] Described = [Version3]; - - /// The layout of the given major version, or null when the version has no described layout. - public static RcsLayout? ForVersion(uint majorVersion) => - Described.FirstOrDefault(l => l.MajorVersion == majorVersion); - - /// The major versions whose layout is described, for a message that names them. - public static string DescribedVersions => string.Join(", ", Described.Select(l => l.MajorVersion)); -} - /// Individual scan of an RCS file. public sealed class RcsScan : PclScan { - // Layout of major version 3: the node table starts at a fixed offset and the node - // payloads occupy the end of the file. Both are verified against the file length before use. - private const ulong MaxNodes = 500_000; - - // Bytes of one point record: the position of the point and, when the node holds them, the intensity and the - // colour. A record without them is shorter. + // Limits of what a file may declare; a file that exceeds one of them is malformed. + private const int MaxSections = 64; + private const long MaxLeaves = 500_000; + + // Layout of the decoded container versions. A table in the header names the sections of the file; reading needs the + // leaves section, one record per leaf of the octree, and the points section, one block per leaf in the same order. + // A block holds the index words of the leaf followed by its points as records of 16 bytes. + private const int SectionTableOffset = 0x129; + private const int SectionEntrySize = 24; + private const ulong SectionPoints = 1; + private const ulong SectionLeaves = 2; + private const int LeafRecordSize = 368; private const int PointRecordSize = 16; - private const int PositionRecordSize = 10; - private const int NormalRecordSize = 4; - private const double Quantization = 0.0001; + + // A record holds three 18-bit fields of a 64-bit word, one per axis: millimetres from the corner of the leaf's cube. + private const int FieldBits = 18; + private const ulong FieldMask = (1UL << FieldBits) - 1; + private const double GridStep = 0.001; + + // The normal is a 16-bit field whose low 14 bits name a cell on a cube face; any other bit set means there is none. + private const ushort NormalFlags = 0xC000; + + // Records are read in chunks of whole records; the chunk is a multiple of the record size. + private const int ChunkBytes = 64 * 1024; private readonly RcsScanDocument _document; private readonly string _filePath; - private (bool Colors, bool Intensities, bool Normals)? _channels; + // The leaves of the file, read and checked as a whole on first use. + private LeafTable? _table; /// public override string Id => _document.ScanGuid; @@ -227,8 +232,13 @@ public sealed class RcsScan : PclScan /// public override string Name => Path.GetFileNameWithoutExtension(_filePath); - /// Point count declared in the file header; it is not cross-checked against the node table. - public override long PointCount => _document.DeclaredPointCount; + /// + /// Number of points the file stores, summed over its leaves; a full read returns exactly this many. The header states + /// a count of its own (), which is not the number of stored points. A + /// file of a version the reader does not decode reports the count of the header. Reading a malformed leaf table fails + /// here, as it does when the points are read. + /// + public override long PointCount => IsDecoded ? Table.PointCount : _document.DeclaredPointCount; /// public override PclBounds Bounds => _document.LocalBounds; @@ -236,14 +246,16 @@ public sealed class RcsScan : PclScan /// public override PclTransform Transform => _document.ScanTransform; - /// True when the file holds colour for its points; it is read from the node table. - public override bool HasColors => Channels.Colors; + /// True when the header states that the points hold a colour. + public override bool HasColors => _document.HasColorData; + + /// True when the header states that the points can hold normals; a single point may still have none. + public override bool HasNormals => _document.HasNormalData; - /// True when the file holds normals for its points; it is read from the node table. - public override bool HasNormals => Channels.Normals; + /// True when the header states that the points hold an intensity. + public override bool HasIntensities => _document.HasIntensityData; - /// True when the file holds an intensity for its points; it is read from the node table. - public override bool HasIntensities => Channels.Intensities; + private bool IsDecoded => RcsScanDocument.DecodedNodeLayoutVersions.Contains(_document.MajorVersion); internal RcsScan(RcsScanDocument document, string filePath) { @@ -251,222 +263,224 @@ internal RcsScan(RcsScanDocument document, string filePath) _filePath = filePath; } - private readonly record struct Node(PclVector3 TightMin, uint Points, uint Bytes); - - // The channels of the points follow from the size of the payload of the nodes. - private (bool Colors, bool Intensities, bool Normals) Channels => _channels ??= DetectChannels(); - - private (bool, bool, bool) DetectChannels() - { - var layout = RcsLayout.ForVersion(_document.MajorVersion); - if (layout == null) return (false, false, false); - - try - { - using var fs = File.OpenRead(_filePath); - var nodes = ReadNodeTable(fs, layout, _document.MinorVersion, out _); - - bool colors = false, intensities = false, normals = false; - foreach (var node in nodes) - { - if (node.Points == 0) continue; - long bytesPerPoint = node.Bytes / node.Points; - if (bytesPerPoint >= PointRecordSize) { colors = true; intensities = true; } - if (node.Bytes >= (long)node.Points * (PointRecordSize + NormalRecordSize)) normals = true; - } - - return (colors, intensities, normals); - } - catch (Exception e) when (e is InvalidDataException or NotSupportedException) - { - // A damaged node table or an undecoded payload leaves the channels unknown. - return (false, false, false); - } - } - /// - /// Streams points from the node table (experimental, major version 3 only). Throws - /// for other versions or node payloads that do not match the known layout, - /// and when the node table is inconsistent with the file size. - /// Scale and translation of the header transform are applied when requested; rotation is not. + /// Streams the points of the file (decoded container versions only). Throws for other + /// versions, and when a section, a leaf or a leaf block is inconsistent with the + /// file; the file is checked as a whole, so nothing is returned before it fails. Scale and translation of the header + /// transform are applied when requested; rotation is not. /// public override IEnumerable ReadPoints(PclReadOptions? options = null) { options ??= PclReadOptions.Default; - if (PointCount == 0) yield break; + if (!IsDecoded) + throw FormatError.Unsupported( + $"RCS container version {_document.MajorVersion}.{_document.MinorVersion}: its layout is not described. The described versions are {string.Join(", ", RcsScanDocument.DecodedNodeLayoutVersions)}."); - var layout = RcsLayout.ForVersion(_document.MajorVersion) - ?? throw FormatError.Unsupported( - $"RCS container version {_document.MajorVersion}.{_document.MinorVersion}: the layout of its node table is not described. The described versions are {RcsLayout.DescribedVersions}."); + // The whole file is checked before the first point is returned, so a malformed file yields nothing. + LeafTable table = Table; + if (table.PointCount == 0) yield break; - long targetCount = options.MaxPoints ?? PointCount; + long targetCount = options.MaxPoints ?? long.MaxValue; int step = Math.Max(1, options.SubsampleStep); - long yielded = 0; + bool transform = options.ApplyTransform; + bool hasColor = _document.HasColorData, hasIntensity = _document.HasIntensityData, hasNormals = _document.HasNormalData; - using var fs = File.OpenRead(_filePath); - var nodes = ReadNodeTable(fs, layout, _document.MinorVersion, out long payloadStart); + // The transform of an RCS file is a scale and a translation. A unit scale leaves a normal as it is. + PclTransform scanTransform = _document.ScanTransform; + double scaleX = scanTransform.Scale.X, scaleY = scanTransform.Scale.Y, scaleZ = scanTransform.Scale.Z; + double shiftX = scanTransform.Translation.X, shiftY = scanTransform.Translation.Y, shiftZ = scanTransform.Translation.Z; + bool scaleNormals = transform && scanTransform.Scale != PclVector3.One; - long curOffset = payloadStart; - byte[] chunkBuf = new byte[65536]; - // Normals are read per chunk, so memory stays constant however large a node is. Sized for the shortest - // record, which packs the most points per chunk. - byte[] normalBuf = new byte[chunkBuf.Length / PositionRecordSize * NormalRecordSize]; + using var fs = File.OpenRead(_filePath); + byte[] chunk = new byte[ChunkBytes]; + long yielded = 0; - foreach (var node in nodes) + foreach (Leaf leaf in table.Leaves) { if (yielded >= targetCount) yield break; - if (node.Points == 0 || node.Bytes == 0) - { - curOffset += node.Bytes; - continue; - } - - // The size of the payload tells which channels the points of the node hold: a record with the intensity - // and the colour is longer than one with the position only. - long bytesPerPoint = node.Bytes / node.Points; - bool hasColor = bytesPerPoint >= PointRecordSize; - int recordSize = hasColor ? PointRecordSize : PositionRecordSize; + if (leaf.Points == 0) continue; - // The optional normal plane follows the point records. - bool hasNormals = node.Bytes >= (long)node.Points * (PointRecordSize + NormalRecordSize); - long normalStart = curOffset + ((long)node.Points * recordSize); - - fs.Position = curOffset; - long remaining = (long)node.Points * recordSize; - long pointIdx = 0; + fs.Position = leaf.RecordsOffset; + long remaining = (long)leaf.Points * PointRecordSize; + uint pointInLeaf = 0; while (remaining > 0) { - // A chunk holds whole records only, so the next one starts at a record boundary. - int toRead = (int)Math.Min(chunkBuf.Length / recordSize * recordSize, remaining); - fs.ReadExactly(chunkBuf, 0, toRead); + int toRead = (int)Math.Min(ChunkBytes, remaining); + fs.ReadExactly(chunk, 0, toRead); remaining -= toRead; - int ptsInBlock = toRead / recordSize; - if (hasNormals) - { - long resume = fs.Position; - fs.Position = normalStart + (pointIdx * NormalRecordSize); - fs.ReadExactly(normalBuf, 0, ptsInBlock * NormalRecordSize); - fs.Position = resume; - } - - for (int p = 0; p < ptsInBlock; p++, pointIdx++) + for (int offset = 0; offset < toRead; offset += PointRecordSize, pointInLeaf++) { - if (pointIdx % step != 0) continue; + // The step counts the points of each leaf, like the blocks of the other readers. + if (pointInLeaf % (uint)step != 0) continue; - int off = p * recordSize; - ushort v1 = Bytes.ReadUInt16LE(chunkBuf.AsSpan(off + 4, 2)); - ushort v2 = Bytes.ReadUInt16LE(chunkBuf.AsSpan(off + 6, 2)); - ushort v3 = Bytes.ReadUInt16LE(chunkBuf.AsSpan(off + 8, 2)); + ReadOnlySpan record = chunk.AsSpan(offset, PointRecordSize); - // Fixed-step quantization relative to the node minimum. - double x = node.TightMin.X + (v1 * Quantization); - double y = node.TightMin.Y + (v2 * Quantization); - double z = node.TightMin.Z + (v3 * Quantization); + // The three fields hold the position; the top ten bits of the word hold other data and are ignored. + ulong packed = Bytes.ReadUInt64LE(record); + double x = leaf.CubeMin.X + ((packed >> (FieldBits * 0)) & FieldMask) * GridStep; + double y = leaf.CubeMin.Y + ((packed >> (FieldBits * 1)) & FieldMask) * GridStep; + double z = leaf.CubeMin.Z + ((packed >> (FieldBits * 2)) & FieldMask) * GridStep; - // Packed normal: signed byte components; an all-zero normal means none. PclVector3? normal = null; if (hasNormals) { - int n = p * NormalRecordSize; - sbyte nx = (sbyte)normalBuf[n]; - sbyte ny = (sbyte)normalBuf[n + 1]; - sbyte nz = (sbyte)normalBuf[n + 2]; - if (nx != 0 || ny != 0 || nz != 0) + // A plain cell code names the direction of the normal; anything else leaves the point without one. + ushort field = Bytes.ReadUInt16LE(record[12..]); + if (field != 0 && (field & NormalFlags) == 0 && field < NormalDirections.Count) { - double len = Math.Sqrt((nx * nx) + (ny * ny) + (nz * nz)); - var norm = new PclVector3(nx / len, ny / len, nz / len); - normal = options.ApplyTransform ? Transform.TransformVector(norm) : norm; + normal = NormalDirections.All[field]; + if (scaleNormals) normal = scanTransform.TransformVector(normal.Value); } } - // A node without colour and intensity holds the position of the point only. - PclColor? color = null; - float? intensity = null; - if (hasColor) + if (transform) { - color = new PclColor(chunkBuf[off + 13], chunkBuf[off + 14], chunkBuf[off + 15]); - intensity = chunkBuf[off + 12] / 255.0f; + // Scale, then translation, as PclTransform applies them. + x = x * scaleX + shiftX; + y = y * scaleY + shiftY; + z = z * scaleZ + shiftZ; } - var pt = new PclPoint( + // Intensity at 8; blue, green and red from 9. + yield return new PclPoint( new PclVector3(x, y, z), - Color: color, - Intensity: intensity, + Color: hasColor ? new PclColor(record[11], record[10], record[9]) : null, + Intensity: hasIntensity ? record[8] / 255.0f : null, Normal: normal, Index: (ulong)yielded); - if (options.ApplyTransform) - pt = pt with { Position = Transform.TransformPoint(pt.Position) }; - - yield return pt; yielded++; if (yielded >= targetCount) yield break; } } - - curOffset += node.Bytes; } } - // Reads and validates the node table; payloadStart is where the first node payload begins. - private static List ReadNodeTable(FileStream fs, RcsLayout layout, uint minorVersion, out long payloadStart) + private LeafTable Table => _table ??= ReadLeafTable(); + + // Reads the leaves section and checks every leaf block against the points section and the size of the file. + private LeafTable ReadLeafTable() { - if (fs.Length < layout.NodeTableOffset + 8) throw FormatError.Truncated("RCS node table"); + using var fs = File.OpenRead(_filePath); + long fileLength = fs.Length; + + fs.Position = SectionTableOffset; + Span word = stackalloc byte[8]; + fs.ReadExactly(word[..4]); + uint sectionCount = Bytes.ReadUInt32LE(word[..4]); + if (sectionCount > MaxSections) throw FormatError.Corrupted("RCS section count is out of range."); + if (SectionTableOffset + 4L + (long)sectionCount * SectionEntrySize > fileLength) + throw FormatError.Truncated("RCS section table"); + + long leavesOffset = -1, leavesSize = 0, pointsOffset = -1, pointsSize = 0; + Span entry = stackalloc byte[SectionEntrySize]; + for (uint i = 0; i < sectionCount; i++) + { + fs.ReadExactly(entry); + ulong type = Bytes.ReadUInt64LE(entry[..8]); + long offset = (long)Bytes.ReadUInt64LE(entry[8..16]); + long size = (long)Bytes.ReadUInt64LE(entry[16..24]); + if (size < 0 || size > fileLength || offset < 0 || offset > fileLength - size) + throw FormatError.Corrupted("RCS section does not fit in the file."); + + if (type == SectionLeaves) + { + if (leavesOffset >= 0) throw FormatError.Corrupted("RCS section table names the leaves section twice."); + (leavesOffset, leavesSize) = (offset, size); + } + else if (type == SectionPoints) + { + if (pointsOffset >= 0) throw FormatError.Corrupted("RCS section table names the points section twice."); + (pointsOffset, pointsSize) = (offset, size); + } + } - fs.Position = layout.NodeTableOffset; - Span countBuf = stackalloc byte[8]; - fs.ReadExactly(countBuf); - ulong numNodes = Bytes.ReadUInt64LE(countBuf); + if (leavesOffset < 0 || pointsOffset < 0) + throw FormatError.Corrupted("RCS file has no leaves section or no points section."); + + if (leavesSize < 8) throw FormatError.Truncated("RCS leaf table"); + fs.Position = leavesOffset; + fs.ReadExactly(word); + uint leafCount = Bytes.ReadUInt32LE(word[..4]); + if (leafCount > MaxLeaves) throw FormatError.Corrupted($"RCS leaf table declares {leafCount} leaves; at most {MaxLeaves} are read."); + if (8L + (long)leafCount * LeafRecordSize > leavesSize) + throw FormatError.Corrupted("RCS leaf table does not fit in its section."); + + long pointsEnd = pointsOffset + pointsSize; + long blockOffset = pointsOffset; + long pointCount = 0; + var leaves = new Leaf[leafCount]; + Span record = stackalloc byte[LeafRecordSize]; + for (int i = 0; i < leaves.Length; i++) + { + fs.ReadExactly(record); + double minX = Bytes.ReadDoubleLE(record[..8]); + double minY = Bytes.ReadDoubleLE(record[8..16]); + double minZ = Bytes.ReadDoubleLE(record[16..24]); + if (!double.IsFinite(minX) || !double.IsFinite(minY) || !double.IsFinite(minZ)) + throw FormatError.Corrupted("RCS leaf cube corner is not finite."); + + // The number of points of the leaf, and the size of its block in the points section. + uint points = Bytes.ReadUInt32LE(record[100..104]); + uint blockSize = Bytes.ReadUInt32LE(record[104..108]); + + // Every point has an index word of four bytes, which precede the records in the block of the leaf. + long indexBytes = (long)blockSize - (long)points * PointRecordSize; + if (indexBytes < 4L * points || indexBytes % 4 != 0 || blockSize > pointsEnd - blockOffset) + throw FormatError.Corrupted("RCS leaf block does not fit its point count and the points section."); + + leaves[i] = new Leaf(new PclVector3(minX, minY, minZ), points, blockOffset + indexBytes); + blockOffset += blockSize; + pointCount += points; + } - long tableEnd = layout.NodeTableOffset + 8 + ((long)Math.Min(numNodes, MaxNodes + 1) * layout.NodeSize); - if (numNodes > MaxNodes || tableEnd > fs.Length) - throw FormatError.Corrupted("RCS node table does not fit in the file."); + if (blockOffset != pointsEnd) throw FormatError.Corrupted("RCS leaf blocks do not fill the points section."); - var nodes = new List((int)numNodes); - byte[] nodeBuf = new byte[layout.NodeSize]; - long totalPayloadBytes = 0; + return new LeafTable(leaves, pointCount); + } - for (ulong i = 0; i < numNodes; i++) - { - fs.ReadExactly(nodeBuf, 0, layout.NodeSize); + // The leaves of a file in file order, and the number of points they hold. + private readonly record struct LeafTable(Leaf[] Leaves, long PointCount); - double tMinX = Bytes.ReadDoubleLE(nodeBuf.AsSpan(0x30, 8)); - double tMinY = Bytes.ReadDoubleLE(nodeBuf.AsSpan(0x38, 8)); - double tMinZ = Bytes.ReadDoubleLE(nodeBuf.AsSpan(0x40, 8)); - double tMaxX = Bytes.ReadDoubleLE(nodeBuf.AsSpan(0x48, 8)); - double tMaxY = Bytes.ReadDoubleLE(nodeBuf.AsSpan(0x50, 8)); - double tMaxZ = Bytes.ReadDoubleLE(nodeBuf.AsSpan(0x58, 8)); + // One leaf of the octree: the corner its point positions count from, its number of points and where its records start. + private readonly record struct Leaf(PclVector3 CubeMin, uint Points, long RecordsOffset); + + // The unit direction of every normal code. A code names a cell on one of the six faces of a cube, the faces along + // +x, -x, +y, -y, +z and -z in that order, with 52 by 52 cells of equal angle across each face. + private static class NormalDirections + { + private const int Cells = 52; + private const int FaceCodes = Cells * Cells; + public const int Count = 6 * FaceCodes; - uint npts = Bytes.ReadUInt32LE(nodeBuf.AsSpan(0x64, 4)); - uint nbytes = Bytes.ReadUInt32LE(nodeBuf.AsSpan(0x68, 4)); + public static readonly PclVector3[] All = Build(); - if (npts > 0 && nbytes > 0) + private static PclVector3[] Build() + { + var table = new PclVector3[Count]; + for (int code = 0; code < Count; code++) { - if (!double.IsFinite(tMinX) || !double.IsFinite(tMinY) || !double.IsFinite(tMinZ) || - !double.IsFinite(tMaxX) || !double.IsFinite(tMaxY) || !double.IsFinite(tMaxZ) || - tMinX > tMaxX || tMinY > tMaxY || tMinZ > tMaxZ) - throw FormatError.Corrupted("RCS node bounds are invalid."); - - // The decoder reads records of exactly ten bytes (position), sixteen (position, colour and - // intensity) or twenty (the same plus the plane of the normals). Any other payload size would be - // read with the wrong stride and return wrong positions, so it is rejected instead of guessed. - if (nbytes != (long)npts * PositionRecordSize && - nbytes != (long)npts * PointRecordSize && - nbytes != (long)npts * (PointRecordSize + NormalRecordSize)) - throw FormatError.Unsupported( - $"RCS container version {layout.MajorVersion}.{minorVersion}: node payload does not match a known point record layout."); + int face = code / FaceCodes; + int i = (code % FaceCodes) / Cells; + int j = code % Cells; + int axis = face / 2; + int first = axis == 0 ? 1 : 0; + int second = axis == 2 ? 1 : 2; + + double[] direction = new double[3]; + direction[axis] = face % 2 == 0 ? 1 : -1; + direction[first] = Across(j); + direction[second] = Across(i); + + double length = Math.Sqrt(direction[0] * direction[0] + direction[1] * direction[1] + direction[2] * direction[2]); + table[code] = new PclVector3(direction[0] / length, direction[1] / length, direction[2] / length); } - - nodes.Add(new Node(new PclVector3(tMinX, tMinY, tMinZ), npts, nbytes)); - totalPayloadBytes += nbytes; + return table; } - payloadStart = fs.Length - totalPayloadBytes; - if (payloadStart < tableEnd) - throw FormatError.Corrupted("RCS node payload sizes exceed the file size."); - - return nodes; + // Where a cell row leaves the centre line of the face: equal angles from -45 to +45 degrees. + private static double Across(int cell) => Math.Tan((2.0 * (cell + 0.5) / Cells - 1.0) * Math.PI / 4.0); } } diff --git a/tests/PclIO.Tests/CliTests.cs b/tests/PclIO.Tests/CliTests.cs index 57f010a..1ae6bf0 100644 --- a/tests/PclIO.Tests/CliTests.cs +++ b/tests/PclIO.Tests/CliTests.cs @@ -18,7 +18,7 @@ private static Result Run(params string[] args) private static string PointsRcs(TempDirectory dir, string name = "points.rcs") => dir.Write(name, SyntheticFixtures.CreateSyntheticRcsWithPoints( - [new RcsSamplePoint(10000, 20000, 30000, 128, 10, 20, 30), new RcsSamplePoint(0, 0, 0, 255, 1, 2, 3), new RcsSamplePoint(5, 5, 5, 0, 4, 5, 6)], + [new RcsSamplePoint(1000, 2000, 3000, 128, 10, 20, 30), new RcsSamplePoint(0, 0, 0, 255, 1, 2, 3), new RcsSamplePoint(5, 5, 5, 0, 4, 5, 6)], (0, 0, 0))); private static string MissingPath(string name) => Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"), name); @@ -175,8 +175,12 @@ public void Info_Json_Describes_The_File() Assert.Equal(Program.ExitOk, result.Exit); using var doc = JsonDocument.Parse(result.Out); Assert.Equal("RecapScan", doc.RootElement.GetProperty("kind").GetString()); - Assert.Equal(777, doc.RootElement.GetProperty("totalPoints").GetInt64()); + // The header states 777 points, but the file stores none. + Assert.Equal(0, doc.RootElement.GetProperty("totalPoints").GetInt64()); Assert.Equal(1, doc.RootElement.GetProperty("scanCount").GetInt32()); + + using var withPoints = JsonDocument.Parse(Run("info", PointsRcs(dir), "--json").Out); + Assert.Equal(3, withPoints.RootElement.GetProperty("totalPoints").GetInt64()); } [Fact] @@ -197,11 +201,15 @@ public void Scans_Lists_Every_Scan() var result = Run("scans", path); Assert.Equal(Program.ExitOk, result.Exit); + // The header states 500 points, but the file stores none: a scan reports the points a read returns. Assert.Contains("Scans in header.rcs (1):", result.Out); - Assert.Contains("Points: 500", result.Out); + Assert.Contains("Points: 0", result.Out); using var json = JsonDocument.Parse(Run("scans", path, "--json").Out); - Assert.Equal(500, json.RootElement[0].GetProperty("pointCount").GetInt64()); + Assert.Equal(0, json.RootElement[0].GetProperty("pointCount").GetInt64()); + + using var withPoints = JsonDocument.Parse(Run("scans", PointsRcs(dir), "--json").Out); + Assert.Equal(3, withPoints.RootElement[0].GetProperty("pointCount").GetInt64()); } [Fact] diff --git a/tests/PclIO.Tests/FormatTests.cs b/tests/PclIO.Tests/FormatTests.cs index 9048dd9..42438e6 100644 --- a/tests/PclIO.Tests/FormatTests.cs +++ b/tests/PclIO.Tests/FormatTests.cs @@ -49,32 +49,67 @@ public void Parse_Synthetic_Rcs_Header() Assert.Equal(PclFileKind.RecapScan, doc.Kind); Assert.Equal(3u, doc.MajorVersion); + Assert.Equal(2u, doc.MinorVersion); Assert.Equal(12345, doc.DeclaredPointCount); + Assert.Equal("12345", doc.Metadata["PointCount"]); Assert.Equal(new PclVector3(10.5, 20.5, 30.5), doc.ScanTransform.Translation); + Assert.Equal(PclVector3.Zero, doc.ScanTransform.Rotation); Assert.Equal(PclVector3.One, doc.ScanTransform.Scale); Assert.Equal(new PclBounds(new PclVector3(-10, -10, -10), new PclVector3(10, 10, 10)), doc.LocalBounds); + Assert.Equal(new PclBounds(new PclVector3(-10, -10, -10), new PclVector3(10, 10, 10)), doc.OctreeBounds); Assert.Equal("00000000-0000-0000-0000-000000000001", doc.ScanGuid); Assert.Equal("LOCAL_GRID_SYSTEM", doc.CoordinateSystem); + Assert.False(doc.HasColorData); + Assert.False(doc.HasNormalData); + Assert.False(doc.HasIntensityData); var scan = Assert.Single(doc.Scans); - Assert.Equal(12345, scan.PointCount); - Assert.Equal(12345, doc.TotalPointCount); + Assert.Equal("00000000-0000-0000-0000-000000000001", scan.Id); + Assert.Equal("sample", scan.Name); + Assert.Equal(doc.ScanTransform, scan.Transform); + Assert.Equal(doc.LocalBounds, scan.Bounds); + Assert.False(scan.HasColors); + Assert.False(scan.HasNormals); + Assert.False(scan.HasIntensities); } [Fact] - public void Rcs_With_An_Empty_Node_Table_Yields_No_Points() + public void Rcs_Without_Leaves_Stores_No_Points() { + // The header states a point count, but the file holds no leaf, so it stores no point. using var dir = new TempDirectory(); using var doc = RcsScanDocument.Open(dir.Write("empty.rcs", SyntheticFixtures.CreateSyntheticRcs(pointCount: 10))); + Assert.Equal(10, doc.DeclaredPointCount); + Assert.Equal(0, doc.Scans[0].PointCount); + Assert.Equal(0, doc.TotalPointCount); Assert.Empty(doc.ReadAllPoints()); } + [Fact] + public void Rcs_Point_Count_Is_The_Number_Of_Stored_Points_Not_The_Count_Of_The_Header() + { + // The header states a count of its own, which is not the number of the points the file stores. + using var dir = new TempDirectory(); + var scan = new RcsScanBuilder { PointCount = 9000 }; + scan.AddLeaf((0, 0, 0), 1, new RcsSamplePoint(1, 1, 1), new RcsSamplePoint(2, 2, 2)); + scan.AddLeaf((5, 5, 5), 1, new RcsSamplePoint(3, 3, 3)); + using var doc = RcsScanDocument.Open(dir.Write("count.rcs", scan.Build())); + + Assert.Equal(9000, doc.DeclaredPointCount); + Assert.Equal(3, doc.Scans[0].PointCount); + Assert.Equal(3, doc.TotalPointCount); + Assert.Equal(3, doc.ReadAllPoints().Count()); + } + + // Records of the synthetic scans. The first lies 0.1, 0.2 and 0.3 metres from the corner of its leaf and names a cell + // near the +z axis; the second is the corner of the leaf and has no normal; the third holds the largest offset an + // axis can hold and the flag that leaves a point without a normal. private static readonly RcsSamplePoint[] RcsPoints = [ - new(1000, 2000, 3000, 128, 10, 20, 30, 0, 0, 127), + new(100, 200, 300, 128, 10, 20, 30, 12194), new(0, 0, 0, 255, 1, 2, 3), - new(65535, 1, 2, 0, 255, 254, 253, 127, 0, 0), + new(RcsScanBuilder.MaxOffset, 1000, 2, 0, 255, 254, 253, 0x4000), ]; [Fact] @@ -88,111 +123,274 @@ public void Read_Synthetic_Rcs_Points_With_And_Without_Transform() var raw = doc.ReadAllPoints(NoTransform).ToList(); var moved = doc.ReadAllPoints().ToList(); + // A position counts millimetres from the corner of the cube of its leaf; the transform adds the translation. Assert.Equal(3, raw.Count); - AssertNear(new PclVector3(1.6, -2.3, 3.8), raw[0].Position); - AssertNear(new PclVector3(1.5, -2.5, 3.5), raw[1].Position); - AssertNear(new PclVector3(1.5 + 6.5535, -2.4999, 3.5002), raw[2].Position); - AssertNear(new PclVector3(11.6, 17.7, 33.8), moved[0].Position); + Assert.Equal(new PclVector3(1.5 + 100 * 0.001, -2.5 + 200 * 0.001, 3.5 + 300 * 0.001), raw[0].Position); + Assert.Equal(new PclVector3(1.5, -2.5, 3.5), raw[1].Position); + Assert.Equal(new PclVector3(1.5 + 262143 * 0.001, -2.5 + 1000 * 0.001, 3.5 + 2 * 0.001), raw[2].Position); + Assert.Equal(new PclVector3((1.5 + 100 * 0.001) * 1 + 10, (-2.5 + 200 * 0.001) * 1 + 20, (3.5 + 300 * 0.001) * 1 + 30), moved[0].Position); + Assert.Equal(new[] { 0UL, 1UL, 2UL }, raw.Select(p => p.Index)); + // The colour and the intensity are the bytes of the record. Assert.Equal(new PclColor(10, 20, 30), raw[0].Color); + Assert.Equal(new PclColor(255, 254, 253), raw[2].Color); Assert.Equal(128 / 255.0f, raw[0].Intensity); Assert.Equal(1.0f, raw[1].Intensity); - Assert.Equal(new[] { 0UL, 1UL, 2UL }, raw.Select(p => p.Index)); + Assert.Equal(0.0f, raw[2].Intensity); - // Packed normals are unit vectors; an all-zero normal means "none". - AssertNear(new PclVector3(0, 0, 1), raw[0].Normal!.Value); + // The first record names a cell of the +z face; the others state that the point has no normal. A scale of one + // leaves a normal as it is. + AssertNear(new PclVector3(0.015101514293334039, 0.015101514293334039, 0.99977191825540723), raw[0].Normal!.Value); Assert.Null(raw[1].Normal); - AssertNear(new PclVector3(1, 0, 0), raw[2].Normal!.Value); + Assert.Null(raw[2].Normal); + Assert.Equal(raw.Select(p => p.Index), moved.Select(p => p.Index)); + Assert.Equal(raw.Select(p => p.Color), moved.Select(p => p.Color)); + Assert.Equal(raw.Select(p => p.Intensity), moved.Select(p => p.Intensity)); + Assert.Equal(raw.Select(p => p.Normal), moved.Select(p => p.Normal)); + } + + [Theory] + [InlineData(1u, 0.60025827522031439, -0.5481850217573937, -0.58239435518416482)] + [InlineData(52u, 0.60025827522031439, -0.58239435518416482, -0.5481850217573937)] + [InlineData(53u, 0.61221412644254303, -0.55910368599401761, -0.55910368599401761)] + [InlineData(2704u, -0.5889765868020802, -0.57144841420681702, -0.57144841420681702)] + [InlineData(2756u, -0.60025827522031439, -0.58239435518416482, -0.5481850217573937)] + [InlineData(5408u, -0.57144841420681702, 0.5889765868020802, -0.57144841420681702)] + [InlineData(5459u, 0.57144841420681702, 0.58897658680208009, -0.57144841420681691)] + [InlineData(8112u, -0.57144841420681702, -0.5889765868020802, -0.57144841420681702)] + [InlineData(10816u, -0.57144841420681702, -0.57144841420681702, 0.5889765868020802)] + [InlineData(10867u, 0.57144841420681702, -0.57144841420681691, 0.58897658680208009)] + [InlineData(13520u, -0.57144841420681702, -0.57144841420681702, -0.5889765868020802)] + [InlineData(16223u, 0.57144841420681702, 0.57144841420681702, -0.58897658680208009)] + public void Rcs_Normals_Are_The_Directions_Of_The_Cells_Their_Codes_Name(ushort code, double x, double y, double z) + { + // A code names a cell on a face of a cube: face * 2704 + i * 52 + j, the faces along +x, -x, +y, -y, +z and -z, each + // with 52 by 52 cells of equal angle. The directions were computed from that definition apart from the reader, for the + // first cell of every face, for cells that differ in i alone and in j alone, and for the last cell. + using var dir = new TempDirectory(); + var scan = new RcsScanBuilder { Normals = true }; + scan.AddLeaf((0, 0, 0), 1, new RcsSamplePoint(0, 0, 0, Normal: code)); + using var doc = RcsScanDocument.Open(dir.Write("normal.rcs", scan.Build())); + + var point = Assert.Single(doc.ReadAllPoints(NoTransform)); + PclVector3 normal = point.Normal!.Value; + + AssertNear(new PclVector3(x, y, z), normal); + Assert.Equal(1.0, normal.X * normal.X + normal.Y * normal.Y + normal.Z * normal.Z, Precision); } [Fact] - public void An_Rcs_Without_Colour_Reports_No_Colour_And_No_Intensity() + public void An_Rcs_Point_Has_A_Normal_Only_For_A_Plain_Cell_Code() { + // A point without a normal states a zero code, as some files do, or a flag bit beside the code, as others do. A + // code above the last cell names no cell either. + ushort[] fields = [12194, 0, 0x4000, 0x4000 | 12194, 0x8000, 0xC000, 0x3FFF]; + bool[] hasNormal = [true, false, false, false, false, false, false]; + using var dir = new TempDirectory(); - using var doc = RcsScanDocument.Open(dir.Write("plain.rcs", - SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0), withColor: false))); + var scan = new RcsScanBuilder { Normals = true }; + scan.AddLeaf((0, 0, 0), 1, [.. fields.Select((field, i) => new RcsSamplePoint((uint)i, 0, 0, Normal: field))]); + using var doc = RcsScanDocument.Open(dir.Write("flags.rcs", scan.Build())); - var scan = Assert.Single(doc.Scans); - Assert.False(scan.HasColors); - Assert.False(scan.HasIntensities); - Assert.False(scan.HasNormals); - Assert.False(doc.HasColorData); + Assert.True(doc.HasNormalData); + Assert.True(doc.Scans[0].HasNormals); + var points = doc.ReadAllPoints(NoTransform).ToList(); + Assert.Equal(hasNormal, points.Select(p => p.Normal.HasValue)); + AssertNear(new PclVector3(0.015101514293334039, 0.015101514293334039, 0.99977191825540723), points[0].Normal!.Value); + } - var points = scan.ReadPoints(NoTransform).ToList(); - Assert.Equal(3, points.Count); - Assert.All(points, p => - { - Assert.Null(p.Color); - Assert.Null(p.Intensity); - Assert.Null(p.Normal); - }); + [Fact] + public void An_Rcs_Without_Normals_Reports_None_Whatever_Its_Records_State() + { + using var dir = new TempDirectory(); + var scan = new RcsScanBuilder(); + scan.AddLeaf((0, 0, 0), 1, new RcsSamplePoint(1, 2, 3, Normal: 12194)); + using var doc = RcsScanDocument.Open(dir.Write("flat.rcs", scan.Build())); + + Assert.False(doc.HasNormalData); + Assert.False(doc.Scans[0].HasNormals); + Assert.Null(Assert.Single(doc.ReadAllPoints(NoTransform)).Normal); } [Theory] - [InlineData(12)] - [InlineData(14)] - [InlineData(17)] - [InlineData(21)] - public void An_Rcs_Node_With_An_Unknown_Record_Size_Is_Rejected(int bytesPerPoint) + [InlineData(true, true, true)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(false, false, false)] + public void Rcs_Channels_Follow_The_Flags_Of_The_Header(bool color, bool intensity, bool normals) + { + // The bytes of a channel are read only when the header states the channel; a file may hold anything in their place. + using var dir = new TempDirectory(); + var scan = new RcsScanBuilder { Color = color, Intensity = intensity, Normals = normals }; + scan.AddLeaf((0, 0, 0), 1, new RcsSamplePoint(1, 2, 3, 200, 10, 20, 30, 12194), new RcsSamplePoint(4, 5, 6)); + using var doc = RcsScanDocument.Open(dir.Write("channels.rcs", scan.Build())); + + var rcsScan = Assert.Single(doc.Scans); + Assert.Equal(color, doc.HasColorData); + Assert.Equal(normals, doc.HasNormalData); + Assert.Equal(intensity, doc.HasIntensityData); + Assert.Equal(color, rcsScan.HasColors); + Assert.Equal(normals, rcsScan.HasNormals); + Assert.Equal(intensity, rcsScan.HasIntensities); + + var points = rcsScan.ReadPoints(NoTransform).ToList(); + Assert.Equal(2, points.Count); + Assert.Equal(color ? new PclColor(10, 20, 30) : (PclColor?)null, points[0].Color); + Assert.Equal(color ? new PclColor(0, 0, 0) : (PclColor?)null, points[1].Color); + Assert.Equal(intensity ? 200 / 255.0f : (float?)null, points[0].Intensity); + Assert.Equal(intensity ? 0.0f : (float?)null, points[1].Intensity); + Assert.Equal(normals, points[0].Normal.HasValue); + Assert.Null(points[1].Normal); + } + + [Fact] + public void Rcs_Points_Count_From_The_Cube_Of_Their_Own_Leaf_In_File_Order() { - // The decoder knows records of ten, sixteen and twenty bytes; any other size would be read with the - // wrong stride and return wrong positions, so the file is rejected instead of guessed. using var dir = new TempDirectory(); - using var doc = RcsScanDocument.Open(dir.Write("odd.rcs", - SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0), - declaredPayloadBytes: (uint)(RcsPoints.Length * bytesPerPoint)))); + var scan = new RcsScanBuilder(); + scan.AddLeaf((1, 2, 3), 0.5, new RcsSamplePoint(100, 0, 0), new RcsSamplePoint(0, 500, 0)); + // A leaf without points and without a block lies between the two. + scan.AddLeaf((9, 9, 9), 0.25); + // The first record of the last leaf states the offsets of the first record of the first leaf. + scan.AddLeaf((-1, 5, 0.5), 0.25, new RcsSamplePoint(100, 0, 0), new RcsSamplePoint(0, 0, 250), new RcsSamplePoint(7, 8, 9)); + using var doc = RcsScanDocument.Open(dir.Write("leaves.rcs", scan.Build())); - Assert.Throws(() => doc.Scans[0].ReadPoints().ToList()); + var rcsScan = Assert.Single(doc.Scans); + Assert.Equal(5, rcsScan.PointCount); + Assert.Equal(5, doc.TotalPointCount); + + var points = rcsScan.ReadPoints(NoTransform).ToList(); + Assert.Equal(5, points.Count); + Assert.Equal(new[] + { + new PclVector3(1 + 100 * 0.001, 2, 3), + new PclVector3(1, 2 + 500 * 0.001, 3), + new PclVector3(-1 + 100 * 0.001, 5, 0.5), + new PclVector3(-1, 5, 0.5 + 250 * 0.001), + new PclVector3(-1 + 7 * 0.001, 5 + 8 * 0.001, 0.5 + 9 * 0.001), + }, points.Select(p => p.Position).ToArray()); + Assert.Equal(new ulong[] { 0, 1, 2, 3, 4 }, points.Select(p => p.Index).ToArray()); + + // The step counts the points of every leaf on their own. + var stepped = rcsScan.ReadPoints(new PclReadOptions { SubsampleStep = 2, ApplyTransform = false }).ToList(); + Assert.Equal(new[] { points[0].Position, points[2].Position, points[4].Position }, stepped.Select(p => p.Position).ToArray()); + Assert.Equal(new ulong[] { 0, 1, 2 }, stepped.Select(p => p.Index).ToArray()); } [Fact] - public void An_Rcs_Position_Only_Node_Larger_Than_A_Chunk_Keeps_Record_Alignment() + public void Rcs_Sections_Are_Taken_From_The_Table_Whatever_Their_Order() { - // A chunk of 65536 bytes holds 6553 whole ten-byte records; the next chunk must start at a record - // boundary, not six bytes into a record. - var points = Enumerable.Range(0, 7000) - .Select(i => new RcsSamplePoint((ushort)(i % 1000), (ushort)(i / 1000), 0, 0, 0, 0, 0)).ToList(); + // Reading needs the leaves section and the points section; the other sections are skipped wherever they lie. + RcsSamplePoint[] records = [new(100, 200, 300, 128, 10, 20, 30, 12194), new(0, 0, 0)]; + var plain = new RcsScanBuilder { Normals = true }; + plain.AddLeaf((1, 2, 3), 0.5, records); + + var shuffled = new RcsScanBuilder { Normals = true }; + shuffled.AddLeaf((1, 2, 3), 0.5, records); + shuffled.OtherSections[3] = new byte[72]; + shuffled.OtherSections[7] = [0x12, 0x00, 0x00, 0x80, 0xFF]; + shuffled.OtherSections[11] = new byte[134]; + shuffled.SectionOrder = [3, 7, RcsScanBuilder.PointsSection, 11, RcsScanBuilder.LeavesSection]; + using var dir = new TempDirectory(); - using var doc = RcsScanDocument.Open(dir.Write("big.rcs", - SyntheticFixtures.CreateSyntheticRcsWithPoints(points, (0, 0, 0), withColor: false))); + using var first = RcsScanDocument.Open(dir.Write("plain.rcs", plain.Build())); + using var second = RcsScanDocument.Open(dir.Write("shuffled.rcs", shuffled.Build())); - var all = doc.Scans[0].ReadPoints(NoTransform).ToList(); - Assert.Equal(7000, all.Count); - AssertNear(new PclVector3(0.0553, 0.0006, 0), all[6553].Position); - AssertNear(new PclVector3(0.0999, 0.0006, 0), all[6999].Position); + Assert.Equal(2, second.Scans[0].PointCount); + Assert.Equal(first.ReadAllPoints(NoTransform).ToList(), second.ReadAllPoints(NoTransform).ToList()); } [Fact] - public void An_Rcs_With_Colour_And_Normals_Reports_Them() + public void An_Rcs_Leaf_With_More_Index_Words_Than_Points_Is_Read() { + // The records of a block follow its index words. A leaf whose octree needs more words than the one every point has + // holds its records further back. using var dir = new TempDirectory(); - using var doc = RcsScanDocument.Open(dir.Write("full.rcs", - SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0), withNormals: true))); + var scan = new RcsScanBuilder(); + scan.AddLeaf((0, 0, 0), 262.144, RcsPoints).IndexBytes = 3 * RcsPoints.Length * 4 + 12; + using var doc = RcsScanDocument.Open(dir.Write("words.rcs", scan.Build())); + using var plain = RcsScanDocument.Open(dir.Write("plain.rcs", SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0)))); - var scan = Assert.Single(doc.Scans); - Assert.True(scan.HasColors); - Assert.True(scan.HasIntensities); - Assert.True(scan.HasNormals); - Assert.True(doc.HasColorData); - Assert.True(doc.HasNormalData); + Assert.Equal(3, doc.Scans[0].PointCount); + Assert.Equal(plain.ReadAllPoints(NoTransform).ToList(), doc.ReadAllPoints(NoTransform).ToList()); + } - var points = scan.ReadPoints(NoTransform).ToList(); - Assert.Equal(3, points.Count); - Assert.All(points, p => Assert.NotNull(p.Color)); + [Fact] + public void The_Top_Byte_Of_The_Word_Of_A_Record_Is_Not_Part_Of_Its_Position() + { + RcsSamplePoint[] plain = [new(100, 200, 300, 128, 10, 20, 30, 12194), new(RcsScanBuilder.MaxOffset, RcsScanBuilder.MaxOffset, RcsScanBuilder.MaxOffset)]; + RcsSamplePoint[] marked = [plain[0] with { Top = 0xFF }, plain[1] with { Top = 0xA5 }]; + + using var dir = new TempDirectory(); + using var first = RcsScanDocument.Open(dir.Write("plain.rcs", SyntheticFixtures.CreateSyntheticRcsWithPoints(plain, (1, 2, 3), withNormals: true))); + using var second = RcsScanDocument.Open(dir.Write("marked.rcs", SyntheticFixtures.CreateSyntheticRcsWithPoints(marked, (1, 2, 3), withNormals: true))); + + Assert.Equal(first.ReadAllPoints(NoTransform).ToList(), second.ReadAllPoints(NoTransform).ToList()); } [Fact] - public void An_Rcs_Without_Normals_Reports_No_Normal() + public void Rcs_Scale_Is_Applied_To_A_Position_Before_The_Translation() { using var dir = new TempDirectory(); - using var doc = RcsScanDocument.Open(dir.Write("flat.rcs", - SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0)))); + var scan = new RcsScanBuilder { Translation = (1, 2, 3), Scale = (0.5, 2, 10), Normals = true }; + scan.AddLeaf((0.25, 0, -0.5), 1, new RcsSamplePoint(1000, 2000, 3000, Normal: 2678), new RcsSamplePoint(100, 100, 100)); + using var doc = RcsScanDocument.Open(dir.Write("scaled.rcs", scan.Build())); - var scan = Assert.Single(doc.Scans); - Assert.True(scan.HasColors); - Assert.True(scan.HasIntensities); - Assert.False(scan.HasNormals); - Assert.All(scan.ReadPoints(NoTransform), p => Assert.Null(p.Normal)); + var raw = doc.ReadAllPoints(NoTransform).ToList(); + var scaled = doc.ReadAllPoints().ToList(); + + Assert.Equal(new PclVector3(0.25 + 1000 * 0.001, 0 + 2000 * 0.001, -0.5 + 3000 * 0.001), raw[0].Position); + Assert.Equal(new PclVector3((0.25 + 1000 * 0.001) * 0.5 + 1, (0 + 2000 * 0.001) * 2 + 2, (-0.5 + 3000 * 0.001) * 10 + 3), scaled[0].Position); + Assert.Equal(new PclVector3((0.25 + 100 * 0.001) * 0.5 + 1, (0 + 100 * 0.001) * 2 + 2, (-0.5 + 100 * 0.001) * 10 + 3), scaled[1].Position); + + // A scale that is not one re-orients a normal, as the transform of any scan does. + AssertNear(new PclVector3(0.71766355869077281, 0.010840278959110543, 0.69630561169603133), raw[0].Normal!.Value); + AssertNear(new PclVector3(0.051465119585504454, 0.0031095141795334682, 0.9986699516795412), scaled[0].Normal!.Value); + Assert.Null(scaled[1].Normal); + } + + [Theory] + [InlineData(12)] + [InlineData(14)] + [InlineData(17)] + [InlineData(21)] + public void An_Rcs_Leaf_Block_That_Does_Not_Fit_Its_Points_Is_Rejected(int bytesPerRecord) + { + // A block holds at least one four-byte index word per record, then the 16-byte records: 20 bytes per record. Any + // other size would place the records elsewhere, so the file is rejected instead of being read at a guess. + using var dir = new TempDirectory(); + using var doc = RcsScanDocument.Open(dir.Write("odd.rcs", + SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0), declaredPayloadBytes: (uint)(RcsPoints.Length * bytesPerRecord)))); + + Assert.Throws(() => doc.Scans[0].ReadPoints().ToList()); + Assert.Throws(() => doc.Scans[0].PointCount); + } + + [Fact] + public void An_Rcs_Leaf_Block_Of_Twenty_Bytes_Per_Record_Is_Read() + { + // The smallest block a leaf can hold: one index word and one record per point. + using var dir = new TempDirectory(); + using var doc = RcsScanDocument.Open(dir.Write("tight.rcs", + SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0), declaredPayloadBytes: (uint)(RcsPoints.Length * 20)))); + + Assert.Equal(3, doc.Scans[0].PointCount); + Assert.Equal(3, doc.ReadAllPoints().Count()); + } + + [Fact] + public void An_Rcs_Leaf_Larger_Than_A_Chunk_Keeps_Record_Alignment() + { + // A chunk of 65536 bytes holds 4096 whole 16-byte records, so 7000 records run over a chunk boundary. + RcsSamplePoint[] records = [.. Enumerable.Range(0, 7000).Select(i => new RcsSamplePoint((uint)(i % 1000), (uint)(i / 1000), 0))]; + using var dir = new TempDirectory(); + using var doc = RcsScanDocument.Open(dir.Write("big.rcs", SyntheticFixtures.CreateSyntheticRcsWithPoints(records, (0, 0, 0)))); + + var all = doc.Scans[0].ReadPoints(NoTransform).ToList(); + + Assert.Equal(7000, all.Count); + Assert.Equal(records.Select(p => new PclVector3(p.X * 0.001, p.Y * 0.001, p.Z * 0.001)), all.Select(p => p.Position)); + Assert.Equal(Enumerable.Range(0, 7000).Select(i => (ulong)i), all.Select(p => p.Index)); } [Fact] @@ -202,8 +400,10 @@ public void Read_Synthetic_Rcs_Points_Honours_Limit_And_Step() using var doc = RcsScanDocument.Open(dir.Write("points.rcs", SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0)))); Assert.Equal(2, doc.ReadAllPoints(new PclReadOptions { MaxPoints = 2 }).Count()); + Assert.Equal(3, doc.ReadAllPoints(new PclReadOptions { MaxPoints = 3 }).Count()); Assert.Equal(3, doc.ReadAllPoints(new PclReadOptions { MaxPoints = 99 }).Count()); Assert.Equal(2, doc.ReadAllPoints(new PclReadOptions { SubsampleStep = 2 }).Count()); + Assert.Single(doc.ReadAllPoints(new PclReadOptions { SubsampleStep = 3 })); Assert.Empty(doc.ReadAllPoints(new PclReadOptions { MaxPoints = 0 })); } @@ -216,7 +416,8 @@ public void Rcs_Of_An_Unsupported_Major_Version_Is_Rejected_At_Read_Time() using var doc = RcsScanDocument.Open(dir.Write("old.rcs", bytes)); Assert.Equal(2u, doc.MajorVersion); - Assert.Throws(() => doc.ReadAllPoints().ToList()); + var error = Assert.Throws(() => doc.ReadAllPoints().ToList()); + Assert.Contains("2.2", error.Message, StringComparison.Ordinal); } [Fact] @@ -227,10 +428,12 @@ public void An_Rcs_Of_A_Version_Without_A_Described_Layout_Is_Rejected_With_A_Me bytes[8] = 4; using var doc = RcsScanDocument.Open(dir.Write("new.rcs", bytes)); - // The file is listed with its header, but its points cannot be decoded. + // The file is listed with its header, but its points cannot be decoded: nothing is read from the file for them, + // so the count of the header is reported. Assert.Equal(4u, doc.MajorVersion); + Assert.Equal(3, doc.Scans[0].PointCount); var error = Assert.Throws(() => doc.ReadAllPoints().ToList()); - Assert.Contains("4", error.Message, StringComparison.Ordinal); + Assert.Contains("4.2", error.Message, StringComparison.Ordinal); Assert.Contains("3", error.Message, StringComparison.Ordinal); } @@ -241,13 +444,13 @@ public void The_Node_Layouts_That_Are_Decoded_Are_Named() } [Fact] - public void An_Rcs_With_A_Truncated_Node_Table_Is_Rejected() + public void An_Rcs_With_A_Truncated_Leaf_Table_Is_Rejected() { using var dir = new TempDirectory(); byte[] bytes = SyntheticFixtures.CreateSyntheticRcsWithPoints(RcsPoints, (0, 0, 0)); - // The file ends in the middle of the node table. - string path = dir.Write("short.rcs", bytes[..(98605 + 100)]); + // The file ends in the middle of the leaf record. + string path = dir.Write("short.rcs", bytes[..(RcsScanBuilder.HeaderSize + 8 + 100)]); using var doc = RcsScanDocument.Open(path); Assert.Throws(() => doc.ReadAllPoints().ToList()); @@ -357,14 +560,15 @@ public void An_Rcp_Placement_Reorients_The_Normals_With_The_Points() .Replace("", "") .Replace("", ""); string rcp = dir.Write("site.rcp", SyntheticFixtures.CreateZip("project.xml", manifest)); - var points = new[] { new RcsSamplePoint(1000, 0, 0, 0, 0, 0, 0, 89, 0, 89) }; + // The point lies 0.1 metres along x and names the cell (i = 51, j = 26) of the +x face. + var points = new[] { new RcsSamplePoint(100, 0, 0, Normal: 2678) }; dir.Write(Path.Combine("site Support", "scan1.rcs"), SyntheticFixtures.CreateSyntheticRcsWithPoints(points, (0, 0, 0), withNormals: true)); using var doc = RcpProjectDocument.Open(rcp); var pt = Assert.Single(doc.ReadAllPoints()); AssertNear(new PclVector3(0.2, 0, 0), pt.Position); - AssertNear(new PclVector3(2 / Math.Sqrt(5), 0, 1 / Math.Sqrt(5)), pt.Normal!.Value); + AssertNear(new PclVector3(0.8996974848469792, 0.0067949470169167041, 0.43646106865911521), pt.Normal!.Value); } [Fact] diff --git a/tests/PclIO.Tests/InputHardeningTests.cs b/tests/PclIO.Tests/InputHardeningTests.cs index a53b29a..2fa1292 100644 --- a/tests/PclIO.Tests/InputHardeningTests.cs +++ b/tests/PclIO.Tests/InputHardeningTests.cs @@ -1000,44 +1000,218 @@ public void A_Leica_Block_Whose_Planes_Together_Inflate_Beyond_The_Block_Limit_I Assert.Contains("decompresses to more than", exception.Message); } - // ---- ReCap scan limit ----------------------------------------------------------------------------------------- + // ---- ReCap scan --------------------------------------------------------------------------------------------- - // Offset of the node table in the supported layout of an .rcs file. - private const int RcsNodeTableOffset = 98605; + // Where the section table starts in an .rcs file, and the entry of the points section in it. + private const int RcsSectionTable = 0x12D; + private const int RcsPointsEntry = RcsSectionTable + 24; + + // Where the leaves section lies in the files built below, and the offset of the block size in a leaf record. + private const int RcsLeavesSection = RcsScanBuilder.HeaderSize; + private const int RcsBlockSizeInLeaf = 8 + 104; + + private static byte[] RcsWithThreePoints() => SyntheticFixtures.CreateSyntheticRcsWithPoints( + [new RcsSamplePoint(1, 1, 1), new RcsSamplePoint(2, 2, 2), new RcsSamplePoint(3, 3, 3)], (0, 0, 0)); [Theory] - [InlineData(500_001UL)] - [InlineData(1UL << 40)] - [InlineData(ulong.MaxValue)] - public void An_Rcs_Node_Table_Declaring_More_Nodes_Than_The_Limit_Is_Rejected_Without_Allocating_For_Them(ulong nodes) + [InlineData(65u)] + [InlineData(uint.MaxValue)] + public void An_Rcs_Section_Count_Above_The_Limit_Is_Rejected_Without_Reading_The_Table(uint sections) + { + using var dir = new TempDirectory(); + byte[] bytes = RcsWithThreePoints(); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(0x129, 4), sections); + string path = dir.Write("sections.rcs", bytes); + + AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + } + + [Fact] + public void An_Rcs_Whose_Section_Table_Runs_Past_The_End_Of_The_File_Is_Rejected() + { + // The file ends with its header. The eight entries the header can hold are empty sections, which are sound, and the + // count states 64: the ninth entry would have to come from beyond the end of the file. + using var dir = new TempDirectory(); + byte[] bytes = SyntheticFixtures.CreateSyntheticRcs()[..RcsScanBuilder.HeaderSize]; + bytes.AsSpan(RcsSectionTable, 8 * 24).Clear(); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(0x129, 4), 64); + string path = dir.Write("table.rcs", bytes); + + var error = AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + Assert.Contains("truncated", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData(0L, long.MaxValue)] + [InlineData(long.MaxValue, 0L)] + [InlineData(-1L, 16L)] + [InlineData(0L, -16L)] + [InlineData(long.MaxValue - 8, 16L)] + public void An_Rcs_Section_That_Does_Not_Fit_In_The_File_Is_Rejected(long offset, long size) + { + // The offset and the size of the points section are set to the 64-bit patterns given, whatever their sign. + using var dir = new TempDirectory(); + byte[] bytes = RcsWithThreePoints(); + BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(RcsPointsEntry + 8, 8), offset); + BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(RcsPointsEntry + 16, 8), size); + string path = dir.Write("outside.rcs", bytes); + + AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + } + + [Theory] + [InlineData(0)] + [InlineData(24)] + public void An_Rcs_Without_Its_Leaves_Section_Or_Without_Its_Points_Section_Is_Rejected(int entry) + { + // The entry is given a section type the reader does not use. + using var dir = new TempDirectory(); + byte[] bytes = RcsWithThreePoints(); + BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(RcsSectionTable + entry, 8), 99); + string path = dir.Write("missing.rcs", bytes); + + var error = AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + Assert.Contains("section", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void An_Rcs_That_Names_A_Section_Twice_Is_Rejected() + { + // The entry of the points section claims to be a second leaves section. + using var dir = new TempDirectory(); + byte[] bytes = RcsWithThreePoints(); + BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(RcsPointsEntry, 8), 2); + string path = dir.Write("twice.rcs", bytes); + + var error = AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + Assert.Contains("twice", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData(2u)] + [InlineData(uint.MaxValue)] + public void An_Rcs_Leaf_Count_That_The_Leaves_Section_Cannot_Hold_Is_Rejected_Without_Allocating_For_It(uint leaves) + { + // The section holds one leaf record; the count states more. + using var dir = new TempDirectory(); + byte[] bytes = RcsWithThreePoints(); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(RcsLeavesSection, 4), leaves); + string path = dir.Write("leaves.rcs", bytes); + + AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + } + + [Theory] + [InlineData(500_001u)] + [InlineData(1u << 20)] + [InlineData(uint.MaxValue)] + public void An_Rcs_Leaf_Table_Declaring_More_Leaves_Than_The_Limit_Is_Rejected_Without_Allocating_For_Them(uint leaves) { using var dir = new TempDirectory(); byte[] bytes = SyntheticFixtures.CreateSyntheticRcs(); - BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(RcsNodeTableOffset, 8), nodes); - string path = dir.Write("nodes.rcs", bytes); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(RcsLeavesSection, 4), leaves); + string path = dir.Write("leaves.rcs", bytes); AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); } [Fact] - public void An_Rcs_Node_Table_One_Node_Beyond_The_Limit_Is_Rejected_Although_The_File_Could_Hold_It() + public void An_Rcs_Leaf_Table_One_Leaf_Beyond_The_Limit_Is_Rejected_Although_The_File_Could_Hold_It() { using var dir = new TempDirectory(); - const long nodeSize = 368; - string path = dir.PathOf("nodes.rcs"); + const long leafSize = 368; + const long leavesSize = 8 + (500_001 * leafSize); + string path = dir.PathOf("leaves.rcs"); byte[] header = SyntheticFixtures.CreateSyntheticRcs(); - BinaryPrimitives.WriteUInt64LittleEndian(header.AsSpan(RcsNodeTableOffset, 8), 500_001); + BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(RcsLeavesSection, 4), 500_001); + // The leaves section is declared large enough for the whole table, so only the limit on the leaf count can reject it. + BinaryPrimitives.WriteUInt64LittleEndian(header.AsSpan(RcsSectionTable + 16, 8), (ulong)leavesSize); - // The file is long enough for the whole table, so only the limit on the node count can reject it (the zero-filled tail costs no data). using (var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write)) { stream.Write(header); - stream.SetLength(RcsNodeTableOffset + 8 + (500_001 * nodeSize)); + stream.SetLength(RcsLeavesSection + leavesSize); } AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); } + [Fact] + public void An_Rcs_Whose_Leaf_Blocks_Do_Not_Fill_The_Points_Section_Is_Rejected() + { + // Eight bytes follow the leaf blocks inside the points section, which the leaf records do not account for. + var scan = new RcsScanBuilder(); + scan.AddLeaf((0, 0, 0), 1, new RcsSamplePoint(1, 1, 1), new RcsSamplePoint(2, 2, 2)); + scan.PointsTail = new byte[8]; + using var dir = new TempDirectory(); + string path = dir.Write("tail.rcs", scan.Build()); + + var error = AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + Assert.Contains("fill", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void An_Rcs_Leaf_Block_Larger_Than_The_Rest_Of_The_Points_Section_Is_Rejected() + { + // The record of the last leaf states a block of 24 bytes where the points section holds 20. + var scan = new RcsScanBuilder(); + scan.AddLeaf((0, 0, 0), 1, new RcsSamplePoint(1, 1, 1)); + scan.AddLeaf((1, 1, 1), 1, new RcsSamplePoint(2, 2, 2)); + byte[] bytes = scan.Build(); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(RcsLeavesSection + RcsBlockSizeInLeaf + RcsScanBuilder.LeafRecordSize, 4), 24); + using var dir = new TempDirectory(); + string path = dir.Write("beyond.rcs", bytes); + + var error = AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + Assert.Contains("block", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + public void An_Rcs_Leaf_With_A_Cube_Corner_That_Is_Not_A_Finite_Number_Is_Rejected(double corner) + { + using var dir = new TempDirectory(); + byte[] bytes = RcsWithThreePoints(); + BinaryPrimitives.WriteDoubleLittleEndian(bytes.AsSpan(RcsLeavesSection + 8 + 8, 8), corner); + string path = dir.Write("corner.rcs", bytes); + + AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + } + + [Fact] + public void An_Rcs_With_A_Damaged_Leaf_Returns_No_Point_At_All() + { + // The first leaf is sound and the second is not. The file is checked as a whole, so no point of the first leaf is + // returned before the failure. + var scan = new RcsScanBuilder(); + scan.AddLeaf((0, 0, 0), 1, new RcsSamplePoint(1, 1, 1), new RcsSamplePoint(2, 2, 2)); + scan.AddLeaf((1, 1, 1), 1, new RcsSamplePoint(3, 3, 3)).DeclaredBlockSize = 4; + using var dir = new TempDirectory(); + using var doc = RcsScanDocument.Open(dir.Write("late.rcs", scan.Build())); + + using var points = doc.Scans[0].ReadPoints().GetEnumerator(); + Assert.Throws(() => points.MoveNext()); + Assert.Throws(() => doc.Scans[0].PointCount); + } + + [Fact] + public void An_Rcs_Truncated_Anywhere_Is_Rejected_As_Malformed() + { + // Wherever the file is cut, the reader reports a malformed file. + byte[] bytes = RcsWithThreePoints(); + using var dir = new TempDirectory(); + + for (int length = 0; length < bytes.Length; length++) + { + string path = dir.Write($"cut/{length}.rcs", bytes[..length]); + AssertRejectedCheaply(() => ReadEverything(p => RcsScanDocument.Open(p), path)); + } + + Assert.Equal(3, OpenAndReadAll(p => RcsScanDocument.Open(p), dir.Write("whole.rcs", bytes))); + } + // ---- E57 XML and prototype limits ----------------------------------------------------------------------------- // The pose element sits three levels below the root, so the nested elements inside it start at depth 4. diff --git a/tests/PclIO.Tests/RcsScanBuilder.cs b/tests/PclIO.Tests/RcsScanBuilder.cs new file mode 100644 index 0000000..368fdbf --- /dev/null +++ b/tests/PclIO.Tests/RcsScanBuilder.cs @@ -0,0 +1,223 @@ +using System.Buffers.Binary; +using System.Runtime.InteropServices; + +namespace PclIO.Tests; + +/// +/// Builds a synthetic .rcs file from the values of its header, its sections and its leaves. The bytes are written from what +/// the reader decodes; no byte of them comes from a real scan. +/// +internal sealed class RcsScanBuilder +{ + public const int HeaderSize = 512; + public const int LeafRecordSize = 368; + public const int PointRecordSize = 16; + + /// Section type of the leaves section. + public const uint LeavesSection = 2; + + /// Section type of the points section. + public const uint PointsSection = 1; + + /// Largest offset a record can hold on an axis. + public const uint MaxOffset = (1u << 18) - 1; + + /// Point count stated in the header. + public long PointCount { get; set; } + + /// Translation stated in the header; every position of the file is relative to it. + public (double X, double Y, double Z) Translation { get; set; } + + /// Scale stated in the header. + public (double X, double Y, double Z) Scale { get; set; } = (1, 1, 1); + + /// Whether the header states that the points hold a colour. + public bool Color { get; set; } = true; + + /// Whether the header states that the points hold an intensity. + public bool Intensity { get; set; } = true; + + /// Whether the header states that the points can hold normals. + public bool Normals { get; set; } + + /// Local bounds stated in the header; the octree bounds of the header are the same. + public (double X, double Y, double Z) BoundsMin { get; set; } = (-10, -10, -10); + + /// Upper corner of . + public (double X, double Y, double Z) BoundsMax { get; set; } = (10, 10, 10); + + /// The sections as they are laid out in the file, by section type. + public List SectionOrder { get; set; } = [LeavesSection, PointsSection]; + + /// The payload of every section that is neither the leaves nor the points section, by section type. + public Dictionary OtherSections { get; } = []; + + /// Bytes that follow the leaf blocks inside the points section. + public byte[] PointsTail { get; set; } = []; + + /// The leaves of the file, in file order. + public List Leaves { get; } = []; + + /// Adds a leaf whose cube starts at and has this edge length, holding these records. + public RcsLeafBuilder AddLeaf((double X, double Y, double Z) min, double edge, params RcsSamplePoint[] records) + { + var leaf = new RcsLeafBuilder(min, edge); + leaf.Records.AddRange(records); + Leaves.Add(leaf); + return leaf; + } + + /// Writes the file. + public byte[] Build() + { + var payloads = new Dictionary + { + [LeavesSection] = BuildLeaves(), + [PointsSection] = BuildPoints(), + }; + + // The header, then the sections in the stated order. + var file = new List(HeaderSize); + file.AddRange(new byte[HeaderSize]); + var entries = new List<(uint Type, long Offset, long Size)>(); + foreach (uint type in SectionOrder) + { + if (!payloads.TryGetValue(type, out byte[]? payload) && !OtherSections.TryGetValue(type, out payload)) + throw new InvalidOperationException($"Section {type} has no payload."); + entries.Add((type, file.Count, payload.Length)); + file.AddRange(payload); + } + + byte[] bytes = [.. file]; + WriteHeader(bytes, entries); + return bytes; + } + + // The leaves section: the number of leaves, four unused bytes, then one record per leaf. + private byte[] BuildLeaves() + { + var section = new byte[8 + (Leaves.Count * LeafRecordSize)]; + BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(0, 4), (uint)Leaves.Count); + for (int i = 0; i < Leaves.Count; i++) + { + Span record = section.AsSpan(8 + (i * LeafRecordSize), LeafRecordSize); + RcsLeafBuilder leaf = Leaves[i]; + WriteTriple(record, leaf.Min); + WriteTriple(record[24..], Add(leaf.Min, leaf.Edge)); + WriteTriple(record[48..], leaf.Min); + WriteTriple(record[72..], Add(leaf.Min, leaf.Edge)); + BinaryPrimitives.WriteUInt32LittleEndian(record[100..104], (uint)leaf.Records.Count); + BinaryPrimitives.WriteUInt32LittleEndian(record[104..108], leaf.StatedBlockSize); + } + return section; + } + + // The points section: the block of every leaf (its index words, then its records), then the tail. + private byte[] BuildPoints() + { + var section = new List(); + foreach (RcsLeafBuilder leaf in Leaves) + { + int blockStart = section.Count; + section.AddRange(new byte[leaf.BytesInFile]); + for (int i = 0; i < leaf.Records.Count; i++) + leaf.Records[i].WriteTo(CollectionsMarshal.AsSpan(section)[(blockStart + leaf.IndexBytesInFile + (i * PointRecordSize))..]); + } + section.AddRange(PointsTail); + return [.. section]; + } + + private void WriteHeader(Span header, List<(uint Type, long Offset, long Size)> entries) + { + // Container signature, then version 3.2. + "ADOCT\0\0\0"u8.CopyTo(header[..8]); + BinaryPrimitives.WriteUInt32LittleEndian(header[8..12], 3); + BinaryPrimitives.WriteUInt32LittleEndian(header[12..16], 2); + + WriteTriple(header[0x10..], Translation); + WriteTriple(header[0x40..], Scale); + + WriteTriple(header[0x70..], BoundsMin); + WriteTriple(header[(0x70 + 24)..], BoundsMax); + WriteTriple(header[0xA0..], BoundsMin); + WriteTriple(header[(0xA0 + 24)..], BoundsMax); + + BinaryPrimitives.WriteUInt64LittleEndian(header[0xD8..0xE0], (ulong)PointCount); + header[0xE0] = (byte)(Color ? 1 : 0); + header[0xE1] = (byte)(Normals ? 1 : 0); + header[0xE2] = (byte)(Intensity ? 1 : 0); + "00000000-0000-0000-0000-000000000001"u8.CopyTo(header[0xE3..]); + "LOCAL_GRID_SYSTEM"u8.CopyTo(header[0x1B9..]); + + BinaryPrimitives.WriteUInt32LittleEndian(header[0x129..0x12D], (uint)entries.Count); + for (int i = 0; i < entries.Count; i++) + { + Span entry = header[(0x12D + (i * 24))..]; + BinaryPrimitives.WriteUInt64LittleEndian(entry[..8], entries[i].Type); + BinaryPrimitives.WriteUInt64LittleEndian(entry[8..16], (ulong)entries[i].Offset); + BinaryPrimitives.WriteUInt64LittleEndian(entry[16..24], (ulong)entries[i].Size); + } + } + + private static void WriteTriple(Span target, (double X, double Y, double Z) value) + { + BinaryPrimitives.WriteDoubleLittleEndian(target[..8], value.X); + BinaryPrimitives.WriteDoubleLittleEndian(target[8..16], value.Y); + BinaryPrimitives.WriteDoubleLittleEndian(target[16..24], value.Z); + } + + private static (double X, double Y, double Z) Add((double X, double Y, double Z) value, double offset) => + (value.X + offset, value.Y + offset, value.Z + offset); +} + +/// One leaf of a synthetic .rcs file: its cube, its records, and what its record states about its block. +internal sealed class RcsLeafBuilder((double X, double Y, double Z) min, double edge) +{ + /// Lower corner of the cube of the leaf. + public (double X, double Y, double Z) Min { get; } = min; + + /// Edge length of the cube of the leaf. + public double Edge { get; } = edge; + + /// The point records of the leaf, in file order. + public List Records { get; } = []; + + /// Bytes of index words before the records; null for the four bytes every record has. + public int? IndexBytes { get; set; } + + /// Block size the leaf record states; null for the size the block is written with. + public uint? DeclaredBlockSize { get; set; } + + /// The index words the block is written with. + public int IndexBytesInFile => IndexBytes ?? 4 * Records.Count; + + /// The bytes the block is written with: its index words, then its records. + public int WrittenBlockSize => IndexBytesInFile + (Records.Count * RcsScanBuilder.PointRecordSize); + + /// The block size the leaf record states: the declared one, or the one the block is written with. + public uint StatedBlockSize => DeclaredBlockSize ?? (uint)WrittenBlockSize; + + /// The bytes the block takes in the file: what it is written with, or more when it states a larger size. + public int BytesInFile => (int)Math.Max(StatedBlockSize, WrittenBlockSize); +} + +/// +/// One point record of a synthetic .rcs leaf, as the file holds it: the millimetre offsets from the corner of the leaf cube +/// on three 18-bit fields, the top byte of the same 64-bit word, and the bytes of the channels. +/// +public readonly record struct RcsSamplePoint(uint X, uint Y, uint Z, byte Intensity = 0, byte R = 0, byte G = 0, byte B = 0, ushort Normal = 0, byte Top = 0) +{ + /// Writes the 16 bytes of the record. + public void WriteTo(Span record) + { + if (X > RcsScanBuilder.MaxOffset || Y > RcsScanBuilder.MaxOffset || Z > RcsScanBuilder.MaxOffset) + throw new ArgumentOutOfRangeException(nameof(X), "An offset does not fit in its 18 bits."); + + BinaryPrimitives.WriteUInt64LittleEndian(record, X | ((ulong)Y << 18) | ((ulong)Z << 36) | ((ulong)Top << 56)); + record[8] = Intensity; + record[9] = B; + record[10] = G; + record[11] = R; + BinaryPrimitives.WriteUInt16LittleEndian(record[12..], Normal); + } +} diff --git a/tests/PclIO.Tests/RealFileTests.cs b/tests/PclIO.Tests/RealFileTests.cs index 8cff42f..eb5f7e3 100644 --- a/tests/PclIO.Tests/RealFileTests.cs +++ b/tests/PclIO.Tests/RealFileTests.cs @@ -1,4 +1,5 @@ using PclIO.Export; +using PclIO.Formats.Recap; using Xunit; namespace PclIO.Tests; @@ -10,6 +11,7 @@ namespace PclIO.Tests; public sealed class RealFileTests { private const int SampleSize = 100; + private const double Precision = 1e-9; private static void AssertReadsPoints(string extension, PclFileKind kind) { @@ -94,6 +96,85 @@ private static void AssertReadable(PclDocument doc, List points, int e [SkippableFact] public void Read_Real_Recap_Project_Points() => AssertReadsPoints(".rcp", PclFileKind.RecapProject); + // The positions of an .rcs file are stored on a grid of this step, in metres. + private const double RcsGridStep = 0.001; + + [SkippableFact] + public void Read_Real_Recap_Scan_To_Its_End() + { + // The smallest scan of the corpus is read to its end, so the check stays fast whatever the corpus holds. A full read + // returns the number of points the scan reports, the points lie within the bounds the header states, and the + // channels follow the flags of the header. + string? path = TestFiles.TryFindAllByExtension(".rcs", TestFiles.Roots()) + .Where(p => PclFile.DetectKind(p) == PclFileKind.RecapScan) + .OrderBy(p => new FileInfo(p).Length) + .FirstOrDefault(StoresDecodablePoints); + if (path == null) throw TestFiles.Missing(".rcs"); + + using var doc = RcsScanDocument.Open(path); + var scan = Assert.Single(doc.Scans); + Assert.True(scan.PointCount > 0); + + long count = 0; + var bounds = PclBounds.Empty; + foreach (PclPoint point in scan.ReadPoints(new PclReadOptions { ApplyTransform = false })) + { + count++; + bounds = bounds.Encapsulate(point.Position); + Assert.Equal(scan.HasColors, point.Color.HasValue); + Assert.Equal(scan.HasIntensities, point.Intensity.HasValue); + if (point.Intensity is { } intensity) Assert.InRange(intensity, 0f, 1f); + if (point.Normal is { } normal) + { + Assert.True(scan.HasNormals); + Assert.Equal(1.0, normal.X * normal.X + normal.Y * normal.Y + normal.Z * normal.Z, Precision); + } + } + + Assert.Equal(scan.PointCount, count); + + // The bounds of the header contain the stored points. They can be wider than these points, when the file states + // the bounds of the scan it was made from; and a stored position is rounded to the grid, so it can leave them by + // one step of the grid at most. + PclBounds stated = doc.LocalBounds; + Assert.True(bounds.Min.X >= stated.Min.X - RcsGridStep, $"x starts at {bounds.Min.X:R}, before {stated.Min.X:R}"); + Assert.True(bounds.Min.Y >= stated.Min.Y - RcsGridStep, $"y starts at {bounds.Min.Y:R}, before {stated.Min.Y:R}"); + Assert.True(bounds.Min.Z >= stated.Min.Z - RcsGridStep, $"z starts at {bounds.Min.Z:R}, before {stated.Min.Z:R}"); + Assert.True(bounds.Max.X <= stated.Max.X + RcsGridStep, $"x ends at {bounds.Max.X:R}, after {stated.Max.X:R}"); + Assert.True(bounds.Max.Y <= stated.Max.Y + RcsGridStep, $"y ends at {bounds.Max.Y:R}, after {stated.Max.Y:R}"); + Assert.True(bounds.Max.Z <= stated.Max.Z + RcsGridStep, $"z ends at {bounds.Max.Z:R}, after {stated.Max.Z:R}"); + Assert.False(bounds.IsEmpty); + + // With a scale of one, the transform adds the translation of the header and leaves the normals as they are. + if (scan.Transform.Scale == PclVector3.One) + { + var translation = scan.Transform.Translation; + var local = doc.ReadAllPoints(new PclReadOptions { ApplyTransform = false, MaxPoints = SampleSize }).ToList(); + var placed = doc.ReadAllPoints(new PclReadOptions { MaxPoints = SampleSize }).ToList(); + + Assert.Equal( + local.Select(p => new PclVector3(p.X * 1 + translation.X, p.Y * 1 + translation.Y, p.Z * 1 + translation.Z)), + placed.Select(p => p.Position)); + Assert.Equal(local.Select(p => p.Normal), placed.Select(p => p.Normal)); + } + } + + // True when the file opens as a scan the reader decodes and states points it stores. + private static bool StoresDecodablePoints(string path) + { + try + { + using var doc = RcsScanDocument.Open(path); + return doc.TotalPointCount > 0; + } + catch (Exception e) when (e is InvalidDataException or NotSupportedException) + { + // A scan of a version the reader does not decode, or a damaged one, is no fixture for the test. + return false; + } + } + + [SkippableFact] public void Read_Real_Leica_Container_Points() => AssertReadsPoints(".lgsx", PclFileKind.LeicaLgsx); diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs index 303a271..d4001ed 100644 --- a/tests/PclIO.Tests/SyntheticFixtures.cs +++ b/tests/PclIO.Tests/SyntheticFixtures.cs @@ -7,9 +7,6 @@ namespace PclIO.Tests; -/// One point record of a synthetic .rcs node: quantised offsets, intensity, colour and an optional packed normal. -public readonly record struct RcsSamplePoint(ushort X, ushort Y, ushort Z, byte Intensity, byte R, byte G, byte B, sbyte Nx = 0, sbyte Ny = 0, sbyte Nz = 0); - /// One point of a synthetic Leica block: 10-bit grid coordinates, optional RGB565 colour and 16-bit intensity. public readonly record struct LeicaSamplePoint(int X, int Y, int Z, ushort Color565 = 0, ushort Intensity = 0); @@ -80,99 +77,34 @@ public readonly record struct CcBinSamplePoint( /// no byte of any of them comes from a real scan. internal static class SyntheticFixtures { - private const int RcsNodeTableOffset = 98605; - private const int RcsNodeSize = 368; - // ---- ReCap scan (.rcs) -------------------------------------------------------------------------------------- - /// A header-only scan: the declared point count is set, the node table is empty, so it yields no points. - public static byte[] CreateSyntheticRcs(long pointCount = 100, double tx = 1.0, double ty = 2.0, double tz = 3.0) - { - byte[] buffer = new byte[RcsNodeTableOffset + 1024]; - WriteRcsHeader(buffer, pointCount, tx, ty, tz); - return buffer; - } - - /// A scan with one node table entry and its point records at the end of the file. - /// Point records; the position is plus 0.0001 times each offset. - /// Tight minimum of the node. - /// Whether the packed normal plane follows the records. - /// Whether the records hold an intensity and a colour; without them they hold the position only. - /// Overrides the payload size the node declares; the records stay as written. - /// Translation of the scan. - /// Translation of the scan. - /// Translation of the scan. - public static byte[] CreateSyntheticRcsWithPoints(IReadOnlyList points, (double X, double Y, double Z) nodeMin, + /// A scan that states a point count in its header but holds no leaf, so it stores no points. + public static byte[] CreateSyntheticRcs(long pointCount = 100, double tx = 1.0, double ty = 2.0, double tz = 3.0) => + new RcsScanBuilder { PointCount = pointCount, Translation = (tx, ty, tz), Color = false, Intensity = false }.Build(); + + /// A scan with one leaf, whose cube is large enough for the largest offset a record can hold, and its records. + /// The records of the leaf; a position counts its offsets in millimetres from . + /// Lower corner of the cube of the leaf, relative to the translation of the scan. + /// Whether the header states that the points can hold normals. + /// Whether the header states that the points hold a colour and an intensity. + /// The block size the leaf states instead of the size it is written with. + /// Translation of the scan, X. + /// Translation of the scan, Y. + /// Translation of the scan, Z. + public static byte[] CreateSyntheticRcsWithPoints(IReadOnlyList points, (double X, double Y, double Z) leafMin, bool withNormals = false, double tx = 0.0, double ty = 0.0, double tz = 0.0, bool withColor = true, uint? declaredPayloadBytes = null) { - int recordBytes = withColor ? 16 : 10; - int recordBytesTotal = recordBytes + (withNormals ? 4 : 0); - int recordBytes_ = points.Count * recordBytesTotal; - byte[] buffer = new byte[RcsNodeTableOffset + 8 + RcsNodeSize + recordBytes_]; - WriteRcsHeader(buffer, points.Count, tx, ty, tz); - - BinaryPrimitives.WriteUInt64LittleEndian(buffer.AsSpan(RcsNodeTableOffset, 8), 1); - Span node = buffer.AsSpan(RcsNodeTableOffset + 8, RcsNodeSize); - double[] min = [nodeMin.X, nodeMin.Y, nodeMin.Z]; - for (int i = 0; i < 3; i++) + var scan = new RcsScanBuilder { - BinaryPrimitives.WriteDoubleLittleEndian(node.Slice(0x30 + (i * 8), 8), min[i]); - BinaryPrimitives.WriteDoubleLittleEndian(node.Slice(0x48 + (i * 8), 8), min[i] + 7.0); - } - BinaryPrimitives.WriteUInt32LittleEndian(node.Slice(0x64, 4), (uint)points.Count); - BinaryPrimitives.WriteUInt32LittleEndian(node.Slice(0x68, 4), declaredPayloadBytes ?? (uint)recordBytes_); - - int payload = buffer.Length - recordBytes_; - int normals = payload + (points.Count * recordBytes); - for (int i = 0; i < points.Count; i++) - { - var p = points[i]; - Span record = buffer.AsSpan(payload + (i * recordBytes), recordBytes); - BinaryPrimitives.WriteUInt16LittleEndian(record.Slice(4, 2), p.X); - BinaryPrimitives.WriteUInt16LittleEndian(record.Slice(6, 2), p.Y); - BinaryPrimitives.WriteUInt16LittleEndian(record.Slice(8, 2), p.Z); - if (withColor) - { - record[12] = p.Intensity; - record[13] = p.R; - record[14] = p.G; - record[15] = p.B; - } - - if (withNormals) - { - buffer[normals + (i * 4)] = (byte)p.Nx; - buffer[normals + (i * 4) + 1] = (byte)p.Ny; - buffer[normals + (i * 4) + 2] = (byte)p.Nz; - } - } - - return buffer; - } - - private static void WriteRcsHeader(byte[] buffer, long pointCount, double tx, double ty, double tz) - { - // Container signature, then version 3.2. - "ADOCT"u8.CopyTo(buffer.AsSpan(0, 5)); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(8, 4), 3); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(12, 4), 2); - - // Translation, rotation, scale. - double[] values = [tx, ty, tz, 0, 0, 0, 1, 1, 1]; - for (int i = 0; i < values.Length; i++) - BinaryPrimitives.WriteDoubleLittleEndian(buffer.AsSpan(0x10 + (i * 8), 8), values[i]); - - // Octree bounds, then local bounds: min -10, max 10 on every axis. - double[] bounds = [-10, -10, -10, 10, 10, 10]; - for (int i = 0; i < bounds.Length; i++) - { - BinaryPrimitives.WriteDoubleLittleEndian(buffer.AsSpan(0x70 + (i * 8), 8), bounds[i]); - BinaryPrimitives.WriteDoubleLittleEndian(buffer.AsSpan(0xA0 + (i * 8), 8), bounds[i]); - } - - BinaryPrimitives.WriteUInt64LittleEndian(buffer.AsSpan(0xD8, 8), (ulong)pointCount); - "00000000-0000-0000-0000-000000000001"u8.CopyTo(buffer.AsSpan(0xE3, 36)); - "LOCAL_GRID_SYSTEM"u8.CopyTo(buffer.AsSpan(0x1B9, 17)); + PointCount = points.Count, + Translation = (tx, ty, tz), + Color = withColor, + Intensity = withColor, + Normals = withNormals, + }; + scan.AddLeaf(leafMin, RcsScanBuilder.MaxOffset * 0.001, [.. points]).DeclaredBlockSize = declaredPayloadBytes; + return scan.Build(); } // ---- ReCap project (.rcp) -------------------------------------------------------------------------------------