diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 474c96c..b0ad66c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -26,6 +26,7 @@ jobs:
8.0.x
- run: dotnet restore PclIO.slnx
- run: dotnet build PclIO.slnx -c Release --no-restore
+ - run: dotnet format PclIO.slnx --verify-no-changes --severity error --no-restore
- run: dotnet test PclIO.slnx -c Release --no-build
- run: dotnet pack PclIO.slnx -c Release --no-build -o artifacts
- uses: actions/upload-artifact@v7
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 20bca00..90e5981 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -8,6 +8,7 @@ on:
- 'docfx.json'
- '.config/dotnet-tools.json'
- 'src/PclIO/**'
+ - 'src/PclIO.Scene/**'
- '.github/workflows/docs.yml'
pull_request:
paths:
@@ -15,6 +16,7 @@ on:
- 'docfx.json'
- '.config/dotnet-tools.json'
- 'src/PclIO/**'
+ - 'src/PclIO.Scene/**'
- '.github/workflows/docs.yml'
workflow_dispatch:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 6ee2174..efa5139 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -40,6 +40,7 @@ jobs:
$notes | Set-Content -LiteralPath release-notes.md -Encoding utf8
- run: dotnet restore PclIO.slnx
- run: dotnet build PclIO.slnx -c Release --no-restore
+ - run: dotnet format PclIO.slnx --verify-no-changes --severity error --no-restore
- run: dotnet test PclIO.slnx -c Release --no-build
- name: Pack release
shell: pwsh
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1ec6911..b67b0c5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- `PclIO.Scene` scene adapter: `PclSceneReader.Read` turns a point cloud file or an opened `PclDocument` into an IOScene `SceneDocument` in metres — one model, one element per scan with the engine's scan id as `SourceId`, non-indexed `Points` geometry with normals when every point of a scan has one, and the scan properties as text. `PclSceneOptions` sets the model key, a total point cap (default 1,000,000, the IOScene contract holds small clouds), a subsampling step and a metres-per-unit factor; `PclSceneResult` reports the scene, the counts and diagnostics for what was left out (per-point colour, intensity and classification are not part of IOScene 0.1.0). The engine stays a leaf: only the adapter references IOScene (`[0.1.0, 0.2.0-0.0)`), and it pins the engine exactly because both ship on one tag.
+- Command line: `pclio export --format scene` (also inferred from the extension `.scene.json`) writes the IOScene scene JSON, prints the conversion diagnostics on standard error, keeps at most 1,000,000 points unless `--limit` is given and rejects `--no-transform`.
- Read packed CC BIN point normals in file versions 41, 42 and 50.
- CC BIN (`*.bin`, `CCB2`) reader supporting single and multi-cloud entity datasets with 32-bit floating point Cartesian XYZ coordinates, global shift and scale vectors, 8-bit RGB colour arrays, 4x4 coordinate transform matrices, and scalar fields (including intensity). Added `CcBinDocument`, `CcBinScan`, and `PclFileKind.CcBin`.
- Leica PTG (`*.ptg`) gridded point cloud reader supporting binary scan files with `PTG\0` signature, magic number `0x928FA3C7`, a binary TLV metadata header (`%%version`, `%%cols`, `%%rows`, `%%properties`, `%%transform` and name records), a uint64 column offset array, and column validity bitmasks (most significant bit first) with single or double precision Cartesian XYZ coordinates, intensity and RGB colour. The scanner pose matrix is transposed from the PTG row-vector convention on load. Top-level ASCII index files (`.ptg`) referencing binary scan files are aggregated into multi-scan documents. Added `PtgDocument`, `PtgScan`, and `PclFileKind.LeicaPtg`.
diff --git a/Directory.Packages.props b/Directory.Packages.props
index e9ed84e..3c309c6 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -9,6 +9,11 @@
+
+
+
+
+
diff --git a/PclIO.slnx b/PclIO.slnx
index deb46fe..88c6ade 100644
--- a/PclIO.slnx
+++ b/PclIO.slnx
@@ -2,6 +2,8 @@
+
+
diff --git a/README.md b/README.md
index 4c03c2f..58f2ba3 100644
--- a/README.md
+++ b/README.md
@@ -2,20 +2,21 @@
-PclIO is a .NET library and command line tool that reads point cloud files from several scanner and project formats and exports the points to LAS, XYZ, PTS and JSON, without the software that wrote the files.
+PclIO is a .NET library and command line tool that reads point cloud files from several scanner and project formats and exports the points to LAS, XYZ, PTS and JSON, without the software that wrote the files. The `PclIO.Scene` adapter turns a cloud into an [IOScene](https://github.com/IOExtend/IOScene) scene for viewers and coordination tools.
## What it does
- Detects the format of a file or folder from its content, extension or layout (`PclFile.DetectKind`).
- Opens a file as a `PclDocument` with its scans, bounds, transforms, metadata and warnings, and streams the points (`ReadAllPoints`, `PclScan.ReadPoints`) with a point limit, a subsampling step and an optional scan transform. Leica scans additionally read a block range with opt-in parallel decoding.
- Exports to ASPRS LAS 1.2 (point format 2) and 1.4 (point formats 6 to 8), ASCII XYZ, ASCII PTS and JSON.
+- Converts a document into an IOScene `SceneDocument` in metres (`PclIO.Scene`, see [scene adapter](docs/scene.md)).
- Ships the command line tool `pclio` with `info`, `scans`, `points` and `export`.
## Install
PclIO is a preview (0.x). The packages are published on nuget.org, not on GitHub Packages, so the Packages box of this repository stays empty.
-[](https://www.nuget.org/packages/PclIO) [](https://www.nuget.org/packages/PclIO.Cli)
+[](https://www.nuget.org/packages/PclIO) [](https://www.nuget.org/packages/PclIO.Cli) [](https://www.nuget.org/packages/PclIO.Scene)
Install the command line tool:
@@ -29,7 +30,13 @@ Add the library to a .NET project:
dotnet add package PclIO
```
-The library targets .NET 8 and .NET 10. It is managed code with no dependencies on other packages (see [third-party notices](THIRD-PARTY-NOTICES.md)), has no native dependencies or Windows-only APIs, and is tested on Windows, Linux and macOS. It does not contact the network and writes nothing to the console.
+Add the scene adapter (depends on `PclIO` and `IOScene`):
+
+```sh
+dotnet add package PclIO.Scene
+```
+
+The library targets .NET 8 and .NET 10. It is managed code with no dependencies on other packages (see [third-party notices](THIRD-PARTY-NOTICES.md)), has no native dependencies or Windows-only APIs, and is tested on Windows, Linux and macOS. It does not contact the network and writes nothing to the console. The engine stays a leaf: only the `PclIO.Scene` adapter references IOScene, and only the command line tool combines the two.
## Supported formats
@@ -165,13 +172,27 @@ outside the file is fetched.
XYZ and PTS output is culture independent (`.` decimal separator) and ends lines with `\n`. JSON output is culture independent; its line ends are those of the platform. Points with a NaN or infinite coordinate are skipped; the overloads with `out long skippedPoints` report how many, and the command line prints `warning: skipped N points with a NaN or infinite coordinate` on standard error when N is not zero. The exception is `pclio points --format json`, which skips nothing and writes such a coordinate as the string `"NaN"`, `"Infinity"` or `"-Infinity"`. Files written by `export` are UTF-8 without a BOM; `info`, `scans` and `points` write to the console with the platform's own line ends and encoding, and control characters in names and messages are printed as `\uXXXX`.
+## Scene adapter
+
+`PclIO.Scene` converts a point cloud document into an IOScene `SceneDocument`: one model, one element per scan, non-indexed `Points` geometry in metres, and the scan properties as text. It follows the [IOScene contract](https://github.com/IOExtend/IOScene/blob/main/docs/contract.md); large clouds are outside that model, so the reader caps the scene at 1,000,000 points by default and reports what it left out. Per-point colour, intensity and classification are not part of IOScene 0.1.0 and are reported as dropped; normals are kept when every point of a scan has one. See [docs/scene.md](docs/scene.md) for the mapping, diagnostics and limits.
+
+```csharp
+using IOScene;
+using PclIO.Scene;
+
+PclSceneResult result = PclSceneReader.Read("site.e57");
+SceneJson.Save(result.Document, "site.scene.json");
+```
+
+The command line writes the same scene: `pclio export site.e57 site.scene.json`.
+
## Command line
```text
pclio info [--json]
pclio scans [--json]
pclio points [--scan ] [--limit ] [--step ] [--format ] [--no-transform]
-pclio export [--format ] [--limit ] [--step ] [--no-transform] [--force]
+pclio export [--format ] [--limit ] [--step ] [--no-transform] [--force]
pclio [--json] same as 'info'
pclio [options] same as 'export'
```
@@ -179,8 +200,8 @@ pclio [options] same as 'export'
- `info` prints the format, file size, scans, point count, bounds, coordinate system, metadata and warnings.
- `scans` lists the scans with their point counts, channels, bounds and translation.
- `points` prints points to standard output, at most 1000 unless `--limit` is given. `--scan` selects one scan by 0-based index, id or name. `--format xyz` and `--format pts` print the same lines as the exporters (PTS starts with its count line); `--format json` prints one JSON object per line.
-- `export` writes a file. The format comes from `--format` or from the output extension (`.las`, `.xyz`, `.pts`, `.json`); any other extension needs `--format`. The output is written to a temporary file next to the target and moved into place when complete. Export refuses to write to the input (compared after following links and junctions, and on Windows by file identity, so the verbatim and device prefixes and administrative shares are caught too; hard links are not detected elsewhere), to a path inside an input folder, to a missing folder or to a directory, and refuses to replace an existing file unless `--force` is given.
-- `--limit` and `--step` take integers of at least 1. `--no-transform` returns coordinates as stored. A JSON export rejects `--step` and `--no-transform`, and `--limit` for it is the number of sample points.
+- `export` writes a file. The format comes from `--format` or from the output extension (`.las`, `.xyz`, `.pts`, `.json`, `.scene.json`); any other extension needs `--format`. The output is written to a temporary file next to the target and moved into place when complete. Export refuses to write to the input (compared after following links and junctions, and on Windows by file identity, so the verbatim and device prefixes and administrative shares are caught too; hard links are not detected elsewhere), to a path inside an input folder, to a missing folder or to a directory, and refuses to replace an existing file unless `--force` is given.
+- `--limit` and `--step` take integers of at least 1. `--no-transform` returns coordinates as stored. A JSON export rejects `--step` and `--no-transform`, and `--limit` for it is the number of sample points. A scene export rejects `--no-transform`, keeps at most 1,000,000 points unless `--limit` is given, and prints the conversion diagnostics on standard error.
- `--help`, `-h` and `help`, and `--version`, `-v` and `version`, print and exit with code 0.
Errors are one line on standard error, with no stack trace for any exit code.
@@ -226,7 +247,7 @@ See the [public API](docs/public-api.md) for the supported surface and [dependen
## Documentation
-[Getting started](docs/getting-started.md), the [public API](docs/public-api.md), [dependencies](docs/dependencies.md) and [private test fixtures](docs/test-fixtures.md) are in `docs/`. The documentation site with the API reference is at , built from them with DocFX (`docfx.json`). [](https://deepwiki.com/IOExtend/PclIO) offers an automatically generated overview of the repository.
+[Getting started](docs/getting-started.md), the [public API](docs/public-api.md), the [scene adapter](docs/scene.md), [dependencies](docs/dependencies.md) and [private test fixtures](docs/test-fixtures.md) are in `docs/`. The documentation site with the API reference is at , built from them with DocFX (`docfx.json`). [](https://deepwiki.com/IOExtend/PclIO) offers an automatically generated overview of the repository.
## Limitations
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 31863fb..d691b4a 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -1,6 +1,8 @@
# Third-party notices
-PclIO has no third-party runtime components: the published packages depend on no other package, and no third-party source code or binaries are included. The Zstandard and Snappy decoders it needs are its own code, written from the public format specifications (RFC 8878 for Zstandard, including its XXH64 content checksum, and the Snappy format description).
+The PclIO engine has no third-party runtime components: the `PclIO` package depends on no other package, and no third-party source code or binaries are included. The Zstandard and Snappy decoders it needs are its own code, written from the public format specifications (RFC 8878 for Zstandard, including its XXH64 content checksum, and the Snappy format description).
+
+The `PclIO.Scene` adapter depends on [IOScene](https://github.com/IOExtend/IOScene), the neutral scene model of the IOExtend ecosystem, released under the same MIT license by the same author. It is a first-party package, not a third-party component; the command line tool carries it through the adapter.
Development and build-time packages (xunit, xunit.runner.visualstudio, Microsoft.NET.Test.Sdk, Microsoft.SourceLink.GitHub,
and ZstdSharp.Port, a test-only benchmark reference for the Zstandard decoder) are not part of the published packages.
diff --git a/docfx.json b/docfx.json
index c80937d..df5e1c2 100644
--- a/docfx.json
+++ b/docfx.json
@@ -2,7 +2,8 @@
"metadata": [
{
"src": [
- { "src": "src/PclIO", "files": ["PclIO.csproj"] }
+ { "src": "src/PclIO", "files": ["PclIO.csproj"] },
+ { "src": "src/PclIO.Scene", "files": ["PclIO.Scene.csproj"] }
],
"dest": "docs/api",
"properties": { "TargetFramework": "net10.0", "TargetFrameworks": "net10.0" },
diff --git a/docs/dependencies.md b/docs/dependencies.md
index b19f4e3..3c61729 100644
--- a/docs/dependencies.md
+++ b/docs/dependencies.md
@@ -8,15 +8,20 @@ All package versions live in `Directory.Packages.props` (central package managem
Build settings shared by every project live in `Directory.Build.props`; the SDK is pinned in `global.json`
(`10.0.100`, `rollForward: latestFeature`, no prereleases).
-## Runtime packages (library)
+## Runtime packages
-None. The library and the command line tool depend on the .NET base class library only (`System.IO.Compression`, `System.Xml`,
-`System.Text.Json`) and reference no native code. A test checks that neither project file references a package.
+The engine (`PclIO`) and the command line tool (`PclIO.Cli`) depend on the .NET base class library only (`System.IO.Compression`,
+`System.Xml`, `System.Text.Json`) and reference no native code and no package. A test checks that neither project file references a package.
+
+The scene adapter (`PclIO.Scene`) is the only shipped project with a package dependency: `IOScene` `[0.1.0, 0.2.0-0.0)`, the neutral
+scene contract of the IOExtend ecosystem. The upper bound keeps out the next breaking line; the adapter pins the engine as an exact
+`[X.Y.Z]` dependency because both ship on one tag. The CLI references the adapter as a project, so the tool carries IOScene too.
### Decisions
-- **No dependencies on other packages.** The Zstandard decoder for the point blocks of Leica containers and the Snappy decoder for
- the channels of PinPoint data files are part of the library, written from the public format specifications.
+- **The engine is a leaf.** No engine code references IOScene or another IOExtend package; the Zstandard decoder for the point blocks
+ of Leica containers and the Snappy decoder for the channels of PinPoint data files are part of the library, written from the public
+ format specifications.
- **Decompression bound.** The Zstandard decoder takes an explicit maximum size, so a frame that declares more than the limit is
rejected before memory is allocated. The Snappy decoder is streaming; memory use does not depend on the size of the data.
@@ -28,7 +33,8 @@ The 11.x line is not used because it pulls `System.IO.Hashing` 11, which does no
## Test packages
Pinned to exact versions: Microsoft.NET.Test.Sdk 18.12.0, xunit 2.9.3 and xunit.runner.visualstudio 4.0.1.
-The test project references the library and the CLI project.
+The test project references the library and the CLI project; the adapter test project (`PclIO.Scene.Tests`) references the adapter
+and links the temporary-directory helper of the main test project.
## Auditing
@@ -46,4 +52,4 @@ Re-run the audit when changing dependencies.
`EmbedUntrackedSources` true, `PublishRepositoryUrl` true, `VersionPrefix` 0.1.0, the package icon (`icon.png` in each packable project folder), symbol packages (`snupkg`),
`DeterministicSourcePaths` true and a `PathMap` that maps the repository folder to `/_/` (so a local pack contains no local
absolute path), and `ContinuousIntegrationBuild` true when `CI`, `GITHUB_ACTIONS` or `TF_BUILD` is set. `src/Directory.Build.props` turns
-warnings into errors for the library and the CLI. The library, the CLI and the tests target `net8.0` and `net10.0`.
+warnings into errors for every project under `src`. The library, the adapter, the CLI and the tests target `net8.0` and `net10.0`.
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 2a01a68..133f9a7 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -22,14 +22,17 @@ pclio scans scan.e57
pclio points scan.e57 --limit 20 --format xyz
pclio export scan.e57 scan.xyz --step 10
pclio export scan.e57 scan.json --limit 100 --force
+pclio export scan.e57 scan.scene.json --limit 100000
```
-The output format of `export` comes from `--format` or from the extension of the output file (`.las`, `.xyz`, `.pts`, `.json`);
-any other extension needs `--format`. The output is written to a temporary file next to the target and moved into place when
+The output format of `export` comes from `--format` or from the extension of the output file (`.las`, `.xyz`, `.pts`, `.json`,
+`.scene.json`); any other extension needs `--format`. The output is written to a temporary file next to the target and moved into place when
it is complete. Export refuses to write to the input (compared after following links and junctions; hard links are not detected),
to a path inside an input folder, to a missing folder or to a directory, and refuses to replace an existing file unless `--force`
is given. `points --format xyz` and `--format pts` print the same lines as the exporters. When points with a NaN or infinite
-coordinate are skipped, one `warning: skipped N points ...` line goes to standard error. Run `pclio --help` for all options.
+coordinate are skipped, one `warning: skipped N points ...` line goes to standard error. A scene export (`--format scene`) writes
+an IOScene scene JSON, keeps at most 1,000,000 points unless `--limit` is given, rejects `--no-transform` and prints the
+conversion diagnostics on standard error; see [Scene adapter](scene.md). Run `pclio --help` for all options.
### Exit codes
diff --git a/docs/index.md b/docs/index.md
index 4d47546..810994b 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -13,14 +13,16 @@ PclIO is a .NET library and command line tool that reads point cloud files from
- Detects the format of a file or folder from its content, extension or layout.
- Opens a file as a document with its scans, bounds, transforms, metadata and warnings, and streams the points with a point limit, a subsampling step and an optional scan transform.
- Exports to ASPRS LAS 1.2 (point format 2), ASCII XYZ, ASCII PTS and JSON.
+- Converts a document into an IOScene scene for viewers and coordination tools (`PclIO.Scene`).
- Ships the command line tool `pclio` with `info`, `scans`, `points` and `export`.
-The library targets .NET 8 and .NET 10, is managed code with no dependencies on other packages, never writes to the console and never contacts the network. It is tested on Windows, Linux and macOS. PclIO is a preview (0.x).
+The library targets .NET 8 and .NET 10, is managed code with no dependencies on other packages, never writes to the console and never contacts the network. The scene adapter depends on the neutral IOScene contract; the engine itself stays a leaf. It is tested on Windows, Linux and macOS. PclIO is a preview (0.x).
## Where to go next
- [Getting started](getting-started.md): install the tool or the package, the supported formats, exit codes and a first export.
- [Public API](public-api.md): the supported surface of the library.
+- [Scene adapter](scene.md): a point cloud as an IOScene scene, its diagnostics and limits.
- [Dependencies](dependencies.md): packages and build settings.
- [Private test fixtures](test-fixtures.md): how tests that need real scan files find them and when they are skipped.
- [API reference](api/PclIO.yml): every public type, generated from the XML documentation.
diff --git a/docs/public-api.md b/docs/public-api.md
index 9959296..8036d0a 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -133,6 +133,17 @@ is empty, rooted, contains invalid characters or resolves outside the folder is
Each exporter has an overload with `out long skippedPoints`, the number of points skipped because a coordinate was NaN or infinite.
Output is culture independent; XYZ and PTS end lines with `\n`, and JSON uses the line ends of the platform. LAS and PTS read the source twice; the others stream it once. Normals are not exported.
+## Scene adapter
+
+The `PclIO.Scene` package converts a document into an IOScene `SceneDocument`. It is a separate package so the engine stays a leaf;
+the [scene adapter guide](scene.md) describes the mapping, the diagnostics and the limits.
+
+| Type | Use |
+|---|---|
+| `PclSceneReader` | Static entry point. `Read(path, options)` opens the file with `PclFile.Open` and converts it; `Read(document, options)` converts an opened document. Both return a `PclSceneResult`. |
+| `PclSceneOptions` | `ModelKey` (null uses the file name), `MaxPoints` (default 1,000,000, null for no limit), `SubsampleStep` (default 1) and `MetresPerUnit` (default 1.0). A negative limit, a step below 1 or a non-positive or non-finite factor throws `ArgumentOutOfRangeException`. |
+| `PclSceneResult` | `Document` (the `SceneDocument`), `Diagnostics` (what the conversion left out), `ScanCount`, `ScansWithPoints`, `PointCount` and `MetresPerUnit`. |
+
## Command line
`PclIO.Cli` installs the tool `pclio`. The `Program` class exposes `Run(args, stdout, stderr)` and the exit-code constants
diff --git a/docs/scene.md b/docs/scene.md
new file mode 100644
index 0000000..cb49bed
--- /dev/null
+++ b/docs/scene.md
@@ -0,0 +1,90 @@
+---
+title: Scene adapter
+---
+
+# PclIO.Scene: point clouds to IOScene
+
+`PclIO.Scene` converts a point cloud file or dataset read by PclIO into an `IOScene` `SceneDocument` for viewers and coordination tools. The scene follows the [IOScene contract](https://github.com/IOExtend/IOScene/blob/main/docs/contract.md) and its [key rules](https://github.com/IOExtend/IOScene/blob/main/docs/keys.md): `SceneModel.Key` plus `SceneElement.SourceId` is the identity that may be stored outside the scene, and the numeric ids are local to it.
+
+**Status:** preview. `PclIO.Scene` is released on the `PclIO` release tag with exactly the same version as `PclIO`, and needs `IOScene` 0.1.0 or a later 0.1 version. The engine itself stays a leaf: it references no other IOExtend package, and only this adapter and the command line tool reference IOScene.
+
+## Usage
+
+```csharp
+using IOScene;
+using PclIO.Scene;
+
+PclSceneResult result = PclSceneReader.Read("site.e57");
+
+foreach (SceneDiagnostic d in result.Diagnostics)
+{
+ Console.WriteLine($"{d.Severity} {d.Code}: {d.Message}");
+}
+
+SceneJson.Save(result.Document, "site.scene.json");
+```
+
+`PclSceneReader.Read(PclDocument, PclSceneOptions)` converts a document that is already open; the model key then comes from `PclDocument.FilePath`, or from `PclSceneOptions.ModelKey`. The command line writes the same scene: `pclio export site.e57 site.scene.json` (the format is also inferred from the extension `.scene.json`).
+
+## What the scene holds
+
+The scene has one model. Geometry positions are in metres, right-handed, Z up, in one coordinate space: the scan transform is applied while reading and the positions are scaled by `PclSceneOptions.MetresPerUnit`.
+
+| Scene part | Content |
+| --- | --- |
+| `SceneModel.Key`, `Name` | `PclSceneOptions.ModelKey`, else the file name with its extension (for a dataset folder, the folder name). |
+| `SceneModel` fields | `SourceFormat` is the format id of `PclDocument.Kind` (table below); `Path` is set only when the scene is read from a path; `Producer` is `PclIO.Scene `. |
+| Elements | A root `Model` element named like the model, then one `Element` per scan with `ParentId` pointing at the root. `Category` is `Point Cloud`, `TypeName` the format id. |
+| `SourceId` | The engine's scan id (`PclScan.Id`), on scan elements only. This derivation does not change; a test pins it. |
+| Property sets | One set named `Scan properties` per scan with properties, holding `PclScan.Properties` as text values (`SceneValueKind.Text`). The properties have no machine key yet: the `pcl:` namespace is not registered in the IOScene key registry. |
+| Geometry, instances | One non-indexed `Points` geometry per scan with points, placed by one instance with no transform (the positions are already in scene coordinates). Normals are kept when every point of the scan has one. |
+
+### `SourceFormat` ids
+
+| Id | Kind | Id | Kind |
+| --- | --- | --- | --- |
+| `e57` | E57 | `pts` | PTS |
+| `rcp` | ReCap project | `ptx` | PTX |
+| `rcs` | ReCap scan | `xyz` | XYZ / text |
+| `lgsx` | Leica container | `sbf` | SBF |
+| `lgs` | Leica legacy container | `pnts` | 3D Tiles |
+| `fls` | FARO scan | `potree` | Potree |
+| `srf` | PinPoint | `laz` | LAZ |
+| `c3db` | EdgeWise | `copc` | COPC |
+| `las` | LAS | `ept` | EPT |
+| `pcd` | PCD | `ptg` | Leica PTG |
+| `ply` | PLY | `ccbin` | CC BIN |
+
+These ids are used by this producer from its first release; the matching rows in the IOScene `docs/keys.md` registry are added there before the first published release, as the registry rules require.
+
+## Options
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `ModelKey` | null (file name) | The model key; empty is invalid. |
+| `MaxPoints` | 1,000,000 | Total point cap across scans; null for no limit. The IOScene contract holds small clouds in memory and puts large point clouds outside the model. Points beyond the cap are reported with `points-capped`. |
+| `SubsampleStep` | 1 | Passed to the engine; readers apply it inside their own blocks, so the spacing is approximate. |
+| `MetresPerUnit` | 1.0 | Metres in one source coordinate unit, applied to every position. Set it when the source uses another unit, for example 0.3048 for a LAS file in feet. |
+
+## Diagnostics
+
+`PclSceneResult.Diagnostics` lists what the conversion left out of the document it was given and could detect; it is empty when it detected nothing.
+
+| Code | Severity | Meaning |
+| --- | --- | --- |
+| `points-capped` | Warning | The point limit was reached; the entry names the limit and how many declared points are not in the scene. |
+| `colours-dropped` | Info | Per-point colour is not part of IOScene 0.1.0; the entry names how many scans carry colour the scene does not hold. |
+| `intensities-dropped` | Info | Per-point intensity is not part of IOScene 0.1.0 (one aggregated entry with the scan count). |
+| `classifications-dropped` | Info | Per-point classification is not part of IOScene 0.1.0 (one aggregated entry with the scan count). |
+| `normals-incomplete` | Info | Some points of a scan have no normal; the normals of those scans are left out (one aggregated entry with the scan count). |
+| `empty-scan` | Info | Scans that were read but yielded no points have no geometry (one aggregated entry with the count). Scans skipped because of the cap are reported by `points-capped` alone. |
+| `reader-warning` | Warning | A warning of the engine document (`PclDocument.Warnings`), one entry each. |
+
+## Limits
+
+- Per-point colour, intensity and classification are not representable in IOScene 0.1.0 and are dropped with a diagnostic. Per-vertex colour is a known additive item of the contract whose first user is small point clouds; when IOScene ships it, this adapter can keep the colour.
+- The scene is a one-way sink: no source file is rebuilt from it, and the engine's exporters (LAS, XYZ, PTS, JSON) remain the lossless path for points.
+- The scan transform is baked into the positions; the instance transform is the identity. A consumer rebases large coordinates as the contract describes.
+- Normals are passed through as the engine returns them; they are kept only when every point of a scan has one.
+- The source length unit is not decoded: positions are taken as metres unless `MetresPerUnit` says otherwise. Georeference and coordinate frames are not part of IOScene 0.1.0.
+- `IfcGuid` is null: point cloud scans have no IFC identity.
diff --git a/docs/toc.yml b/docs/toc.yml
index 6194b2e..207b99f 100644
--- a/docs/toc.yml
+++ b/docs/toc.yml
@@ -5,6 +5,8 @@
items:
- name: Public API
href: public-api.md
+ - name: Scene adapter
+ href: scene.md
- name: Dependencies
href: dependencies.md
- name: Private test fixtures
diff --git a/src/PclIO.Cli/PclIO.Cli.csproj b/src/PclIO.Cli/PclIO.Cli.csproj
index 41b7fc7..8bcfe15 100644
--- a/src/PclIO.Cli/PclIO.Cli.csproj
+++ b/src/PclIO.Cli/PclIO.Cli.csproj
@@ -2,7 +2,7 @@
PclIO.Cli
- Command line tool that inspects point cloud files, lists their scans, prints sample points and exports to LAS, XYZ, PTS or JSON.
+ Command line tool that inspects point cloud files, lists their scans, prints sample points and exports to LAS, XYZ, PTS, JSON or an IOScene scene.
Exe
true
pclio
@@ -12,6 +12,7 @@
+
diff --git a/src/PclIO.Cli/Program.cs b/src/PclIO.Cli/Program.cs
index 6806008..91bbe26 100644
--- a/src/PclIO.Cli/Program.cs
+++ b/src/PclIO.Cli/Program.cs
@@ -31,7 +31,7 @@ public static class Program
private const long DefaultPointsLimit = 1000;
private static readonly string[] PointsFormats = ["xyz", "pts", "json"];
- private static readonly string[] ExportFormats = ["las", "xyz", "pts", "json"];
+ private static readonly string[] ExportFormats = ["las", "xyz", "pts", "json", "scene"];
private static readonly UTF8Encoding Utf8NoBom = new(encoderShouldEmitUTF8Identifier: false);
@@ -57,7 +57,7 @@ public static class Program
pclio info [--json]
pclio scans [--json]
pclio points [--scan ] [--limit ] [--step ] [--format ] [--no-transform]
- pclio export [--format ] [--limit ] [--step ] [--no-transform] [--force]
+ pclio export [--format ] [--limit ] [--step ] [--no-transform] [--force]
pclio [--json] same as 'info'
pclio [options] same as 'export'
pclio --help | -h
@@ -90,6 +90,11 @@ PLY by header structure (.ply)
SBF Simple Binary Format with a companion header (.sbf, .sbf.data)
3D Tiles OGC 3D Tiles point clouds and glTF point primitives (.pnts, .glb, tileset.json)
Potree Potree octree point clouds (cloud.js, metadata.json, .hrc, .bin)
+ LAZ LASzip compressed LAS by signature and a valid LASzip record (.laz)
+ COPC Cloud Optimized Point Cloud, a LAS 1.4 copc record (.copc.laz)
+ EPT Entwine Point Tile datasets (ept.json, ept-hierarchy/, ept-data/)
+ Leica PTG by the PTG signature and magic, or a 'PTG index' header with the extension .ptg
+ CC BIN binary point cloud entities by the CCB2 signature (.bin)
Output formats (--format, or the output extension; any other extension needs --format):
las ASPRS LAS 1.2, point data record format 2 (XYZ, intensity, RGB)
@@ -97,10 +102,14 @@ Potree Potree octree point clouds (cloud.js, metadata.json, .hrc, .bin)
pts ASCII: a line with the point count, then "X Y Z intensity R G B" per point
json export: metadata and scans; with --limit also the first n points (--step and --no-transform are rejected)
points: one JSON object per line with x, y, z, intensity, r, g, b (null when the point lacks a value)
+ scene IOScene scene JSON (also inferred from the extension .scene.json): one element per scan, point geometry
+ in metres, scan properties as text. Per-point colour, intensity and classification are not part of
+ IOScene 0.1.0 and are reported on standard error. At most 1,000,000 points unless --limit is given;
+ --no-transform is rejected. Conversion notes and warnings go to standard error.
las, xyz, pts and the json export skip points with a NaN or infinite coordinate; the count is reported on
standard error. 'points --format json' writes every point; such coordinates appear as the strings "NaN",
"Infinity" and "-Infinity".
- No output format stores normals.
+ No output format stores normals, except scene, which keeps them when every point of a scan has one.
Options:
--scan points only: read one scan by 0-based index, id or name (default: all scans)
@@ -426,6 +435,9 @@ private static int RunExport(string command, string[] args, TextWriter stdout, T
throw Usage($"--limit for --format json must not exceed {int.MaxValue}");
}
+ if (format == "scene" && parsed.Flags.Contains("--no-transform"))
+ throw Usage("--no-transform is not supported with --format scene; the scene holds one transformed coordinate space");
+
string input = ResolveInput(parsed.Positionals[0]);
string output = FullPath(outputArg, "output");
@@ -492,6 +504,23 @@ private static int RunExport(string command, string[] args, TextWriter stdout, T
return n;
}));
break;
+ case "scene":
+ label = "IOScene JSON";
+ var sceneOptions = new PclIO.Scene.PclSceneOptions
+ {
+ // Without --limit the adapter's own cap applies, so a huge cloud cannot fill the disk by accident.
+ MaxPoints = options.MaxPoints ?? PclIO.Scene.PclSceneOptions.Default.MaxPoints,
+ SubsampleStep = options.SubsampleStep,
+ };
+ count = WriteThroughTempFile(output, stderr, force, fs =>
+ {
+ PclIO.Scene.PclSceneResult result = PclIO.Scene.PclSceneReader.Read(doc, sceneOptions);
+ foreach (IOScene.SceneDiagnostic d in result.Diagnostics)
+ stderr.WriteLine($"{(d.Severity == IOScene.SceneSeverity.Warning ? "warning" : "note")}: {d.Code}: {d.Message}");
+ IOScene.SceneJson.Write(result.Document, fs);
+ return result.PointCount;
+ });
+ break;
default:
label = "XYZ";
count = WriteThroughTempFile(output, stderr, force, fs => WriteText(fs, sw =>
@@ -631,6 +660,9 @@ private static long WriteThroughTempFile(string output, TextWriter stderr, bool
private static string FormatFromExtension(string outputPath)
{
+ if (outputPath.EndsWith(".scene.json", StringComparison.OrdinalIgnoreCase))
+ return "scene";
+
string ext = Path.GetExtension(outputPath).TrimStart('.').ToLowerInvariant();
if (!ExportFormats.Contains(ext))
throw Usage($"cannot infer the output format from '{outputPath}'; use --format <{string.Join('|', ExportFormats)}>");
diff --git a/src/PclIO.Scene/PclIO.Scene.csproj b/src/PclIO.Scene/PclIO.Scene.csproj
new file mode 100644
index 0000000..42682f6
--- /dev/null
+++ b/src/PclIO.Scene/PclIO.Scene.csproj
@@ -0,0 +1,35 @@
+
+
+
+ Turns a point cloud read by PclIO into an IOScene scene document in metres: one element per scan, non-indexed point geometry with normals, and the scan properties as text.
+ pointcloud;lidar;laser-scanning;ioscene;scene;viewer
+ net8.0;net10.0
+ PclIO.Scene
+ PclIO.Scene
+ PclIO.Scene
+ true
+
+ $(NoWarn);NU5104
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ <_Pinned Include="@(_ProjectReferencesWithVersions)">[%(_ProjectReferencesWithVersions.ProjectVersion)]
+ <_ProjectReferencesWithVersions Remove="@(_ProjectReferencesWithVersions)" />
+ <_ProjectReferencesWithVersions Include="@(_Pinned)" />
+
+
+
+
diff --git a/src/PclIO.Scene/PclSceneOptions.cs b/src/PclIO.Scene/PclSceneOptions.cs
new file mode 100644
index 0000000..cfb2226
--- /dev/null
+++ b/src/PclIO.Scene/PclSceneOptions.cs
@@ -0,0 +1,71 @@
+namespace PclIO.Scene;
+
+/// Options for .
+public sealed record PclSceneOptions
+{
+ /// Default options: the file name as model key, at most 1,000,000 points, every point, coordinates taken as metres.
+ public static PclSceneOptions Default { get; } = new();
+
+ ///
+ /// The key of the scene model (SceneModel.Key ), which with each scan's SourceId forms the identity that may
+ /// be stored outside the scene. Null uses the file name with its extension, for example Site.e57 . A document
+ /// without a file name needs it. An empty key is invalid, and throws
+ /// for it.
+ ///
+ public string? ModelKey { get; init; }
+
+ private readonly long? _maxPoints = 1_000_000;
+
+ ///
+ /// Maximum number of points in the scene, across all scans; null for no limit. The IOScene contract holds small
+ /// clouds in memory and puts large point clouds outside the model, so the default caps the scene at 1,000,000 points.
+ /// Points beyond the cap are left out and reported with a points-capped diagnostic. Must not be negative;
+ /// 0 makes a scene without geometry.
+ ///
+ /// The value is negative.
+ public long? MaxPoints
+ {
+ get => _maxPoints;
+ init
+ {
+ ArgumentOutOfRangeException.ThrowIfNegative(value ?? 0, nameof(value));
+ _maxPoints = value;
+ }
+ }
+
+ private readonly int _subsampleStep = 1;
+
+ ///
+ /// Subsampling step passed to the engine: 1 keeps every point, N keeps one point in N. Readers apply the step inside
+ /// their own internal blocks, so the spacing is approximate and depends on the format's block layout. Must be at least 1.
+ ///
+ /// The value is less than 1.
+ public int SubsampleStep
+ {
+ get => _subsampleStep;
+ init
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(value, 1, nameof(value));
+ _subsampleStep = value;
+ }
+ }
+
+ private readonly double _metresPerUnit = 1.0;
+
+ ///
+ /// Metres in one unit of the source coordinates, applied to every point position. The scene is in metres; most
+ /// scanner formats store metres, so the default is 1. Set it when the source uses another unit, for example 0.3048
+ /// for a LAS file in feet. Must be finite and above zero.
+ ///
+ /// The value is not finite or not above zero.
+ public double MetresPerUnit
+ {
+ get => _metresPerUnit;
+ init
+ {
+ if (!double.IsFinite(value) || value <= 0)
+ throw new ArgumentOutOfRangeException(nameof(value), "The metres-per-unit factor must be finite and above zero.");
+ _metresPerUnit = value;
+ }
+ }
+}
diff --git a/src/PclIO.Scene/PclSceneReader.cs b/src/PclIO.Scene/PclSceneReader.cs
new file mode 100644
index 0000000..fdb9e04
--- /dev/null
+++ b/src/PclIO.Scene/PclSceneReader.cs
@@ -0,0 +1,288 @@
+using System.Globalization;
+using System.Reflection;
+using IOScene;
+
+namespace PclIO.Scene;
+
+/// Converts a point cloud file, or a read by PclIO, into a .
+///
+///
+/// The scene has one : Key and Name are , else the
+/// file name; SourceFormat is the format id of (see docs/scene.md ). One
+/// per scan holds the scan's properties as text; its points become one non-indexed
+/// geometry, placed by one instance.
+///
+///
+/// Point positions are read with the scan transform applied and scaled by , so the
+/// scene is in metres with one coordinate space. Per-point colour, intensity and classification are not part of IOScene 0.1.0
+/// and are left out with a diagnostic; normals are kept when every point of a scan has one.
+///
+///
+public static class PclSceneReader
+{
+ private static readonly string Producer = "PclIO.Scene "
+ + typeof(PclSceneReader).Assembly.GetCustomAttribute()!.InformationalVersion.Split('+')[0];
+
+ /// Reads the point cloud file or dataset at with and converts it.
+ /// The point cloud file or dataset folder.
+ /// Conversion options; null uses the defaults.
+ /// The scene with a report of the conversion.
+ /// or is empty.
+ /// The format is not recognized or uses an unsupported feature.
+ /// The file is malformed or truncated.
+ public static PclSceneResult Read(string path, PclSceneOptions? options = null)
+ {
+ ArgumentException.ThrowIfNullOrEmpty(path);
+ string key = options?.ModelKey ?? Path.GetFileName(path);
+ if (key.Length == 0)
+ {
+ throw new ArgumentException("PclSceneOptions.ModelKey must not be empty; leave it null to use the file name.", nameof(options));
+ }
+
+ using var document = PclFile.Open(path);
+ return Convert(document, key, path, options ?? PclSceneOptions.Default);
+ }
+
+ ///
+ /// Converts an opened document. replaces the key derived from
+ /// ; a document whose file path has no file name needs it.
+ ///
+ /// The document, for example from .
+ /// Conversion options; null uses the defaults.
+ /// The scene with a report of the conversion.
+ /// is null.
+ /// The model key is empty and the document has no file name to derive one from.
+ public static PclSceneResult Read(PclDocument document, PclSceneOptions? options = null)
+ {
+ ArgumentNullException.ThrowIfNull(document);
+ options ??= PclSceneOptions.Default;
+ string key = options.ModelKey ?? Path.GetFileName(document.FilePath);
+ if (string.IsNullOrEmpty(key))
+ {
+ throw new ArgumentException("A document without a file name needs PclSceneOptions.ModelKey.", nameof(options));
+ }
+
+ return Convert(document, key, null, options);
+ }
+
+ private static PclSceneResult Convert(PclDocument document, string key, string? path, PclSceneOptions options)
+ {
+ string formatId = FormatId(document.Kind);
+ var scene = new SceneDocument { Title = key };
+ var diagnostics = new List();
+
+ scene.Models.Add(new SceneModel
+ {
+ Id = 1,
+ Key = key,
+ Name = key,
+ Path = path,
+ SourceFormat = formatId,
+ Producer = Producer,
+ });
+
+ var root = new SceneElement
+ {
+ Id = 1,
+ ModelId = 1,
+ Kind = SceneNodeKind.Model,
+ Name = key,
+ };
+ scene.Elements.Add(root);
+
+ long remaining = options.MaxPoints ?? long.MaxValue;
+ long totalRead = 0;
+ int scansWithPoints = 0;
+ int scansWithColors = 0;
+ int scansWithIntensities = 0;
+ int scansWithClassifications = 0;
+ int scansWithIncompleteNormals = 0;
+ int emptyScans = 0;
+ double scale = options.MetresPerUnit;
+
+ for (int i = 0; i < document.Scans.Count; i++)
+ {
+ PclScan scan = document.Scans[i];
+ var element = new SceneElement
+ {
+ Id = 2 + i,
+ ModelId = 1,
+ ParentId = 1,
+ Kind = SceneNodeKind.Element,
+ SourceId = scan.Id,
+ Name = string.IsNullOrEmpty(scan.Name) ? scan.Id : scan.Name,
+ Category = "Point Cloud",
+ TypeName = formatId,
+ };
+ scene.Elements.Add(element);
+
+ if (scan.Properties.Count > 0)
+ {
+ var set = new ScenePropertySet
+ {
+ Id = scene.PropertySets.Count + 1,
+ Name = "Scan properties",
+ };
+ foreach (var pair in scan.Properties)
+ {
+ set.Properties.Add(new SceneProperty
+ {
+ Name = pair.Key,
+ Value = SceneValue.FromText(pair.Value),
+ });
+ }
+ scene.PropertySets.Add(set);
+ element.PropertySetIds.Add(set.Id);
+ }
+
+ if (remaining <= 0) continue;
+
+ var readOptions = new PclReadOptions
+ {
+ MaxPoints = remaining,
+ SubsampleStep = options.SubsampleStep,
+ ApplyTransform = true,
+ };
+
+ var vertices = new List();
+ var normals = new List();
+ bool hasColors = false, hasIntensities = false, hasClassifications = false;
+ bool anyNormal = false, allNormals = true;
+
+ foreach (PclPoint point in scan.ReadPoints(readOptions))
+ {
+ vertices.Add(new Vector3d(point.X * scale, point.Y * scale, point.Z * scale));
+ if (point.Color.HasValue) hasColors = true;
+ if (point.Intensity.HasValue) hasIntensities = true;
+ if (point.Classification.HasValue) hasClassifications = true;
+ if (point.Normal is { } normal)
+ {
+ anyNormal = true;
+ normals.Add(new Vector3d(normal.X, normal.Y, normal.Z));
+ }
+ else
+ {
+ allNormals = false;
+ }
+ }
+
+ remaining -= vertices.Count;
+ totalRead += vertices.Count;
+ if (hasColors) scansWithColors++;
+ if (hasIntensities) scansWithIntensities++;
+ if (hasClassifications) scansWithClassifications++;
+
+ if (vertices.Count == 0)
+ {
+ emptyScans++;
+ continue;
+ }
+
+ scansWithPoints++;
+ var geometry = new SceneGeometry
+ {
+ Id = scene.Geometries.Count + 1,
+ Topology = SceneTopology.Points,
+ Vertices = vertices,
+ };
+ if (anyNormal && allNormals)
+ {
+ geometry.Normals = normals;
+ }
+ else if (anyNormal)
+ {
+ scansWithIncompleteNormals++;
+ }
+ scene.Geometries.Add(geometry);
+ scene.Instances.Add(new SceneInstance
+ {
+ ElementId = element.Id,
+ GeometryId = geometry.Id,
+ Name = element.Name,
+ });
+ }
+
+ if (options.MaxPoints.HasValue && totalRead >= options.MaxPoints.Value)
+ {
+ long omitted = document.TotalPointCount - totalRead;
+ if (omitted > 0)
+ {
+ diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "points-capped",
+ string.Create(CultureInfo.InvariantCulture,
+ $"The point limit of {options.MaxPoints.Value} was reached; {omitted} declared points are not in the scene.")));
+ }
+ }
+ if (scansWithColors > 0)
+ {
+ diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "colours-dropped",
+ string.Create(CultureInfo.InvariantCulture,
+ $"Per-point colour is not part of IOScene 0.1.0; {scansWithColors} scans carry colour the scene does not hold.")));
+ }
+ if (scansWithIntensities > 0)
+ {
+ diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "intensities-dropped",
+ string.Create(CultureInfo.InvariantCulture,
+ $"Per-point intensity is not part of IOScene 0.1.0; {scansWithIntensities} scans carry intensity the scene does not hold.")));
+ }
+ if (scansWithClassifications > 0)
+ {
+ diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "classifications-dropped",
+ string.Create(CultureInfo.InvariantCulture,
+ $"Per-point classification is not part of IOScene 0.1.0; {scansWithClassifications} scans carry classification the scene does not hold.")));
+ }
+ if (scansWithIncompleteNormals > 0)
+ {
+ diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "normals-incomplete",
+ string.Create(CultureInfo.InvariantCulture,
+ $"{scansWithIncompleteNormals} scans have points without a normal; their normals are left out.")));
+ }
+ if (emptyScans > 0)
+ {
+ diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "empty-scan",
+ string.Create(CultureInfo.InvariantCulture,
+ $"{emptyScans} scans yielded no points and have no geometry in the scene.")));
+ }
+ foreach (string warning in document.Warnings)
+ {
+ diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "reader-warning", warning));
+ }
+
+ return new PclSceneResult
+ {
+ Document = scene,
+ Diagnostics = diagnostics,
+ ScanCount = document.Scans.Count,
+ ScansWithPoints = scansWithPoints,
+ PointCount = totalRead,
+ MetresPerUnit = scale,
+ };
+ }
+
+ /// The registered-style id of the format of the content, used as SceneModel.SourceFormat and the element type name.
+ private static string FormatId(PclFileKind kind) => kind switch
+ {
+ PclFileKind.E57 => "e57",
+ PclFileKind.RecapProject => "rcp",
+ PclFileKind.RecapScan => "rcs",
+ PclFileKind.LeicaLgsx => "lgsx",
+ PclFileKind.LeicaLgs => "lgs",
+ PclFileKind.FaroFls => "fls",
+ PclFileKind.PinPoint => "srf",
+ PclFileKind.EdgeWise => "c3db",
+ PclFileKind.Las => "las",
+ PclFileKind.Pcd => "pcd",
+ PclFileKind.Ply => "ply",
+ PclFileKind.Pts => "pts",
+ PclFileKind.Ptx => "ptx",
+ PclFileKind.Xyz => "xyz",
+ PclFileKind.Sbf => "sbf",
+ PclFileKind.Tiles3d => "pnts",
+ PclFileKind.Potree => "potree",
+ PclFileKind.Laz => "laz",
+ PclFileKind.Copc => "copc",
+ PclFileKind.Ept => "ept",
+ PclFileKind.LeicaPtg => "ptg",
+ PclFileKind.CcBin => "ccbin",
+ _ => throw new NotSupportedException($"No scene format id is described for {kind}."),
+ };
+}
diff --git a/src/PclIO.Scene/PclSceneResult.cs b/src/PclIO.Scene/PclSceneResult.cs
new file mode 100644
index 0000000..d136876
--- /dev/null
+++ b/src/PclIO.Scene/PclSceneResult.cs
@@ -0,0 +1,28 @@
+using IOScene;
+
+namespace PclIO.Scene;
+
+/// The scene made from one point cloud document by , what was lost on the way, and counts.
+public sealed class PclSceneResult
+{
+ /// The scene: one model with one element per scan, point geometry in metres, and the scan properties as text.
+ public required SceneDocument Document { get; init; }
+
+ ///
+ /// What the conversion left out of the document it was given and could detect; empty when it detected nothing.
+ /// Per-point colour, intensity and classification are not part of IOScene 0.1.0 and are always reported when present.
+ ///
+ public IReadOnlyList Diagnostics { get; init; } = [];
+
+ /// The number of scans in the document, each one element of the scene.
+ public int ScanCount { get; init; }
+
+ /// The number of scans with at least one point in the scene.
+ public int ScansWithPoints { get; init; }
+
+ /// The number of points in the scene.
+ public long PointCount { get; init; }
+
+ /// The metres-per-unit factor used: .
+ public double MetresPerUnit { get; init; }
+}
diff --git a/src/PclIO/Formats/Potree/PotreeScan.cs b/src/PclIO/Formats/Potree/PotreeScan.cs
index 312153e..88ab9fb 100644
--- a/src/PclIO/Formats/Potree/PotreeScan.cs
+++ b/src/PclIO/Formats/Potree/PotreeScan.cs
@@ -189,17 +189,17 @@ private static bool TryDecodePoint(ReadOnlySpan record, PotreeLayout layou
normal = DecodeOct16p(record[off], record[off + 1]);
break;
case NormalEncoding.Floats:
- {
- float nx = BinaryPrimitives.ReadSingleLittleEndian(record.Slice(off, 4));
- float ny = BinaryPrimitives.ReadSingleLittleEndian(record.Slice(off + 4, 4));
- float nz = BinaryPrimitives.ReadSingleLittleEndian(record.Slice(off + 8, 4));
- if (float.IsFinite(nx) && float.IsFinite(ny) && float.IsFinite(nz))
{
- double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
- normal = len > 0 ? new PclVector3(nx / len, ny / len, nz / len) : new PclVector3(nx, ny, nz);
+ float nx = BinaryPrimitives.ReadSingleLittleEndian(record.Slice(off, 4));
+ float ny = BinaryPrimitives.ReadSingleLittleEndian(record.Slice(off + 4, 4));
+ float nz = BinaryPrimitives.ReadSingleLittleEndian(record.Slice(off + 8, 4));
+ if (float.IsFinite(nx) && float.IsFinite(ny) && float.IsFinite(nz))
+ {
+ double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
+ normal = len > 0 ? new PclVector3(nx / len, ny / len, nz / len) : new PclVector3(nx, ny, nz);
+ }
+ break;
}
- break;
- }
}
}
diff --git a/src/PclIO/Formats/Tiles3d/GlbScan.cs b/src/PclIO/Formats/Tiles3d/GlbScan.cs
index a7fa91f..d6ac4e1 100644
--- a/src/PclIO/Formats/Tiles3d/GlbScan.cs
+++ b/src/PclIO/Formats/Tiles3d/GlbScan.cs
@@ -504,33 +504,33 @@ private static PclColor DecodeColor(ReadOnlySpan span, AccessorDesc desc)
switch (desc.ComponentType)
{
case 5121: // UNSIGNED_BYTE
- {
- byte r = span[0];
- byte g = span[1];
- byte b = span[2];
- byte a = hasAlpha ? span[3] : (byte)255;
- return new PclColor(r, g, b, a);
- }
+ {
+ byte r = span[0];
+ byte g = span[1];
+ byte b = span[2];
+ byte a = hasAlpha ? span[3] : (byte)255;
+ return new PclColor(r, g, b, a);
+ }
case 5123: // UNSIGNED_SHORT
- {
- ushort r16 = BinaryPrimitives.ReadUInt16LittleEndian(span);
- ushort g16 = BinaryPrimitives.ReadUInt16LittleEndian(span[2..]);
- ushort b16 = BinaryPrimitives.ReadUInt16LittleEndian(span[4..]);
- ushort a16 = hasAlpha ? BinaryPrimitives.ReadUInt16LittleEndian(span[6..]) : (ushort)65535;
- return new PclColor((byte)(r16 * 255 / 65535), (byte)(g16 * 255 / 65535), (byte)(b16 * 255 / 65535), (byte)(a16 * 255 / 65535));
- }
+ {
+ ushort r16 = BinaryPrimitives.ReadUInt16LittleEndian(span);
+ ushort g16 = BinaryPrimitives.ReadUInt16LittleEndian(span[2..]);
+ ushort b16 = BinaryPrimitives.ReadUInt16LittleEndian(span[4..]);
+ ushort a16 = hasAlpha ? BinaryPrimitives.ReadUInt16LittleEndian(span[6..]) : (ushort)65535;
+ return new PclColor((byte)(r16 * 255 / 65535), (byte)(g16 * 255 / 65535), (byte)(b16 * 255 / 65535), (byte)(a16 * 255 / 65535));
+ }
case 5126: // FLOAT
- {
- float rf = BinaryPrimitives.ReadSingleLittleEndian(span);
- float gf = BinaryPrimitives.ReadSingleLittleEndian(span[4..]);
- float bf = BinaryPrimitives.ReadSingleLittleEndian(span[8..]);
- float af = hasAlpha ? BinaryPrimitives.ReadSingleLittleEndian(span[12..]) : 1.0f;
- return new PclColor(
- (byte)Math.Clamp((int)Math.Round(rf * 255.0f), 0, 255),
- (byte)Math.Clamp((int)Math.Round(gf * 255.0f), 0, 255),
- (byte)Math.Clamp((int)Math.Round(bf * 255.0f), 0, 255),
- (byte)Math.Clamp((int)Math.Round(af * 255.0f), 0, 255));
- }
+ {
+ float rf = BinaryPrimitives.ReadSingleLittleEndian(span);
+ float gf = BinaryPrimitives.ReadSingleLittleEndian(span[4..]);
+ float bf = BinaryPrimitives.ReadSingleLittleEndian(span[8..]);
+ float af = hasAlpha ? BinaryPrimitives.ReadSingleLittleEndian(span[12..]) : 1.0f;
+ return new PclColor(
+ (byte)Math.Clamp((int)Math.Round(rf * 255.0f), 0, 255),
+ (byte)Math.Clamp((int)Math.Round(gf * 255.0f), 0, 255),
+ (byte)Math.Clamp((int)Math.Round(bf * 255.0f), 0, 255),
+ (byte)Math.Clamp((int)Math.Round(af * 255.0f), 0, 255));
+ }
default:
return new PclColor(255, 255, 255, 255);
}
diff --git a/src/PclIO/Formats/Tiles3d/PntsScan.cs b/src/PclIO/Formats/Tiles3d/PntsScan.cs
index 73af946..493ae59 100644
--- a/src/PclIO/Formats/Tiles3d/PntsScan.cs
+++ b/src/PclIO/Formats/Tiles3d/PntsScan.cs
@@ -524,24 +524,24 @@ private bool TryDecodePoint(long index, ReadOnlySpan ftBin, ReadOnlySpan ftBin, ReadOnlySpan 0 ? new PclVector3(nx / len, ny / len, nz / len) : new PclVector3(nx, ny, nz);
+ int offset = _normOffset + (int)(index * 12);
+ float nx = BinaryPrimitives.ReadSingleLittleEndian(ftBin.Slice(offset, 4));
+ float ny = BinaryPrimitives.ReadSingleLittleEndian(ftBin.Slice(offset + 4, 4));
+ float nz = BinaryPrimitives.ReadSingleLittleEndian(ftBin.Slice(offset + 8, 4));
+ if (float.IsFinite(nx) && float.IsFinite(ny) && float.IsFinite(nz))
+ {
+ double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
+ normal = len > 0 ? new PclVector3(nx / len, ny / len, nz / len) : new PclVector3(nx, ny, nz);
+ }
+ break;
}
- break;
- }
case NormalFormat.Oct16p:
- {
- int offset = _normOffset + (int)(index * 2);
- normal = DecodeOct16p(ftBin[offset], ftBin[offset + 1]);
- break;
- }
+ {
+ int offset = _normOffset + (int)(index * 2);
+ normal = DecodeOct16p(ftBin[offset], ftBin[offset + 1]);
+ break;
+ }
}
// Intensity
diff --git a/tests/PclIO.Scene.Tests/PclIO.Scene.Tests.csproj b/tests/PclIO.Scene.Tests/PclIO.Scene.Tests.csproj
new file mode 100644
index 0000000..8c46057
--- /dev/null
+++ b/tests/PclIO.Scene.Tests/PclIO.Scene.Tests.csproj
@@ -0,0 +1,27 @@
+
+
+
+ net8.0;net10.0
+ PclIO.Scene.Tests
+ false
+ true
+
+
+
+
+
+
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/PclIO.Scene.Tests/PclSceneReaderTests.cs b/tests/PclIO.Scene.Tests/PclSceneReaderTests.cs
new file mode 100644
index 0000000..a755491
--- /dev/null
+++ b/tests/PclIO.Scene.Tests/PclSceneReaderTests.cs
@@ -0,0 +1,362 @@
+using System.Buffers.Binary;
+using System.Text;
+using IOScene;
+using PclIO;
+using PclIO.Scene;
+using PclIO.Tests;
+using Xunit;
+
+namespace PclIO.Scene.Tests;
+
+public sealed class PclSceneReaderTests
+{
+ private static string XyzFile(TempDirectory dir, int points, string name = "cloud.xyz")
+ {
+ var sb = new StringBuilder();
+ for (int i = 0; i < points; i++)
+ sb.Append(i).Append(' ').Append(i * 2).Append(' ').Append(i * 3).Append('\n');
+ return dir.Write(name, Encoding.ASCII.GetBytes(sb.ToString()));
+ }
+
+ private static string PtsFileWithChannels(TempDirectory dir)
+ {
+ string text = "2\n1 2 3 0.5 10 20 30\n4 5 6 0.8 100 150 200\n";
+ return dir.Write("channels.pts", Encoding.ASCII.GetBytes(text));
+ }
+
+ private static string PlyFileWithNormals(TempDirectory dir)
+ {
+ string text =
+ "ply\nformat ascii 1.0\nelement vertex 2\n" +
+ "property float x\nproperty float y\nproperty float z\n" +
+ "property float nx\nproperty float ny\nproperty float nz\n" +
+ "end_header\n" +
+ "1 2 3 0 0 1\n4 5 6 0 1 0\n";
+ return dir.Write("normals.ply", Encoding.ASCII.GetBytes(text));
+ }
+
+ /// A one-row PTG scan with one point per column, float XYZ only (properties 0x01), in the binary TLV layout.
+ /// The optional transform is in the PTG row-vector convention (translation in the last row).
+ private static byte[] PtgChunk((float X, float Y, float Z)[] columnPoints, double[]? transform = null, bool pointValid = true)
+ {
+ using var ms = new MemoryStream();
+ ms.Write([0x50, 0x54, 0x47, 0x00]);
+ Span magic = stackalloc byte[4];
+ BinaryPrimitives.WriteUInt32LittleEndian(magic, 0x928FA3C7);
+ ms.Write(magic);
+
+ void Record(string key, byte[] value)
+ {
+ byte[] name = Encoding.ASCII.GetBytes(key + "\0");
+ Span u32 = stackalloc byte[4];
+ BinaryPrimitives.WriteUInt32LittleEndian(u32, (uint)name.Length);
+ ms.Write(u32);
+ ms.Write(name);
+ ms.Write(value);
+ }
+ void U32(string key, uint value)
+ {
+ byte[] buf = new byte[4];
+ BinaryPrimitives.WriteUInt32LittleEndian(buf, value);
+ Record(key, buf);
+ }
+
+ Record("%%header_begin", []);
+ U32("%%version", 1);
+ U32("%%cols", (uint)columnPoints.Length);
+ U32("%%rows", 1);
+ if (transform is { Length: 16 } m)
+ {
+ byte[] matrixBytes = new byte[128];
+ for (int i = 0; i < 16; i++)
+ BinaryPrimitives.WriteDoubleLittleEndian(matrixBytes.AsSpan(i * 8, 8), m[i]);
+ Record("%%transform", matrixBytes);
+ }
+ U32("%%properties", 0x01);
+ Record("%%header_end", []);
+
+ long dataStart = ms.Position + columnPoints.Length * 8;
+ int blockSize = 1 + (pointValid ? 12 : 0);
+ Span u64 = stackalloc byte[8];
+ for (int c = 0; c < columnPoints.Length; c++)
+ {
+ BinaryPrimitives.WriteInt64LittleEndian(u64, dataStart + c * blockSize);
+ ms.Write(u64);
+ }
+ Span record = stackalloc byte[12];
+ foreach (var point in columnPoints)
+ {
+ ms.Write([pointValid ? (byte)0x80 : (byte)0x00]); // one row, most significant bit first
+ if (!pointValid) continue;
+ BinaryPrimitives.WriteSingleLittleEndian(record[0..], point.X);
+ BinaryPrimitives.WriteSingleLittleEndian(record[4..], point.Y);
+ BinaryPrimitives.WriteSingleLittleEndian(record[8..], point.Z);
+ ms.Write(record);
+ }
+ return ms.ToArray();
+ }
+
+ private static string PtgIndex(TempDirectory dir)
+ {
+ string folder = Path.Combine(dir.Root, "Scans");
+ Directory.CreateDirectory(folder);
+ File.WriteAllBytes(Path.Combine(folder, "a.ptg"), PtgChunk([(1, 2, 3), (4, 5, 6)]));
+ File.WriteAllBytes(Path.Combine(folder, "b.ptg"), PtgChunk([(7, 8, 9)]));
+ string index = "PTG index file\n--------------\nScans\\a.ptg\nScans\\b.ptg\n";
+ return dir.Write("site.ptg", Encoding.ASCII.GetBytes(index));
+ }
+
+ private static void AssertNoErrors(SceneDocument scene)
+ {
+ var errors = scene.Validate().Where(d => d.Severity == SceneSeverity.Error).ToList();
+ Assert.True(errors.Count == 0, string.Join("; ", errors.Select(e => $"{e.Code}: {e.Message}")));
+ }
+
+ [Fact]
+ public void Read_Xyz_File_Produces_A_Valid_Scene()
+ {
+ using var dir = new TempDirectory();
+ string path = XyzFile(dir, 3);
+
+ var result = PclSceneReader.Read(path);
+
+ Assert.Equal(1, result.ScanCount);
+ Assert.Equal(1, result.ScansWithPoints);
+ Assert.Equal(3, result.PointCount);
+ Assert.Equal(1.0, result.MetresPerUnit);
+ Assert.Empty(result.Diagnostics);
+
+ SceneDocument scene = result.Document;
+ Assert.Equal(SceneDocument.DocumentKind, scene.Kind);
+ Assert.Equal(SceneDocument.CurrentFormat, scene.Format);
+ Assert.Equal("cloud.xyz", scene.Title);
+ AssertNoErrors(scene);
+
+ SceneModel model = Assert.Single(scene.Models);
+ Assert.Equal("cloud.xyz", model.Key);
+ Assert.Equal("cloud.xyz", model.Name);
+ Assert.Equal("xyz", model.SourceFormat);
+ Assert.Equal(path, model.Path);
+ Assert.StartsWith("PclIO.Scene ", model.Producer);
+
+ Assert.Equal(2, scene.Elements.Count);
+ SceneElement root = scene.Elements[0];
+ Assert.Equal(SceneNodeKind.Model, root.Kind);
+ Assert.Null(root.SourceId);
+ SceneElement scan = scene.Elements[1];
+ Assert.Equal(SceneNodeKind.Element, scan.Kind);
+ Assert.Equal(root.Id, scan.ParentId);
+ Assert.Equal("Point Cloud", scan.Category);
+ Assert.Equal("xyz", scan.TypeName);
+
+ // The frozen identity derivation: the element's SourceId is the engine's scan id.
+ using var document = PclFile.Open(path);
+ Assert.Equal(document.Scans[0].Id, scan.SourceId);
+
+ SceneGeometry geometry = Assert.Single(scene.Geometries);
+ Assert.Equal(SceneTopology.Points, geometry.Topology);
+ Assert.Empty(geometry.Indices);
+ Assert.Equal(3, geometry.Vertices.Count);
+ Assert.Equal(new Vector3d(0, 0, 0), geometry.Vertices[0]);
+ Assert.Equal(new Vector3d(2, 4, 6), geometry.Vertices[2]);
+ Assert.Null(geometry.Normals);
+
+ SceneInstance instance = Assert.Single(scene.Instances);
+ Assert.Equal(scan.Id, instance.ElementId);
+ Assert.Equal(geometry.Id, instance.GeometryId);
+ Assert.Null(instance.Transform);
+ Assert.Null(instance.Color);
+ }
+
+ [Fact]
+ public void ModelKey_Override_And_Validation()
+ {
+ using var dir = new TempDirectory();
+ string path = XyzFile(dir, 1);
+
+ var result = PclSceneReader.Read(path, new PclSceneOptions { ModelKey = "Site#1" });
+ Assert.Equal("Site#1", result.Document.Models[0].Key);
+
+ Assert.Throws(() => PclSceneReader.Read(path, new PclSceneOptions { ModelKey = "" }));
+ Assert.Throws(() => PclSceneReader.Read(""));
+ }
+
+ [Fact]
+ public void Read_Document_Overload_Derives_The_Key_From_The_File_Path()
+ {
+ using var dir = new TempDirectory();
+ string path = XyzFile(dir, 2);
+
+ using var document = PclFile.Open(path);
+ var result = PclSceneReader.Read(document);
+ Assert.Equal("cloud.xyz", result.Document.Models[0].Key);
+ Assert.Null(result.Document.Models[0].Path);
+ Assert.Equal(2, result.PointCount);
+
+ var named = PclSceneReader.Read(document, new PclSceneOptions { ModelKey = "k" });
+ Assert.Equal("k", named.Document.Models[0].Key);
+
+ Assert.Throws(() => PclSceneReader.Read((PclDocument)null!));
+ }
+
+ [Fact]
+ public void Colours_And_Intensities_Are_Reported_Dropped()
+ {
+ using var dir = new TempDirectory();
+ string path = PtsFileWithChannels(dir);
+
+ var result = PclSceneReader.Read(path);
+
+ Assert.Equal(2, result.PointCount);
+ Assert.Contains(result.Diagnostics, d => d.Severity == SceneSeverity.Info && d.Code == "colours-dropped");
+ Assert.Contains(result.Diagnostics, d => d.Severity == SceneSeverity.Info && d.Code == "intensities-dropped");
+ Assert.All(result.Document.Instances, i => Assert.Null(i.Color));
+ AssertNoErrors(result.Document);
+ }
+
+ [Fact]
+ public void MaxPoints_Caps_The_Scene_And_Reports_It()
+ {
+ using var dir = new TempDirectory();
+ string path = XyzFile(dir, 10);
+
+ var capped = PclSceneReader.Read(path, new PclSceneOptions { MaxPoints = 4 });
+ Assert.Equal(4, capped.PointCount);
+ var diagnostic = Assert.Single(capped.Diagnostics, d => d.Code == "points-capped");
+ Assert.Equal(SceneSeverity.Warning, diagnostic.Severity);
+ Assert.Equal(4, capped.Document.Geometries[0].Vertices.Count);
+
+ var zero = PclSceneReader.Read(path, new PclSceneOptions { MaxPoints = 0 });
+ Assert.Equal(0, zero.PointCount);
+ Assert.Equal(0, zero.ScansWithPoints);
+ Assert.Empty(zero.Document.Geometries);
+ Assert.Empty(zero.Document.Instances);
+ // Scans skipped because of the cap are reported by points-capped alone, not as empty scans.
+ Assert.Contains(zero.Diagnostics, d => d.Code == "points-capped");
+ Assert.DoesNotContain(zero.Diagnostics, d => d.Code == "empty-scan");
+ AssertNoErrors(zero.Document);
+
+ Assert.Throws(() => new PclSceneOptions { MaxPoints = -1 });
+ }
+
+ [Fact]
+ public void A_Scan_That_Yields_No_Points_Is_Reported_Empty()
+ {
+ using var dir = new TempDirectory();
+ string path = dir.Write("empty.ptg", PtgChunk([(0, 0, 0)], pointValid: false));
+
+ var result = PclSceneReader.Read(path);
+
+ Assert.Equal(1, result.ScanCount);
+ Assert.Equal(0, result.ScansWithPoints);
+ Assert.Equal(0, result.PointCount);
+ Assert.Empty(result.Document.Geometries);
+ var diagnostic = Assert.Single(result.Diagnostics, d => d.Code == "empty-scan");
+ Assert.Equal(SceneSeverity.Info, diagnostic.Severity);
+ AssertNoErrors(result.Document);
+ }
+
+ [Fact]
+ public void SubsampleStep_Thins_The_Points()
+ {
+ using var dir = new TempDirectory();
+ string path = XyzFile(dir, 10);
+
+ var result = PclSceneReader.Read(path, new PclSceneOptions { SubsampleStep = 2 });
+
+ Assert.Equal(5, result.PointCount);
+ Assert.Throws(() => new PclSceneOptions { SubsampleStep = 0 });
+ }
+
+ [Fact]
+ public void MetresPerUnit_Scales_The_Positions()
+ {
+ using var dir = new TempDirectory();
+ string path = XyzFile(dir, 2);
+
+ var result = PclSceneReader.Read(path, new PclSceneOptions { MetresPerUnit = 0.5 });
+
+ Assert.Equal(0.5, result.MetresPerUnit);
+ Assert.Equal(new Vector3d(0.5, 1, 1.5), result.Document.Geometries[0].Vertices[1]);
+ Assert.Throws(() => new PclSceneOptions { MetresPerUnit = 0 });
+ Assert.Throws(() => new PclSceneOptions { MetresPerUnit = double.NaN });
+ }
+
+ [Fact]
+ public void MultiScan_Ptg_Index_Becomes_One_Element_Per_Scan()
+ {
+ using var dir = new TempDirectory();
+ string path = PtgIndex(dir);
+
+ var result = PclSceneReader.Read(path);
+
+ Assert.Equal(2, result.ScanCount);
+ Assert.Equal(2, result.ScansWithPoints);
+ Assert.Equal(3, result.PointCount);
+ Assert.Equal("ptg", result.Document.Models[0].SourceFormat);
+
+ SceneElement root = result.Document.Elements[0];
+ Assert.Equal(3, result.Document.Elements.Count);
+ Assert.Equal(["scan-0", "scan-1"], result.Document.Elements.Skip(1).Select(e => e.SourceId));
+ Assert.All(result.Document.Elements.Skip(1), e => Assert.Equal(root.Id, e.ParentId));
+ Assert.Equal(2, result.Document.Geometries.Count);
+ Assert.Equal(2, result.Document.Instances.Count);
+
+ // Scan properties are text properties of the element's set.
+ SceneElement first = result.Document.Elements[1];
+ int setId = Assert.Single(first.PropertySetIds);
+ ScenePropertySet set = result.Document.PropertySets.Single(s => s.Id == setId);
+ Assert.Contains(set.Properties, p => p.Name == "Columns" && p.Value.Text == "2");
+ Assert.All(set.Properties, p => Assert.Equal(SceneValueKind.Text, p.Value.Kind));
+ AssertNoErrors(result.Document);
+ }
+
+ [Fact]
+ public void Ptg_Scanner_Pose_Is_Baked_Into_The_Positions()
+ {
+ using var dir = new TempDirectory();
+ double[] matrix =
+ [
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 10, 20, 30, 1,
+ ];
+ string path = dir.Write("posed.ptg", PtgChunk([(1, 0, 0)], matrix));
+
+ var result = PclSceneReader.Read(path);
+
+ Assert.Equal(new Vector3d(11, 20, 30), result.Document.Geometries[0].Vertices[0]);
+ }
+
+ [Fact]
+ public void Normals_Are_Kept_When_Every_Point_Has_One()
+ {
+ using var dir = new TempDirectory();
+ string path = PlyFileWithNormals(dir);
+
+ var result = PclSceneReader.Read(path);
+
+ SceneGeometry geometry = Assert.Single(result.Document.Geometries);
+ Assert.NotNull(geometry.Normals);
+ Assert.Equal(2, geometry.Normals!.Count);
+ Assert.Equal(new Vector3d(0, 0, 1), geometry.Normals[0]);
+ AssertNoErrors(result.Document);
+ }
+
+ [Fact]
+ public void SceneJson_Roundtrip_Keeps_The_Points()
+ {
+ using var dir = new TempDirectory();
+ string path = XyzFile(dir, 3);
+ var result = PclSceneReader.Read(path);
+
+ string scenePath = dir.PathOf("cloud.scene.json");
+ SceneJson.Save(result.Document, scenePath);
+ SceneDocument read = SceneJson.Load(scenePath);
+
+ AssertNoErrors(read);
+ Assert.Equal(result.Document.Geometries[0].Vertices, read.Geometries[0].Vertices);
+ Assert.Equal("cloud.xyz", read.Models[0].Key);
+ }
+}
diff --git a/tests/PclIO.Tests/CliTests.cs b/tests/PclIO.Tests/CliTests.cs
index 2d52e11..57f010a 100644
--- a/tests/PclIO.Tests/CliTests.cs
+++ b/tests/PclIO.Tests/CliTests.cs
@@ -290,6 +290,7 @@ public void A_Negative_Limit_Is_Reported_Not_Mistaken_For_An_Option()
[InlineData("xyz")]
[InlineData("pts")]
[InlineData("json")]
+ [InlineData("scene")]
public void Export_Writes_The_Requested_Format(string format)
{
using var dir = new TempDirectory();
@@ -301,7 +302,7 @@ public void Export_Writes_The_Requested_Format(string format)
Assert.Equal(Program.ExitOk, result.Exit);
Assert.Contains(format == "json" ? "Exported 0 points" : "Exported 3 points", result.Out);
Assert.True(new FileInfo(output).Length > 0);
- Assert.Equal(format == "las" ? (byte)'L' : format == "json" ? (byte)'{' : (byte)(format == "pts" ? '3' : '1'), File.ReadAllBytes(output)[0]);
+ Assert.Equal(format == "las" ? (byte)'L' : format is "json" or "scene" ? (byte)'{' : (byte)(format == "pts" ? '3' : '1'), File.ReadAllBytes(output)[0]);
Assert.Equal([Path.GetFileName(output), Path.GetFileName(input)], Directory.GetFiles(dir.Root).Select(Path.GetFileName).Order(StringComparer.Ordinal));
}
@@ -349,6 +350,52 @@ public void Export_Json_With_A_Limit_Includes_Sample_Points_And_Rejects_Step()
Assert.Equal(Program.ExitUsage, Run("export", input, dir.PathOf("two.json"), "--no-transform").Exit);
}
+ [Fact]
+ public void Export_Scene_Writes_An_Ioscene_Document()
+ {
+ using var dir = new TempDirectory();
+ string input = PointsRcs(dir);
+ string output = dir.PathOf("out.scene.json");
+
+ var result = Run("export", input, output);
+
+ Assert.Equal(Program.ExitOk, result.Exit);
+ Assert.Contains("Exported 3 points to IOScene JSON", result.Out);
+ // Per-point channels that IOScene 0.1.0 does not hold are reported on standard error.
+ Assert.Contains("colours-dropped", result.Err);
+ Assert.Contains("intensities-dropped", result.Err);
+ IOScene.SceneDocument scene = IOScene.SceneJson.Load(output);
+ Assert.Equal("ioscene", scene.Kind);
+ Assert.Equal(3, scene.Geometries[0].Vertices.Count);
+ Assert.Equal("rcs", scene.Models[0].SourceFormat);
+ }
+
+ [Fact]
+ public void Export_Scene_Format_Option_And_Limit()
+ {
+ using var dir = new TempDirectory();
+ string input = PointsRcs(dir);
+ string output = dir.PathOf("out.dat");
+
+ var result = Run("export", input, output, "--format", "scene", "--limit", "2");
+
+ Assert.Equal(Program.ExitOk, result.Exit);
+ IOScene.SceneDocument scene = IOScene.SceneJson.Load(output);
+ Assert.Equal(2, scene.Geometries[0].Vertices.Count);
+ Assert.Contains("points-capped", result.Err);
+ }
+
+ [Fact]
+ public void Export_Scene_Rejects_No_Transform()
+ {
+ using var dir = new TempDirectory();
+
+ var result = Run("export", PointsRcs(dir), dir.PathOf("out.scene.json"), "--no-transform");
+
+ Assert.Equal(Program.ExitUsage, result.Exit);
+ Assert.False(File.Exists(dir.PathOf("out.scene.json")));
+ }
+
[Fact]
public void Export_Refuses_To_Overwrite_The_Input()
{
diff --git a/tests/PclIO.Tests/FormatTests.cs b/tests/PclIO.Tests/FormatTests.cs
index c3e3514..9048dd9 100644
--- a/tests/PclIO.Tests/FormatTests.cs
+++ b/tests/PclIO.Tests/FormatTests.cs
@@ -6751,7 +6751,7 @@ public void Cc_Bin_Reads_Intensity_After_Scalar_Display_Metadata(bool withPalett
];
byte[] paletteSteps = new byte[18 + 4 + 2 * 19];
paletteSteps[18] = 2;
- palette = [..nameAndId, ..paletteSteps];
+ palette = [.. nameAndId, .. paletteSteps];
}
string path = dir.Write("two_scalars.bin", [..bytes.AsSpan(0, fieldStart), ..firstField, ..display,
diff --git a/tests/PclIO.Tests/RepositoryHygieneTests.cs b/tests/PclIO.Tests/RepositoryHygieneTests.cs
index dd874ea..3ddb410 100644
--- a/tests/PclIO.Tests/RepositoryHygieneTests.cs
+++ b/tests/PclIO.Tests/RepositoryHygieneTests.cs
@@ -9,8 +9,8 @@ namespace PclIO.Tests;
/// Keeps private data and proprietary material out of the repository. The files checked are the ones git tracks (or
/// would track), or every file outside build output when git is not available. The patterns are assembled from pieces at
-/// run time so that this file does not contain a literal that would match itself. It also checks that the shipped projects
-/// reference no package.
+/// run time so that this file does not contain a literal that would match itself. It also checks that the engine and the
+/// CLI reference no package, and the scene adapter only the neutral scene contract.
public sealed class RepositoryHygieneTests
{
private const long MaxFileBytes = 1024 * 1024;
@@ -63,9 +63,10 @@ private static readonly (string Label, Regex Pattern)[] ForbiddenWording =
("assistant or generator mention", Rx(
"cla" + "ude|anthr" + "opic|co-auth" + "ored-by|generated " + "with|" + @"\bai[\s-]+assist" + "|chat" + "gpt|open" + @"ai\b")),
- // Sibling projects and other implementations are not referred to.
+ // Sibling projects and other implementations are not referred to. IOScene is the neutral scene contract the
+ // adapter depends on, so it is named; the viewer and the sibling engines are not.
("other project or implementation", Rx(
- @"\b(?:Rvt|Pla|Tdb|Nwc|Dwg|Ifc)" + @"IO\b|\bIO(?:Sc" + "ene|Vie" + @"wer)\b|lib" + "e57|cloud" + "compare|" + @"\bpd" + @"al\b|\bla" + @"spy\b"
+ @"\b(?:Rvt|Pla|Tdb|Nwc|Dwg|Ifc)" + @"IO\b|\bIOVie" + @"wer\b|lib" + "e57|cloud" + "compare|" + @"\bpd" + @"al\b|\bla" + @"spy\b"
+ "|pye" + "57|open" + "3d|las" + "tools|lib" + "las|pot" + "reeconverter")),
];
@@ -383,11 +384,11 @@ bool IsCommitter(string name, string address) =>
}
[SkippableFact]
- public void The_Packages_Have_No_Dependencies_On_Other_Packages()
+ public void The_Engine_And_Cli_Have_No_Package_Dependencies()
{
string root = FindRepoRoot();
- // Neither shipped project references a package; the only package any of them gets is the build-time one that
+ // The engine and the CLI reference no package; the only package they get is the build-time one that
// Directory.Build.props adds with PrivateAssets, which never reaches the consumer.
foreach (string project in new[] { "src/PclIO/PclIO.csproj", "src/PclIO.Cli/PclIO.Cli.csproj" })
{
@@ -395,6 +396,10 @@ public void The_Packages_Have_No_Dependencies_On_Other_Packages()
Assert.Empty(references);
}
+ // The scene adapter is the only shipped project with a package dependency, and it is the neutral scene contract.
+ var adapter = XDocument.Load(Path.Combine(root, "src/PclIO.Scene/PclIO.Scene.csproj")).Descendants("PackageReference").ToList();
+ Assert.Equal(["IOScene"], adapter.Select(r => (string?)r.Attribute("Include")));
+
var shared = XDocument.Load(Path.Combine(root, "Directory.Build.props")).Descendants("PackageReference");
Assert.All(shared, r => Assert.Equal("all", (string?)r.Attribute("PrivateAssets")));
}
diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs
index 6413dcf..303a271 100644
--- a/tests/PclIO.Tests/SyntheticFixtures.cs
+++ b/tests/PclIO.Tests/SyntheticFixtures.cs
@@ -2414,13 +2414,21 @@ public static (string cloudJs, byte[] rBin, byte[] rHrc) CreateSyntheticPotree1x
["octreeDir"] = "data",
["boundingBox"] = new Dictionary
{
- ["lx"] = offset.X, ["ly"] = offset.Y, ["lz"] = offset.Z,
- ["ux"] = offset.X + 100, ["uy"] = offset.Y + 100, ["uz"] = offset.Z + 100
+ ["lx"] = offset.X,
+ ["ly"] = offset.Y,
+ ["lz"] = offset.Z,
+ ["ux"] = offset.X + 100,
+ ["uy"] = offset.Y + 100,
+ ["uz"] = offset.Z + 100
},
["tightBoundingBox"] = new Dictionary
{
- ["lx"] = minX, ["ly"] = minY, ["lz"] = minZ,
- ["ux"] = maxX, ["uy"] = maxY, ["uz"] = maxZ
+ ["lx"] = minX,
+ ["ly"] = minY,
+ ["lz"] = minZ,
+ ["ux"] = maxX,
+ ["uy"] = maxY,
+ ["uz"] = maxZ
},
["pointAttributes"] = attrs,
["spacing"] = 0.05,
diff --git a/tools/pack-release.ps1 b/tools/pack-release.ps1
index 76b306d..071d409 100644
--- a/tools/pack-release.ps1
+++ b/tools/pack-release.ps1
@@ -29,6 +29,40 @@ function Invoke-DotNet {
if ($LASTEXITCODE -ne 0) { throw "dotnet $($args -join ' ') failed with exit code $LASTEXITCODE" }
}
+function Assert-AdapterNuspec([string]$NuspecPath, [string]$EngineId, [string]$Version) {
+ $dependencies = @(([xml](Get-Content -LiteralPath $NuspecPath -Raw)).SelectNodes("//*[local-name()='dependency']"))
+ # (a) Guards the PinProjectReferencesExactly target, which hooks a private NuGet target and would fail silently if an SDK renamed it.
+ $engine = @($dependencies | Where-Object { $_.GetAttribute('id') -eq $EngineId })
+ if ($engine.Count -eq 0) { throw "$NuspecPath has no dependency on $EngineId." }
+ foreach ($dependency in $engine) {
+ if ($dependency.GetAttribute('version') -cne "[$Version]") {
+ throw "$NuspecPath depends on $EngineId '$($dependency.GetAttribute('version'))'; it must be exactly '[$Version]'."
+ }
+ }
+ # (b) Replaces the NU5104 protection that the IOScene range switches off: no adapter built on a preview contract reaches nuget.org.
+ $scene = @($dependencies | Where-Object { $_.GetAttribute('id') -eq 'IOScene' })
+ if ($scene.Count -eq 0) { throw "$NuspecPath has no dependency on IOScene." }
+ foreach ($dependency in $scene) {
+ $range = $dependency.GetAttribute('version')
+ $lower = $range.TrimStart('[', '(').Split(',')[0].Trim()
+ if ($lower -eq '' -or $lower.Contains('-')) {
+ throw "$NuspecPath depends on IOScene '$range', whose lower bound is missing or a prerelease; release IOScene first and require its stable version."
+ }
+ }
+ # (c) nuget.org refuses a dependency bound with metadata, or one whose prerelease label has one part and does not start
+ # with a letter (NuGetGallery ManifestValidator.ValidateDependencyVersion); dotnet pack accepts both, so only the push would fail.
+ foreach ($dependency in $dependencies) {
+ $range = $dependency.GetAttribute('version')
+ foreach ($bound in $range.Trim('[', ']', '(', ')').Split(',')) {
+ $bound = $bound.Trim()
+ $label = if ($bound.Contains('-')) { $bound.Substring($bound.IndexOf('-') + 1) } else { '' }
+ if ($bound.Contains('+') -or ($label -ne '' -and -not $label.Contains('.') -and $label -notmatch '^[a-z][0-9a-z-]*$')) {
+ throw "$NuspecPath depends on $($dependency.GetAttribute('id')) '$range', whose bound '$bound' nuget.org refuses."
+ }
+ }
+ }
+}
+
function New-Zip([string]$SourceDir, [string]$ZipPath) {
if (Test-Path -LiteralPath $ZipPath) { Remove-Item -LiteralPath $ZipPath }
Compress-Archive -Path (Join-Path $SourceDir '*') -DestinationPath $ZipPath
@@ -72,10 +106,23 @@ Copy-Item (Join-Path $root 'LICENSE') $cli10Stage
Copy-Item (Join-Path $root 'THIRD-PARTY-NOTICES.md') $cli10Stage
New-Zip $cli10Stage (Join-Path $Output "PclIO-Cli-$version-net10.0.zip")
-# 4. NuGet packages
+# 4. NuGet packages (pack runs with --no-build, and the publish steps build only PclIO and PclIO.Cli)
+Write-Host "Building the solution..."
+Invoke-DotNet build (Join-Path $root 'PclIO.slnx') -c Release
Write-Host "Packing NuGet packages..."
Invoke-DotNet pack (Join-Path $root 'PclIO.slnx') -c Release --no-build -o $Output
+Write-Host "Checking PclIO.Scene dependencies..."
+Add-Type -AssemblyName System.IO.Compression.FileSystem
+$adapterNuspec = Join-Path $stage 'PclIO.Scene.nuspec'
+$adapterPackage = [System.IO.Compression.ZipFile]::OpenRead((Join-Path $Output "PclIO.Scene.$version.nupkg"))
+try {
+ $entry = @($adapterPackage.Entries | Where-Object { $_.FullName -notlike '*/*' -and $_.Name -like '*.nuspec' })[0]
+ [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $adapterNuspec, $true)
+}
+finally { $adapterPackage.Dispose() }
+Assert-AdapterNuspec $adapterNuspec 'PclIO' $version
+
# 5. Source code archive
Write-Host "Creating source code archive..."
$sourceZip = Join-Path $Output "PclIO-$version-source.zip"